id3 frame id3 frame id3 frameid id impl new id3 frameimpl id id3_frame id3_frame id3_frameid _impl id3_frameimpl id3 frame id3 frame const id3 frame frame impl new id3 frameimpl frame id3_frame id3_frame id3_frame _impl id3_frameimpl id3 frame id3 frame delete impl id3_frame id3_frame _impl void id3 frame clear impl clear id3_frame _impl bool id3 frame setid id3 frameid id return impl setid id id3_frame id3_frameid _impl id3 frameid id3 frame getid const return impl getid id3_frameid id3_frame _impl id3 field id3 frame get field id3 fieldid field name const return impl get field field name id3_field id3_frame getfield id3_fieldid fieldname _impl getfield fieldname size t id3 frame num fields const return impl num fields size_t id3_frame numfields _impl numfields const char id3 frame get description const return impl get description id3_frame getdescription _impl getdescription const char id3 frame get description id3 frameid id return id3 frameimpl get description id id3_frame getdescription id3_frameid id3_frameimpl getdescription const char id3 frame get textid const return impl get textid id3_frame gettextid _impl gettextid id3 frame id3 frame operator const id3 frame r frame if this r frame impl r frame return this id3_frame id3_frame id3_frame rframe rframe _impl rframe bool id3 frame has changed const return impl has changed id3_frame haschanged _impl haschanged bool id3 frame parse id3 reader reader return impl parse reader id3_frame id3_reader _impl void id3 frame render id3 writer writer const impl render writer id3_frame id3_writer _impl size t id3 frame size return impl size size_t id3_frame _impl bool id3 frame contains id3 fieldid id const return impl contains id id3_frame id3_fieldid _impl bool id3 frame set spec id3 v2spec spec return impl set spec spec id3_frame setspec id3_v2spec _impl setspec id3 v2spec id3 frame get spec const return impl get spec id3_v2spec id3_frame getspec _impl getspec bool id3 frame set compression bool b return impl set compression b id3_frame setcompression _impl setcompression bool id3 frame get compression const return impl get compression id3_frame getcompression _impl getcompression size t id3 frame get data size const return impl get data size size_t id3_frame getdatasize _impl getdatasize bool id3 frame set encryptionid uchar id return impl set encryptionid id id3_frame setencryptionid _impl setencryptionid uchar id3 frame get encryptionid const return impl get encryptionid id3_frame getencryptionid _impl getencryptionid bool id3 frame set groupingid uchar id return impl set groupingid id id3_frame setgroupingid _impl setgroupingid uchar id3 frame get groupingid const return impl get groupingid id3_frame getgroupingid _impl getgroupingid id3 frame create iterator return new iterator impl impl id3_frame createiterator iteratorimpl _impl id3 frame create iterator const return new const iterator impl impl id3_frame createiterator constiteratorimpl _impl id3 field id3 frame field id3 fieldid field name const return this get field field name id3_field id3_frame id3_fieldid fieldname getfield fieldname pos type set cur pos type cur return reader set cur mid this get beg cur this get end pos_type setcur pos_type _reader setcur getbeg getend size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type pos type set cur pos type cur return reader set cur mid this get beg cur this get end pos_type setcur pos_type _reader setcur getbeg getend size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type void io windowed reader set window pos type beg size type size id3d notice windowed reader set window beg size this get beg size pos type cur this get cur reset the end marker so as to avoid errors this set end reader get end set the beginning marker this set beg beg since the characters might be more than a byte in size we need to manually get all the chars to set the window appropriately this set cur beg id3d notice windowed reader set window after set cur beg cur this get cur this skip chars size id3d notice windowed reader set window after skip chars cur this get cur this set end this get cur id3d notice windowed reader set window beg cur end this get beg this get cur this get end reset the stream this set cur cur windowedreader setwindow pos_type size_type id3d_notice windowedreader setwindow getbeg pos_type getcur setend _reader getend setbeg setcur id3d_notice windowedreader setwindow setcur getcur skipchars id3d_notice windowedreader setwindow skipchars getcur setend getcur id3d_notice windowedreader setwindow getbeg getcur getend setcur id3 reader pos type io windowed reader set beg pos type beg make sure the position we want to set to isn t past the current end position or the superclass s beginning position if beg this get end beg reader get beg beg beg else if beg this get end id3d warning windowed reader set beg failed beg end beg this get end else id3d warning windowed reader set beg failed beg beg beg this get beg return beg id3_reader pos_type windowedreader setbeg pos_type getend _reader getbeg _beg getend id3d_warning windowedreader setbeg _end getend id3d_warning windowedreader setbeg _beg getbeg _beg id3 reader pos type io windowed reader set end pos type end make sure the position we want to set to isn t beforen the current beginning position or the superclass s end position if this get beg end end reader get end end end else id3d warning windowed reader set end failed end end id3d warning windowed reader set end failed beg this get beg id3d warning windowed reader set end failed super end reader get end return end id3_reader pos_type windowedreader setend pos_type getbeg _reader getend _end id3d_warning windowedreader setend id3d_warning windowedreader setend getbeg id3d_warning windowedreader setend _reader getend _end id3 reader int type io windowed reader read char int type ch end of reader if this in window ch reader read char else id3d warning io windowed reader read char not in window pos this get cur window this get beg this get end return ch id3_reader int_type windowedreader readchar int_type end_of_reader inwindow _reader readchar id3d_warning windowedreader readchar getcur getbeg getend id3 reader int type io windowed reader peek char int type ch end of reader if this in window ch reader peek char return ch id3_reader int_type windowedreader peekchar int_type end_of_reader inwindow _reader peekchar id3 reader size type io windowed reader read chars char type buf size type len pos type cur this get cur size type size 0 if this in window cur size reader read chars buf min size type len end cur return size id3_reader size_type windowedreader readchars char_type size_type pos_type getcur size_type inwindow _reader readchars size_type _end size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type id3 reader size type io char reader read chars char type buf size type len size type num chars 0 id3d notice char reader read chars len len for num chars len num chars if this at end break char type ch this read char if buf null buf num chars ch id3d notice char reader read chars num chars len return num chars id3_reader size_type charreader readchars char_type size_type size_type numchars id3d_notice charreader readchars numchars numchars atend char_type readchar numchars id3d_notice charreader readchars numchars numchars size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type id3 writer int type io unsynced writer write char char type ch if last 0xff ch 0x00 ch 0xe0 writer write char 0 numsyncs last writer write char ch return last id3_writer int_type unsyncedwriter writechar char_type _last _writer writechar _numsyncs _last _writer writechar _last void io unsynced writer flush if last 0xff last writer write char 0 numsyncs writer flush unsyncedwriter _last _last _writer writechar _numsyncs _writer io unsynced writer write chars const char type buf size type len pos type beg this get cur id3d notice unsynced writer write chars len len for size t i 0 i len i if this at end break this write char buf i size type num chars this get cur beg id3d notice char writer write chars num chars num chars return num chars unsyncedwriter writechars char_type size_type pos_type getcur id3d_notice unsyncedwriter writechars size_t atend writechar size_type numchars getcur id3d_notice charwriter writechars numchars numchars numchars size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type void io compressed writer flush if data size 0 return const char type data reinterpret cast const char type data data size type data size data size origsize data size the zlib documentation specifies that the destination size needs to be an unsigned long at least 0 1 larger than the source buffer plus 12 bytes unsigned long new data size data size data size 10 12 char type new data new char type new data size if compress new data new data size data data size z ok log this id3d warning io compressed writer error compressing writer write chars data data size else if new data size data size id3d notice io compressed writer compressed size new data size original size data size writer write chars new data new data size else id3d notice io compressed writer no compression compressed size new data size original size data size writer write chars data data size delete new data data erase compressedwriter _data char_type reinterpret_cast char_type _data size_type datasize _data _origsize datasize newdatasize datasize datasize char_type newdata char_type newdatasize newdata newdatasize datasize z_ok id3d_warning compressedwriter _writer writechars datasize newdatasize datasize id3d_notice compressedwriter newdatasize datasize _writer writechars newdata newdatasize id3d_notice compressedwriter newdatasize datasize _writer writechars datasize newdata _data io compressed writer write chars const char type buf size type len id3d notice io compressed writer writing chars len data append buf len return len compressedwriter writechars char_type size_type id3d_notice compressedwriter _data virtual int type peek char if this at end return string cur return end of reader int_type peekchar atend _string _cur end_of_reader size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type virtual size type read chars char type buf size type len size type size min unsigned int len unsigned int string size cur string copy reinterpret cast string value type buf size cur cur size return size size_type readchars char_type size_type size_type _string _cur _string reinterpret_cast value_type _cur _cur virtual pos type get cur return cur pos_type getcur _cur virtual pos type get beg return 0 pos_type getbeg virtual pos type get end return string size pos_type getend _string virtual pos type set cur pos type pos pos type end this get end cur pos end pos end return cur pos_type setcur pos_type pos_type getend _cur _cur virtual bool at end return cur string size atend _cur _string virtual size type skip chars size type len size type size min unsigned int len unsigned int string size cur cur size return size size_type skipchars size_type size_type _string _cur _cur virtual int type peek char if this at end return string cur return end of reader int_type peekchar atend _string _cur end_of_reader size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type virtual size type read chars char type buf size type len size type size min unsigned int len unsigned int string size cur string copy reinterpret cast string value type buf size cur cur size return size size_type readchars char_type size_type size_type _string _cur _string reinterpret_cast value_type _cur _cur virtual pos type get cur return cur pos_type getcur _cur virtual pos type get beg return 0 pos_type getbeg virtual pos type get end return string size pos_type getend _string virtual pos type set cur pos type pos pos type end this get end cur pos end pos end return cur pos_type setcur pos_type pos_type getend _cur _cur virtual bool at end return cur string size atend _cur _string virtual size type skip chars size type len size type size min unsigned int len unsigned int string size cur cur size return size size_type skipchars size_type size_type _string _cur _cur virtual int type peek char if this at end return string cur return end of reader int_type peekchar atend _string _cur end_of_reader size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type virtual size type read chars char type buf size type len size type size min unsigned int len unsigned int string size cur string copy reinterpret cast b string value type buf size cur cur size return size size_type readchars char_type size_type size_type _string _cur _string reinterpret_cast bstring value_type _cur _cur virtual pos type get cur return cur pos_type getcur _cur virtual pos type get beg return 0 pos_type getbeg virtual pos type get end return string size pos_type getend _string virtual pos type set cur pos type pos pos type end this get end cur pos end pos end return cur pos_type setcur pos_type pos_type getend _cur _cur virtual bool at end return cur string size atend _cur _string virtual size type skip chars size type len size type size min unsigned int len unsigned int string size cur cur size return size size_type skipchars size_type size_type _string _cur _cur virtual int type peek char if this at end return string cur return end of reader int_type peekchar atend _string _cur end_of_reader size type read chars char buf size type len return this read chars char type buf len size_type readchars size_type readchars char_type virtual size type read chars char type buf size type len size type size min unsigned int len unsigned int string size cur string copy reinterpret cast b string value type buf size cur cur size return size size_type readchars char_type size_type size_type _string _cur _string reinterpret_cast bstring value_type _cur _cur virtual pos type get cur return cur pos_type getcur _cur virtual pos type get beg return 0 pos_type getbeg virtual pos type get end return string size pos_type getend _string virtual pos type set cur pos type pos pos type end this get end cur pos end pos end return cur pos_type setcur pos_type pos_type getend _cur _cur virtual bool at end return cur string size atend _cur _string virtual size type skip chars size type len size type size min unsigned int len unsigned int string size cur cur size return size size_type skipchars size_type size_type _string _cur _cur virtual size type write chars const char buf size type len string append reinterpret cast const string value type buf len return len size_type writechars size_type _string reinterpret_cast value_type size type write chars const char type buf size type len string append reinterpret cast const string value type buf len return len size_type writechars char_type size_type _string reinterpret_cast value_type pos type get cur return string size pos_type getcur _string virtual size type write chars const char buf size type len string append reinterpret cast const string value type buf len return len size_type writechars size_type _string reinterpret_cast value_type size type write chars const char type buf size type len string append reinterpret cast const string value type buf len return len size_type writechars char_type size_type _string reinterpret_cast value_type pos type get cur return string size pos_type getcur _string virtual size type write chars const char buf size type len string append reinterpret cast const b string value type buf len return len size_type writechars size_type _string reinterpret_cast bstring value_type size type write chars const char type buf size type len string append reinterpret cast const b string value type buf len return len size_type writechars char_type size_type _string reinterpret_cast bstring value_type pos type get cur return string size pos_type getcur _string virtual size type write chars const char buf size type len string append reinterpret cast const b string value type buf len return len size_type writechars size_type _string reinterpret_cast bstring value_type size type write chars const char type buf size type len string append reinterpret cast const b string value type buf len return len size_type writechars char_type size_type _string reinterpret_cast bstring value_type pos type get cur return string size pos_type getcur _string id3 reader int type io line feed reader read char if this at end return end of reader char type ch reader read char if ch 0x0d this peek char 0x0a id3d notice line feed reader read char found crlf at pos this get cur ch reader read char return ch id3_reader int_type linefeedreader readchar atend end_of_reader char_type _reader readchar peekchar id3d_notice linefeedreader readchar getcur _reader readchar id3 reader int type io unsynced reader read char if this at end return end of reader char type ch reader read char if ch 0xff this peek char 0x00 id3d notice unsynced reader read char found sync at pos this get cur reader read char return ch id3_reader int_type unsyncedreader readchar atend end_of_reader char_type _reader readchar peekchar id3d_notice unsyncedreader readchar getcur _reader readchar uncompressed new char type new size size type old size reader remaining bytes b string binary read binary reader old size int dw result uncompress uncompressed reinterpret cast luint new size reinterpret cast const uchar binary data old size if dw result z ok new size 0 this set buffer uncompressed new size _uncompressed char_type newsize size_type oldsize remainingbytes bstring readbinary oldsize dwresult _uncompressed reinterpret_cast newsize reinterpret_cast oldsize dwresult z_ok newsize setbuffer _uncompressed newsize io compressed reader compressed reader delete uncompressed compressedreader compressedreader _uncompressed virtual int type read char if this at end return end of reader char type ch this read chars ch 1 return ch int_type readchar atend end_of_reader char_type readchars virtual size type read chars char buf size type len return this read chars reinterpret cast char type buf len size_type readchars size_type readchars reinterpret_cast char_type virtual size type skip chars size type len const size type size 1024 char type bytes size size type remaining len while this at end remaining 0 remaining this read chars bytes remaining size remaining size return len remaining size_type skipchars size_type size_type char_type size_type atend readchars virtual size type remaining bytes pos type end this get end cur this get cur if end pos type 1 return size type 1 if end cur return end cur return 0 size_type remainingbytes pos_type getend getcur pos_type size_type virtual int type read char if this at end return end of reader char type ch this read chars ch 1 return ch int_type readchar atend end_of_reader char_type readchars virtual size type read chars char buf size type len return this read chars reinterpret cast char type buf len size_type readchars size_type readchars reinterpret_cast char_type virtual size type skip chars size type len const size type size 1024 char type bytes size size type remaining len while this at end remaining 0 remaining this read chars bytes remaining size remaining size return len remaining size_type skipchars size_type size_type char_type size_type atend readchars virtual size type remaining bytes pos type end this get end cur this get cur if end pos type 1 return size type 1 if end cur return end cur return 0 size_type remainingbytes pos_type getend getcur pos_type size_type virtual int type write char char type ch if this at end return end of writer this write chars ch 1 return ch int_type writechar char_type atend end_of_writer writechars virtual size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type virtual bool at end return this get cur this get end atend getcur getend virtual int type write char char type ch if this at end return end of writer this write chars ch 1 return ch int_type writechar char_type atend end_of_writer writechars virtual size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type virtual bool at end return this get cur this get end atend getcur getend void id3 fieldimpl set uint32 val this set integer val id3_fieldimpl setinteger uint32 id3 fieldimpl get const return this get integer id3_fieldimpl getinteger void id3 fieldimpl set integer uint32 val if this get type id3fty integer this clear integer val changed true id3_fieldimpl setinteger gettype id3fty_integer _integer _changed uint32 id3 fieldimpl get integer const uint32 val 0 if this get type id3fty integer val integer return val id3_fieldimpl getinteger gettype id3fty_integer _integer size t set const char buf size t size return this set reinterpret cast const uchar buf size size_t size_t reinterpret_cast void id3 fieldimpl render integer id3 writer writer const io writebe number writer integer this size id3_fieldimpl renderinteger id3_writer writebenumber _integer bool id3 fieldimpl parse integer id3 reader reader id3d notice id3 fieldimpl parse integer beg reader get beg id3d notice id3 fieldimpl parse integer cur reader get cur id3d notice id3 fieldimpl parse integer end reader get end bool success false if reader at end this clear size t fixed this size size t n bytes fixed 0 fixed sizeof uint32 this set io readbe number reader n bytes changed false success true return success id3_fieldimpl parseinteger id3_reader id3d_notice id3_fieldimpl parseinteger getbeg id3d_notice id3_fieldimpl parseinteger getcur id3d_notice id3_fieldimpl parseinteger getend atend size_t size_t nbytes readbenumber nbytes _changed size t id3 fieldimpl set const unicode t data size t size 0 if this get type id3fty textstring this get encoding id3te unicode data string text const char data ucslen data 2 size this settext i text return size size_t id3_fieldimpl unicode_t size_t gettype id3fty_textstring getencoding id3te_unicode settext_i size t id3 fieldimpl get unicode t buffer size t max length const size t length 0 if this get type id3fty textstring this get encoding id3te unicode buffer null max length 0 size t size this size length dami min max length size memcpy void buffer void text data length 2 if length max length buffer length null unicode return length size_t id3_fieldimpl unicode_t size_t maxlength size_t gettype id3fty_textstring getencoding id3te_unicode maxlength size_t maxlength _text maxlength null_unicode size t id3 fieldimpl get unicode t buffer size t max length size t item num const size t length 0 size t total items this get num text items if this get type id3fty textstring this get encoding id3te unicode buffer null max length 0 item num total items const unicode t text this get raw unicode text item item num if null text size t length dami min max length ucslen text memcpy buffer text length 2 if length max length buffer length null unicode return length size_t id3_fieldimpl unicode_t size_t maxlength size_t itemnum size_t size_t total_items getnumtextitems gettype id3fty_textstring getencoding id3te_unicode maxlength itemnum total_items unicode_t getrawunicodetextitem itemnum size_t maxlength maxlength null_unicode size t id3 fieldimpl add const unicode t data size t size 0 if this get type id3fty textstring this get encoding id3te unicode string text const char data ucslen data 2 size this addtext i text return size size_t id3_fieldimpl unicode_t size_t gettype id3fty_textstring getencoding id3te_unicode addtext_i const unicode t id3 fieldimpl get raw unicode text const const unicode t text null if this get type id3fty textstring this get encoding id3te unicode text unicode t text data return text unicode_t id3_fieldimpl getrawunicodetext unicode_t gettype id3fty_textstring getencoding id3te_unicode unicode_t _text const unicode t id3 fieldimpl get raw unicode text item size t index const const unicode t text null if this get type id3fty textstring this get encoding id3te unicode index this get num text items string unicode text 0 0 text unicode t unicode data for size t i 0 i index i text ucslen text 1 return text unicode_t id3_fieldimpl getrawunicodetextitem size_t unicode_t gettype id3fty_textstring getencoding id3te_unicode getnumtextitems _text unicode_t size_t size t id3 fieldimpl set const uchar data size t len size t size 0 if this get type id3fty binary data len b string str data len size dami min len this set binary str return size size_t id3_fieldimpl size_t size_t gettype id3fty_binary bstring setbinary const size t bytes 0 if this get type id3fty binary bytes dami min max bytes this size if null buffer bytes 0 memcpy buffer binary data bytes return bytes size_t gettype id3fty_binary max_bytes _binary const uchar id3 fieldimpl get raw binary const const uchar data null if this get type id3fty binary data binary data return data id3_fieldimpl getrawbinary gettype id3fty_binary _binary if this get type id3fty binary null info return file temp file fopen info rb if temp file null fseek temp file 0 seek end size t file size ftell temp file fseek temp file 0 seek set uchar buffer new uchar file size if buffer null fread buffer 1 file size temp file this set buffer file size delete buffer fclose temp file gettype id3fty_binary temp_file temp_file temp_file seek_end size_t filesize temp_file temp_file seek_set filesize filesize temp_file filesize temp_file const if this get type id3fty binary null info return size t size this size if size 0 file temp file fopen info wb if temp file null fwrite binary data 1 size temp file fclose temp file return gettype id3fty_binary size_t temp_file temp_file _binary temp_file temp_file size t id3 fieldimpl set binary b string data data to assign to this field size t size 0 if this get type id3fty binary this clear size t fixed fixed size size data size if fixed 0 binary data else binary assign data 0 dami min size fixed if size fixed binary append fixed size 0 size binary size changed true return size size_t id3_fieldimpl setbinary bstring size_t gettype id3fty_binary size_t _fixed_size _binary _binary _binary _binary _changed b string id3 fieldimpl get binary const b string data if this get type id3fty binary data binary return data bstring id3_fieldimpl getbinary bstring gettype id3fty_binary _binary void id3 fieldimpl render binary id3 writer writer const writer write chars this get raw binary this size id3_fieldimpl renderbinary id3_writer writechars getrawbinary bool id3 fieldimpl parse binary id3 reader reader copy the remaining bytes unless we re fixed length in which case copy the minimum of the remaining bytes vs the fixed length binary io read all binary reader return true id3_fieldimpl parsebinary id3_reader _binary readallbinary size t id3 fieldimpl get num text items const return num items size_t id3_fieldimpl getnumtextitems _num_items size t id3 fieldimpl set const char data size t len 0 if this get type id3fty textstring data string str data len this settext i str return len size_t id3_fieldimpl size_t gettype id3fty_textstring settext_i size t id3 fieldimpl get char buffer size t max length const size t size 0 if this get type id3fty textstring this get encoding id3te ascii buffer null max length 0 string data this get text size dami min max length data size memcpy buffer data data size if size max length buffer size 0 return size size_t id3_fieldimpl size_t maxlength size_t gettype id3fty_textstring getencoding id3te_ascii maxlength gettext maxlength maxlength size t id3 fieldimpl get char buf size t max len size t index const size t size 0 if this get type id3fty textstring this get encoding id3te ascii buf null max len 0 string data this get text item index size dami min max len data size memcpy buf data data size if size max len buf size 0 return size size_t id3_fieldimpl size_t maxlen size_t size_t gettype id3fty_textstring getencoding id3te_ascii maxlen gettextitem maxlen maxlen const char id3 fieldimpl get raw text const const char text null if this get type id3fty textstring this get encoding id3te ascii text text c str return text id3_fieldimpl getrawtext gettype id3fty_textstring getencoding id3te_ascii _text c_str const char id3 fieldimpl get raw text item size t index const const char text null if this get type id3fty textstring this get encoding id3te ascii index this get num text items text text c str for size t i 0 i index i text strlen text 1 return text id3_fieldimpl getrawtextitem size_t gettype id3fty_textstring getencoding id3te_ascii getnumtextitems _text c_str size_t size t id3 fieldimpl add const char data size t len 0 if this get type id3fty textstring string str data len this addtext i str return len size_t id3_fieldimpl size_t gettype id3fty_textstring addtext_i string id3 fieldimpl get text const string data if this get type id3fty textstring data text return data id3_fieldimpl gettext gettype id3fty_textstring _text string id3 fieldimpl get text item size t index const string data if this get type id3fty textstring this get encoding id3te ascii const char raw this get raw text item index if raw null data raw return data id3_fieldimpl gettextitem size_t gettype id3fty_textstring getencoding id3te_ascii getrawtextitem size t id3 fieldimpl set text string data size t len 0 if this get type id3fty textstring len this settext i data return len size_t id3_fieldimpl settext size_t gettype id3fty_textstring settext_i size t id3 fieldimpl add text string data size t len 0 if this get type id3fty textstring len this addtext i data return len size_t id3_fieldimpl addtext size_t gettype id3fty_textstring addtext_i size t id3 fieldimpl settext i string data this clear if fixed size 0 text get fixed data fixed size else text data id3d notice settext i text text changed true if text size 0 num items 0 else num items 1 return text size size_t id3_fieldimpl settext_i _fixed_size _text getfixed _fixed_size _text id3d_notice settext_i _text _changed _text _num_items _num_items _text size t id3 fieldimpl addtext i string data size t len 0 how much of str we copied into this field max is str len id3d notice id3 fieldimpl addtext i adding data if this get num text items 0 there aren t any text items in the field so just assign the string to the field len this settext i data else assert fixed size 0 text 0 if this get encoding id3te unicode text 0 text append data len data size num items return len size_t id3_fieldimpl addtext_i size_t strlen id3d_notice id3_fieldimpl addtext_i getnumtextitems settext_i _fixed_size _text getencoding id3te_unicode _text _text _num_items void id3 fieldimpl render text id3 writer writer const id3 textenc enc this get encoding if flags id3ff cstr write encoded string writer text enc else write encoded text writer text enc changed false id3_fieldimpl rendertext id3_writer id3_textenc getencoding _flags id3ff_cstr writeencodedstring _text writeencodedtext _text _changed bool id3 fieldimpl parse text id3 reader reader id3d notice id3 field parse text reader get beg reader get beg id3d notice id3 field parse text reader get cur reader get cur id3d notice id3 field parse text reader get end reader get end this clear id3 textenc enc this get encoding size t fixed size this size if fixed size id3d notice id3 field parse text fixed size string the string is of fixed length string text read encoded text reader fixed size enc this set text text id3d notice id3 field parse text fixed size string text else if flags id3ff list id3d notice id3 field parse text text list lists are always the last field in a frame parse all remaining characters in the reader while reader at end string text read encoded string reader enc this add text text id3d notice id3 field parse text adding string text else if flags id3ff cstr id3d notice id3 field parse text null terminated string string text read encoded string reader enc this set text text id3d notice id3 field parse text null terminated string text else id3d notice id3 field parse text last field string string text read encoded text reader reader remaining bytes enc not null terminated this add text text id3d notice id3 field parse text last field string text changed false return true id3_fieldimpl parsetext id3_reader id3d_notice id3_field parsetext getbeg getbeg id3d_notice id3_field parsetext getcur getcur id3d_notice id3_field parsetext getend getend id3_textenc getencoding size_t fixed_size fixed_size id3d_notice id3_field parsetext readencodedtext fixed_size settext id3d_notice id3_field parsetext _flags id3ff_list id3d_notice id3_field parsetext atend readencodedstring addtext id3d_notice id3_field parsetext _flags id3ff_cstr id3d_notice id3_field parsetext readencodedstring settext id3d_notice id3_field parsetext id3d_notice id3_field parsetext readencodedtext remainingbytes addtext id3d_notice id3_field parsetext _changed flags def flags changed false fixed size def fixed size num items 0 enc type id3fty textstring id3te ascii id3te none this clear id3 fieldimpl id3 fieldimpl clears any data and frees any memory associated with the field sa id3 tag clear sa id3 frame clear void id3 fieldimpl clear switch type case id3fty integer integer 0 break case id3fty binary binary erase if fixed size 0 binary assign fixed size 0 break case id3fty textstring text erase if fixed size 0 if this get encoding id3te unicode _flags _flags _changed _fixed_size _fixed_size _num_items _enc _type id3fty_textstring id3te_ascii id3te_none id3_fieldimpl id3_fieldimpl id3_tag id3_frame id3_fieldimpl _type id3fty_integer _integer id3fty_binary _binary _fixed_size _binary _fixed_size id3fty_textstring _text _fixed_size getencoding id3te_unicode id3 textenc enc this get encoding if enc id3te unicode size 0 size if flags id3ff cstr size if enc id3te unicode size 2 return size size t id3 fieldimpl size const size t size 0 check to see if we are within the legal limit for this field 0 means arbitrary length field id3_textenc getencoding id3te_unicode _flags id3ff_cstr id3te_unicode size_t id3_fieldimpl size_t brief returns the size of a field the value returned is dependent on the type of the field for ascii strings this returns the number of characters in the field not including any null terminator the same holds true for unicode it returns the number of characters in the field not bytes and this does not include the unicode bom which isn t put in a unicode string obtained by the get unicode t size t size t method anyway for binary and integer fields this returns the number of bytes in the field code size t how big my frame get field id3fn data size endcode return the size of the field either in bytes for binary or integer fields or characters for strings size t id3 fieldimpl bin size const if fixed size 0 return fixed size unicode_t size_t size_t size_t howbig myframe getfield id3fn_data size_t id3_fieldimpl binsize _fixed_size _fixed_size break case id3fty textstring render text writer break default id3d warning id3d fieldimpl render unknown field type break id3 field id3 fieldimpl operator const id3 field rhs const id3 fieldimpl fld const id3 fieldimpl rhs if this rhs this get type fld get type switch fld get type case id3fty integer this set integer fld get integer break id3fty_textstring rendertext id3d_warning id3d_fieldimpl id3_field id3_fieldimpl id3_field id3_fieldimpl id3_fieldimpl gettype gettype gettype id3fty_integer setinteger getinteger this set encoding fld get encoding this set text fld get text break case id3fty binary this set binary fld get binary break default setencoding getencoding settext gettext id3fty_binary setbinary getbinary id3 frameid fid id3fid noframe const int slen strlen id for size t cur 0 id3 framedefs cur eid id3fid noframe cur if strcmp id3 framedefs cur s short textid id 0 slen 3 strcmp id3 framedefs cur s long textid id 0 slen 4 fid id3 framedefs cur eid break return fid void id3 fieldimpl render id3 writer writer const switch this get type case id3fty integer render integer writer break id3_frameid id3fid_noframe size_t id3_framedefs id3fid_noframe id3_framedefs sshorttextid id3_framedefs slongtextid id3_framedefs id3_fieldimpl id3_writer gettype id3fty_integer renderinteger size fixed size else if type id3fty integer size sizeof uint32 else if type id3fty textstring size text size else size binary size return size bool id3 fieldimpl parse id3 reader reader bool success false switch this get type case id3fty integer success this parse integer reader break case id3fty binary _fixed_size _type id3fty_integer _type id3fty_textstring _text _binary id3_fieldimpl id3_reader gettype id3fty_integer parseinteger id3fty_binary else if this get encoding id3te ascii text assign fixed size 0 getencoding id3te_ascii _text _fixed_size c download queue c download queue filesrdy 0 datarate 0 cur udpserver 0 lastfile 0 lastcheckdiskspacetime 0 lastudpsearchtime 0 lastudpstattime 0 set last kademlia file request udcounter 0 m isearchedservers 0 m dataratems 0 m nudpfilereasks 0 m nfailedudpfilereasks 0 m dwnexttcpsrcreq 0 m crequestssenttoserver 0 m dwlasta4aftime 0 zz download manager cdownloadqueue cdownloadqueue cur_udpserver setlastkademliafilerequest m_isearchedservers m_dataratems m_nudpfilereasks m_nfailedudpfilereasks m_dwnexttcpsrcreq m_crequestssenttoserver m_dwlasta4aftime downloadmanager c download queue c download queue for position pos filelist get head position pos 0 delete filelist get next pos m srcwnd destroy window just to avoid a mfc warning cdownloadqueue cdownloadqueue getheadposition getnext m_srcwnd destroywindow void c download queue process process local requests send src requests to local server uint32 downspeed 0 uint64 max download the prefs get max download in bytes per sec true if max download unlimited 1024 datarate 1500 downspeed uint max download 100 datarate 1 if downspeed 50 downspeed 50 else if downspeed 200 downspeed 200 while avarage dr list get count 0 get tick count avarage dr list get head timestamp 10 1000 m dataratems avarage dr list remove head datalen if avarage dr list get count 1 datarate uint m dataratems avarage dr list get count else datarate 0 uint32 dataratex 0 udcounter filelist is already sorted by prio therefore i removed all the extra loops for position pos filelist get head position pos 0 c part file cur file filelist get next pos if cur file get status ps ready cur file get status ps empty dataratex cur file process downspeed udcounter else this will make sure we don t keep old sources to paused and stoped files cur file stop paused file transferred data newitem dataratex get tick count avarage dr list add tail newitem m dataratems dataratex if udcounter 5 if the app serverconnect isudp socket available if lastudpstattime get tick count lastudpstattime udpserverstattime lastudpstattime get tick count the app serverlist server stats if udcounter 10 udcounter 0 if the app serverconnect isudp socket available if lastudpsearchtime get tick count lastudpsearchtime udpserverreasktime send nextudp packet check diskspace timed zz download manager if m dwlasta4aftime get tick count m dwlasta4aftime 2 60 1000 the app clientlist processa4af clients m dwlasta4aftime get tick count zz download manager cdownloadqueue processlocalrequests maxdownload theprefs getmaxdownloadinbytespersec maxdownload maxdownload avarage_dr_list getcount gettickcount avarage_dr_list gethead m_dataratems avarage_dr_list removehead avarage_dr_list getcount m_dataratems avarage_dr_list getcount getheadposition cpartfile cur_file getnext cur_file getstatus ps_ready cur_file getstatus ps_empty cur_file cur_file stoppausedfile transferreddata gettickcount avarage_dr_list addtail m_dataratems theapp isudpsocketavailable gettickcount gettickcount theapp serverstats theapp isudpsocketavailable gettickcount sendnextudppacket checkdiskspacetimed downloadmanager m_dwlasta4aftime gettickcount m_dwlasta4aftime theapp processa4afclients m_dwlasta4aftime gettickcount downloadmanager void c download queue init find all part files read hash them if needed and store into a list c file find ff int count 0 for int i 0 i the prefs tempdir get count i c string search path the prefs get temp dir i search path t part met check all part met files bool end ff find file search path 0 while end end ff find next file if ff is directory continue c part file toadd new c part file if toadd load part file the prefs get temp dir i ff get file name count filelist add tail toadd to downloadqueue if toadd get status true ps ready the app sharedfiles safe addk file toadd part files are always shared files the app emuledlg transferwnd downloadlistctrl add file toadd show in downloadwindow else delete toadd ff close try recovering any part met files search path t backup end ff find file search path 0 while end end ff find next file if ff is directory continue c part file toadd new c part file if toadd load part file the prefs get temp dir i ff get file name toadd save part file resave backup count filelist add tail toadd to downloadqueue if toadd get status true ps ready the app sharedfiles safe addk file toadd part files are always shared files the app emuledlg transferwnd downloadlistctrl add file toadd show in downloadwindow add log line false get res string ids recovered partmet toadd get file name else delete toadd ff close if count 0 add log line false get res string ids nopartsfound else add log line false get res string ids foundparts count sort by priority check diskspace verify m srcwnd create ex 0 afx register wnd class 0 t e mule async dns resolve socket wnd 2 ws overlapped 0 0 0 0 null null export part met files overview cdownloadqueue cfilefind theprefs getcount cstring searchpath theprefs gettempdir searchpath _t findfile searchpath findnextfile isdirectory cpartfile cpartfile loadpartfile theprefs gettempdir getfilename addtail getstatus ps_ready theapp safeaddkfile theapp addfile searchpath _t findfile searchpath findnextfile isdirectory cpartfile cpartfile loadpartfile theprefs gettempdir getfilename savepartfile addtail getstatus ps_ready theapp safeaddkfile theapp addfile addlogline getresstring ids_recovered_partmet getfilename addlogline getresstring ids_nopartsfound addlogline getresstring ids_foundparts sortbypriority checkdiskspace m_srcwnd createex afxregisterwndclass _t emule ws_overlapped exportpartmetfilesoverview void c download queue add part files to share for position pos filelist get head position pos 0 c part file cur file filelist get next pos if cur file get status true ps ready the app sharedfiles safe addk file cur file true cdownloadqueue addpartfilestoshare getheadposition cpartfile cur_file getnext cur_file getstatus ps_ready theapp safeaddkfile cur_file void c download queue add download c part file newfile bool paused barry add in paused mode if required if paused newfile pause file set auto cat newfile hoax 69 slugfiller auto cat filelist add tail newfile sort by priority check diskspace the app emuledlg transferwnd downloadlistctrl add file newfile add log line true get res string ids newdownload newfile get file name c string msg temp msg temp format get res string ids newdownload t n newfile get file name the app emuledlg show notifier msg temp tbn downloadadded export part met files overview cdownloadqueue adddownload cpartfile pausefile setautocat hoax_69 autocat addtail sortbypriority checkdiskspace theapp addfile addlogline getresstring ids_newdownload getfilename cstring msgtemp msgtemp getresstring ids_newdownload _t getfilename theapp shownotifier msgtemp tbn_downloadadded exportpartmetfilesoverview void c download queue add search to download c search file toadd uint8 paused int cat if toadd get file size uint64 0 is file existing toadd get file hash return if toadd get file size old max emule file size the prefs canfs handle large files log error get res string ids err fscanthandlefile return c part file newfile new c part file toadd cat if newfile get status ps error delete newfile return if paused 2 paused uint8 the prefs add new files paused add download newfile paused 1 if the search result is from op globsearchres there may also be a source if toadd get clientid toadd get client port c safe mem file sources 1 4 2 try sources writeu int8 1 sources writeu int32 toadd get clientid sources writeu int16 toadd get client port sources seek to begin newfile add sources sources toadd get client serverip toadd get client server port catch c file exception error assert 0 error delete add more sources which were found via global udp search const c simple array c search file s client a clients toadd get clients for int i 0 i a clients get size i c safe mem file sources 1 4 2 try sources writeu int8 1 sources writeu int32 a clients i m nip sources writeu int16 a clients i m nport sources seek to begin newfile add sources sources a clients i m nserverip a clients i m nserverport catch c file exception error assert 0 error delete break cdownloadqueue addsearchtodownload csearchfile getfilesize isfileexisting getfilehash getfilesize old_max_emule_file_size theprefs canfshandlelargefiles logerror getresstring ids_err_fscanthandlefile cpartfile cpartfile getstatus ps_error theprefs addnewfilespaused adddownload op_globsearchres getclientid getclientport csafememfile writeuint8 writeuint32 getclientid writeuint16 getclientport seektobegin addsources getclientserverip getclientserverport cfileexception csimplearray csearchfile sclient aclients getclients aclients getsize csafememfile writeuint8 writeuint32 aclients m_nip writeuint16 aclients m_nport seektobegin addsources aclients m_nserverip aclients m_nserverport cfileexception void c download queue add search to download c string link uint8 paused int cat c part file newfile new c part file link cat if newfile get status ps error delete newfile return if paused 2 paused uint8 the prefs add new files paused add download newfile paused 1 cdownloadqueue addsearchtodownload cstring cpartfile cpartfile getstatus ps_error theprefs addnewfilespaused adddownload void c download queue add file link to download ced2k file link p link int cat c part file newfile new c part file p link cat if newfile get status ps error delete newfile newfile null else add download newfile the prefs add new files paused c part file partfile newfile if partfile null partfile get file byid p link get hash key if partfile if p link has valid sources partfile add client sources p link sources list 1 if p link has validaich hash if partfile getaich hashset has valid master hash partfile getaich hashset get master hash p link getaich hash partfile getaich hashset set master hash p link getaich hash aich verified partfile getaich hashset free hash set if p link has hostname sources position pos p link m hostnamesourceslist get head position while pos null const s unresolved hostname p unres host p link m hostnamesourceslist get next pos m srcwnd add to resolve p link get hash key p unres host str hostname p unres host n port p unres host strurl cdownloadqueue addfilelinktodownload ced2kfilelink plink cpartfile cpartfile plink getstatus ps_error adddownload theprefs addnewfilespaused cpartfile getfilebyid plink gethashkey plink hasvalidsources addclientsources plink sourceslist plink hasvalidaichhash getaichhashset hasvalidmasterhash getaichhashset getmasterhash plink getaichhash getaichhashset setmasterhash plink getaichhash aich_verified getaichhashset freehashset plink hashostnamesources plink m_hostnamesourceslist getheadposition sunresolvedhostname punreshost plink m_hostnamesourceslist getnext m_srcwnd addtoresolve plink gethashkey punreshost strhostname punreshost nport punreshost void c download queue remove file c part file toremove remove local server request toremove for position pos filelist get head position pos 0 filelist get next pos if toremove filelist get at pos filelist remove at pos break sort by priority check diskspace export part met files overview cdownloadqueue removefile cpartfile removelocalserverrequest getheadposition getnext getat removeat sortbypriority checkdiskspace exportpartmetfilesoverview void c download queue delete all position pos for pos filelist get head position pos 0 c part file cur file filelist get next pos cur file srclist remove all barry should also remove all requested blocks don t worry about deleting the blocks that gets handled when c up down client is deleted in c client list delete all cur file remove all requested blocks cdownloadqueue deleteall getheadposition cpartfile cur_file getnext cur_file removeall cupdownclient cclientlist deleteall cur_file removeallrequestedblocks uint c download queue get downloading file count const uint result 0 for position pos filelist get head position pos 0 uint u status filelist get next pos get status if u status ps ready u status ps empty result return result cdownloadqueue getdownloadingfilecount getheadposition ustatus getnext getstatus ustatus ps_ready ustatus ps_empty uint c download queue get paused file count const uint result 0 for position pos filelist get head position pos 0 if filelist get next pos get status ps paused result return result cdownloadqueue getpausedfilecount getheadposition getnext getstatus ps_paused bool c download queue is file existing const uchar fileid bool b log warnings const const c known file file the app sharedfiles get file byid fileid if file if b log warnings if file is part file log warning log statusbar get res string ids err already downloading file get file name else log warning log statusbar get res string ids err already downloaded file get file name return true else if file get file byid fileid null if b log warnings log warning log statusbar get res string ids err already downloading file get file name return true return false cdownloadqueue isfileexisting blogwarnings cknownfile theapp getfilebyid blogwarnings ispartfile logwarning log_statusbar getresstring ids_err_already_downloading getfilename logwarning log_statusbar getresstring ids_err_already_downloaded getfilename getfilebyid blogwarnings logwarning log_statusbar getresstring ids_err_already_downloading getfilename bool c download queue is part file const c known file file const for position pos filelist get head position pos 0 if file filelist get next pos return true return false cdownloadqueue ispartfile cknownfile getheadposition getnext c part file c download queue get file byid const uchar filehash const for position pos filelist get head position pos 0 c part file cur file filelist get next pos if md4cmp filehash cur file get file hash return cur file return null cpartfile cdownloadqueue getfilebyid getheadposition cpartfile cur_file getnext cur_file getfilehash cur_file c part file c download queue get file by index int index const position pos filelist find index index if pos return filelist get at pos return null cpartfile cdownloadqueue getfilebyindex findindex getat c part file c download queue get file by kad file searchid uint32 id const for position pos filelist get head position pos 0 c part file cur file filelist get next pos if id cur file get kad file searchid return cur file return null cpartfile cdownloadqueue getfilebykadfilesearchid getheadposition cpartfile cur_file getnext cur_file getkadfilesearchid cur_file void c download queue start next file if prefs int cat if the prefs start next file start next file the prefs start next file 1 cat 1 the prefs start next file 3 cdownloadqueue startnextfileifprefs theprefs startnextfile startnextfile theprefs startnextfile theprefs startnextfile void c download queue start next file int cat bool force c part file pfile null c part file cur file position pos if cat 1 try to find in specified category for pos filelist get head position pos 0 cur file filelist get next pos if cur file get status ps paused cur file get category uint cat cat 0 the prefs get category 0 filter 0 cur file get category 0 c part file right file has higher prio pfile cur file pfile cur file if pfile null force return if cat 1 pfile null force for pos filelist get head position pos 0 cur file filelist get next pos if cur file get status ps paused c part file right file has higher prio pfile cur file pick first found matching file since they are sorted in prio order with most important file first pfile cur file if pfile pfile resume file cdownloadqueue startnextfile cpartfile cpartfile cur_file getheadposition cur_file getnext cur_file getstatus ps_paused cur_file getcategory theprefs getcategory cur_file getcategory cpartfile rightfilehashigherprio cur_file cur_file getheadposition cur_file getnext cur_file getstatus ps_paused cpartfile rightfilehashigherprio cur_file cur_file resumefile c up down client c download queue get download client byip uint32 dwip for position pos filelist get head position pos 0 c part file cur file filelist get next pos for position pos2 cur file srclist get head position pos2 0 c up down client cur client cur file srclist get next pos2 if dwip cur client getip return cur client return null cupdownclient cdownloadqueue getdownloadclientbyip getheadposition cpartfile cur_file getnext cur_file getheadposition cupdownclient cur_client cur_file getnext cur_client cur_client c up down client c download queue getdownloadclientbyip udp uint32 dwip uint16 nudp port for position pos filelist get head position pos 0 c part file cur file filelist get next pos for position pos2 cur file srclist get head position pos2 0 c up down client cur client cur file srclist get next pos2 if dwip cur client getip nudp port cur client getudp port return cur client return null cupdownclient cdownloadqueue getdownloadclientbyip_udp nudpport getheadposition cpartfile cur_file getnext cur_file getheadposition cupdownclient cur_client cur_file getnext cur_client nudpport cur_client getudpport cur_client bool c download queue is in list const c up down client client const for position pos filelist get head position pos 0 c part file cur file filelist get next pos for position pos2 cur file srclist get head position pos2 0 if cur file srclist get next pos2 client return true return false cdownloadqueue isinlist cupdownclient getheadposition cpartfile cur_file getnext cur_file getheadposition cur_file getnext bool c download queue check and add source c part file sender c up down client source if sender is stopped delete source return false if source has valid hash if md4cmp source get user hash the prefs get user hash if the prefs get verbose add debug log line false t tried to add source with matching hash to your own delete source return false filter sources which are known to be dead useless if the app clientlist m globdeadsourcelist is dead source source sender m deadsourcelist is dead source source if the prefs get log filteredi ps add debug log line dlp default false t rejected source because it was found on the dead sources list s for file s s sender m deadsourcelist is dead source source t local t global sender get file name source dbg get client info delete source return false filter lan i ps and or i pfilter is not required here because it was already done in parent functions uses this only for temp clients for position pos filelist get head position pos 0 c part file cur file filelist get next pos for position pos2 cur file srclist get head position pos2 0 c up down client cur client cur file srclist get next pos2 if cur client compare source true cur client compare source false if cur file sender this file has already this source delete source return false set request for this source if cur client add request for another file sender the app emuledlg transferwnd downloadlistctrl add source sender cur client true delete source if cur client get download state ds connected cur client swap to another file t new a4af source found c download queue check and add source false false false null true false zz download manager return false else delete source return false our new source is real new but maybe it is already uploading to us if yes the known client will be attached to the var source and the old sourceclient will be deleted if the app clientlist attach to already known source 0 ifdef debug if the prefs get verbose source get request file if a client sent us wrong sources sources for some other file for which we asked but which we are also downloading we may get a little in trouble here when moving this source to some other partfile without further checks and updates if md4cmp source get request file get file hash sender get file hash 0 add debug log line false t c download queue check and add source added potential wrong source u diff filehash to file s source get userid hybrid sender get file name if source get request file get part count 0 source get request file get part count sender get part count add debug log line false t c download queue check and add source added potential wrong source u diff partcount to file s source get userid hybrid sender get file name endif source set request file sender else here we know that the client instance source is a new created client instance see callers which is therefor not already in the clientlist we can avoid the check for duplicate client list entries when adding this client the app clientlist add client source true ifdef debug if the prefs get verbose source get part count 0 source get part count sender get part count debug only add debug log line false t c download queue check and add source new added source u s had still value in partcount source get userid hybrid sender get file name endif sender srclist add tail source the app emuledlg transferwnd downloadlistctrl add source sender source false return true cdownloadqueue checkandaddsource cpartfile cupdownclient isstopped hasvalidhash getuserhash theprefs getuserhash theprefs getverbose adddebuglogline _t theapp m_globdeadsourcelist isdeadsource m_deadsourcelist isdeadsource theprefs getlogfilteredips adddebuglogline dlp_default _t deadsourceslist m_deadsourcelist isdeadsource _t _t getfilename dbggetclientinfo ips ipfilter getheadposition cpartfile cur_file getnext cur_file getheadposition cupdownclient cur_client cur_file getnext cur_client cur_client cur_file cur_client addrequestforanotherfile theapp addsource cur_client cur_client getdownloadstate ds_connected cur_client swaptoanotherfile _t cdownloadqueue checkandaddsource downloadmanager theapp attachtoalreadyknown _debug theprefs getverbose getrequestfile getrequestfile getfilehash getfilehash adddebuglogline _t cdownloadqueue checkandaddsource getuseridhybrid getfilename getrequestfile getpartcount getrequestfile getpartcount getpartcount adddebuglogline _t cdownloadqueue checkandaddsource getuseridhybrid getfilename setrequestfile theapp addclient _debug theprefs getverbose getpartcount getpartcount getpartcount debug_only adddebuglogline _t cdownloadqueue checkandaddsource getuseridhybrid getfilename addtail theapp addsource bool c download queue check and add known source c part file sender c up down client source bool b ignore glob dead list if sender is stopped return false filter sources which are known to be dead useless if the app clientlist m globdeadsourcelist is dead source source b ignore glob dead list sender m deadsourcelist is dead source source if the prefs get log filteredi ps add debug log line dlp default false t rejected source because it was found on the dead sources list s for file s s sender m deadsourcelist is dead source source t local t global sender get file name source dbg get client info return false filter lan i ps this may be needed here in case we are connected to the internet and are also connected to a lan and some client from within the lan connected to us though this situation may be supported in future by adding that client to the source list and filtering that client s lan ip when sending sources to a client within the internet i pfilter is not needed here because that known client was already i pfiltered when receiving op hello if source has lowid uint32 n clientip ntohl source get userid hybrid if is goodip n clientip check for 0 ip localhost and lan addresses if the prefs get log filteredi ps add debug log line false t ignored already known source with ip s ipstr n clientip return false use this for client which are already know downloading for example for position pos filelist get head position pos 0 c part file cur file filelist get next pos if cur file srclist find source if cur file sender return false if source add request for another file sender the app emuledlg transferwnd downloadlistctrl add source sender source true if source get download state ds connected source swap to another file t new a4af source found c download queue check and add known source false false false null true false zz download manager return false ifdef debug if the prefs get verbose source get request file if a client sent us wrong sources sources for some other file for which we asked but which we are also downloading we may get a little in trouble here when moving this source to some other partfile without further checks and updates if md4cmp source get request file get file hash sender get file hash 0 add debug log line false t c download queue check and add known source added potential wrong source u diff filehash to file s source get userid hybrid sender get file name if source get request file get part count 0 source get request file get part count sender get part count add debug log line false t c download queue check and add known source added potential wrong source u diff partcount to file s source get userid hybrid sender get file name endif source set request file sender sender srclist add tail source source set source from sf passive if the prefs get debug source exchange add debug log line false t sx recv passively added source s file s source dbg get client info sender get file name ifdef debug if the prefs get verbose source get part count 0 source get part count sender get part count debug only add debug log line false t c download queue check and add known source new added source u s had still value in partcount source get userid hybrid sender get file name endif the app emuledlg transferwnd downloadlistctrl add source sender source false update displayed info return true cdownloadqueue checkandaddknownsource cpartfile cupdownclient bignoreglobdeadlist isstopped theapp m_globdeadsourcelist isdeadsource bignoreglobdeadlist m_deadsourcelist isdeadsource theprefs getlogfilteredips adddebuglogline dlp_default _t deadsourceslist m_deadsourcelist isdeadsource _t _t getfilename dbggetclientinfo ips ipfilter ipfiltered op_hello haslowid nclientip getuseridhybrid isgoodip nclientip theprefs getlogfilteredips adddebuglogline _t nclientip getheadposition cpartfile cur_file getnext cur_file cur_file addrequestforanotherfile theapp addsource getdownloadstate ds_connected swaptoanotherfile _t cdownloadqueue checkandaddknownsource downloadmanager _debug theprefs getverbose getrequestfile getrequestfile getfilehash getfilehash adddebuglogline _t cdownloadqueue checkandaddknownsource getuseridhybrid getfilename getrequestfile getpartcount getrequestfile getpartcount getpartcount adddebuglogline _t cdownloadqueue checkandaddknownsource getuseridhybrid getfilename setrequestfile addtail setsourcefrom sf_passive theprefs getdebugsourceexchange adddebuglogline _t sxrecv dbggetclientinfo getfilename _debug theprefs getverbose getpartcount getpartcount getpartcount debug_only adddebuglogline _t cdownloadqueue checkandaddknownsource getuseridhybrid getfilename theapp addsource updatedisplayedinfo bool c download queue remove source c up down client toremove bool b do stats update bool b removed src from part file false for position pos filelist get head position pos 0 c part file cur file filelist get next pos for position pos2 cur file srclist get head position pos2 0 cur file srclist get next pos2 if toremove cur file srclist get at pos2 cur file srclist remove at pos2 b removed src from part file true if b do stats update cur file remove downloading source toremove cur file update parts info break if b do stats update cur file update available parts count remove this source on all files in the downloadqueue who link this source pretty slow but no way arround maybe using a map is better but that s slower on other parts position pos3 pos4 for pos3 toremove m otherrequests list get head position pos4 pos3 null toremove m otherrequests list get next pos3 position pos5 toremove m otherrequests list get at pos4 a4a fsrclist find toremove if pos5 toremove m otherrequests list get at pos4 a4a fsrclist remove at pos5 the app emuledlg transferwnd downloadlistctrl remove source toremove toremove m otherrequests list get at pos4 toremove m otherrequests list remove at pos4 for pos3 toremove m othernoneeded list get head position pos4 pos3 null toremove m othernoneeded list get next pos3 position pos5 toremove m othernoneeded list get at pos4 a4a fsrclist find toremove if pos5 toremove m othernoneeded list get at pos4 a4a fsrclist remove at pos5 the app emuledlg transferwnd downloadlistctrl remove source toremove toremove m othernoneeded list get at pos4 toremove m othernoneeded list remove at pos4 if b removed src from part file toremove has file rating toremove get file comment is empty c part file p file toremove get request file if p file p file update file rating comment avail toremove set download state ds none the app emuledlg transferwnd downloadlistctrl remove source toremove 0 toremove set request file null return b removed src from part file cdownloadqueue removesource cupdownclient bdostatsupdate bremovedsrcfrompartfile getheadposition cpartfile cur_file getnext cur_file getheadposition cur_file getnext cur_file getat cur_file removeat bremovedsrcfrompartfile bdostatsupdate cur_file removedownloadingsource cur_file updatepartsinfo bdostatsupdate cur_file updateavailablepartscount m_otherrequests_list getheadposition m_otherrequests_list getnext m_otherrequests_list getat a4afsrclist m_otherrequests_list getat a4afsrclist removeat theapp removesource m_otherrequests_list getat m_otherrequests_list removeat m_othernoneeded_list getheadposition m_othernoneeded_list getnext m_othernoneeded_list getat a4afsrclist m_othernoneeded_list getat a4afsrclist removeat theapp removesource m_othernoneeded_list getat m_othernoneeded_list removeat bremovedsrcfrompartfile hasfilerating getfilecomment isempty cpartfile pfile getrequestfile pfile pfile updatefileratingcommentavail setdownloadstate ds_none theapp removesource setrequestfile bremovedsrcfrompartfile void c download queue get download stats s download stats results memset results 0 sizeof results for position pos filelist get head position pos 0 const c part file cur file filelist get next pos results a 0 cur file get source count results a 1 cur file get transferring src count results a 2 cur file get src statistics value ds onqueue results a 3 cur file get src statistics value ds remotequeuefull results a 4 cur file get src statistics value ds noneededparts results a 5 cur file get src statistics value ds connected results a 6 cur file get src statistics value ds reqhashset results a 7 cur file get src statistics value ds connecting results a 8 cur file get src statistics value ds waitcallback results a 8 cur file get src statistics value ds waitcallbackkad results a 9 cur file get src statistics value ds toomanyconns results a 9 cur file get src statistics value ds toomanyconnskad results a 10 cur file get src statistics value ds lowtolowip results a 11 cur file get src statistics value ds none results a 12 cur file get src statistics value ds error results a 13 cur file get src statistics value ds banned results a 14 cur file src stats 3 results a 15 cur file get srca4af count results a 16 cur file src stats 0 results a 17 cur file src stats 1 results a 18 cur file src stats 2 results a 19 cur file net stats 0 results a 20 cur file net stats 1 results a 21 cur file net stats 2 results a 22 cur file m deadsourcelist get dead sources count cdownloadqueue getdownloadstats sdownloadstats getheadposition cpartfile cur_file getnext cur_file getsourcecount cur_file gettransferringsrccount cur_file getsrcstatisticsvalue ds_onqueue cur_file getsrcstatisticsvalue ds_remotequeuefull cur_file getsrcstatisticsvalue ds_noneededparts cur_file getsrcstatisticsvalue ds_connected cur_file getsrcstatisticsvalue ds_reqhashset cur_file getsrcstatisticsvalue ds_connecting cur_file getsrcstatisticsvalue ds_waitcallback cur_file getsrcstatisticsvalue ds_waitcallbackkad cur_file getsrcstatisticsvalue ds_toomanyconns cur_file getsrcstatisticsvalue ds_toomanyconnskad cur_file getsrcstatisticsvalue ds_lowtolowip cur_file getsrcstatisticsvalue ds_none cur_file getsrcstatisticsvalue ds_error cur_file getsrcstatisticsvalue ds_banned cur_file src_stats cur_file getsrca4afcount cur_file src_stats cur_file src_stats cur_file src_stats cur_file net_stats cur_file net_stats cur_file net_stats cur_file m_deadsourcelist getdeadsourcescount uint64 rui64 tot needed space results 0 0 results 1 0 results 2 0 for position pos filelist get head position pos 0 const c part file cur file filelist get next pos uint u state cur file get status if u state ps ready u state ps empty uint64 ui64 size to transfer 0 uint64 ui64 needed space 0 cur file get size to transfer and needed space ui64 size to transfer ui64 needed space rui64 tot file size uint64 cur file get file size rui64 tot bytes left to transfer ui64 size to transfer rui64 tot needed space ui64 needed space results 2 results 0 cur file get source count results 1 cur file get transferring src count rui64totneededspace getheadposition cpartfile cur_file getnext ustate cur_file getstatus ustate ps_ready ustate ps_empty ui64sizetotransfer ui64neededspace cur_file getsizetotransferandneededspace ui64sizetotransfer ui64neededspace rui64totfilesize cur_file getfilesize rui64totbyteslefttotransfer ui64sizetotransfer rui64totneededspace ui64neededspace cur_file getsourcecount cur_file gettransferringsrccount void c download queue reset cat parts uint cat c part file cur file for position pos filelist get head position pos 0 cur file filelist get next pos if cur file get category cat cur file set category 0 else if cur file get category cat cur file set category cur file get category 1 cdownloadqueue resetcatparts cpartfile cur_file getheadposition cur_file getnext cur_file getcategory cur_file setcategory cur_file getcategory cur_file setcategory cur_file getcategory void c download queue set cat prio uint cat uint8 newprio for position pos filelist get head position pos 0 c part file cur file filelist get next pos if cat 0 cur file get category cat if newprio pr auto cur file set auto down priority true cur file set down priority pr high false else cur file set auto down priority false cur file set down priority newprio false the app downloadqueue sort by priority the app downloadqueue check diskspace timed cdownloadqueue setcatprio getheadposition cpartfile cur_file getnext cur_file getcategory pr_auto cur_file setautodownpriority cur_file setdownpriority pr_high cur_file setautodownpriority cur_file setdownpriority theapp sortbypriority theapp checkdiskspacetimed zz download manager void c download queue remove auto prio in cat uint cat uint8 newprio c part file cur file for position pos filelist get head position pos 0 filelist get next pos cur file filelist get at pos if cur file is auto down priority cat 0 cur file get category cat cur file set auto down priority false cur file set down priority newprio false the app downloadqueue sort by priority the app downloadqueue check diskspace timed downloadmanager cdownloadqueue removeautoprioincat cpartfile cur_file getheadposition getnext cur_file getat cur_file isautodownpriority cur_file getcategory cur_file setautodownpriority cur_file setdownpriority theapp sortbypriority theapp checkdiskspacetimed void c download queue set cat status uint cat int newstatus bool reset false bool resort false position pos filelist get head position while pos 0 c part file cur file filelist get at pos if cur file continue if cat 1 cat 2 cur file get category 0 cat 0 cur file check show item in given cat cat cat 0 cat cur file get category switch newstatus case mp cancel cur file delete file reset true break case mp pause cur file pause file false false resort true break case mp stop cur file stop file false false resort true break case mp resume if cur file can resume file if cur file get status ps insufficient cur file resume file insufficient else cur file resume file false resort true break filelist get next pos if reset reset false pos filelist get head position if resort the app downloadqueue sort by priority the app downloadqueue check diskspace cdownloadqueue setcatstatus getheadposition cpartfile cur_file getat cur_file cur_file getcategory cur_file checkshowitemingivencat cur_file getcategory mp_cancel cur_file deletefile mp_pause cur_file pausefile mp_stop cur_file stopfile mp_resume cur_file canresumefile cur_file getstatus ps_insufficient cur_file resumefileinsufficient cur_file resumefile getnext getheadposition theapp sortbypriority theapp checkdiskspace void c download queue move cat uint from uint to if from to to position pos filelist get head position while pos 0 c part file cur file filelist get at pos if cur file continue uint mycat cur file get category if mycat min from to mycat max from to if from to mycat from mycat to from to mycat from mycat to continue not affected if mycat from cur file set category to else if from to cur file set category mycat 1 else cur file set category mycat 1 filelist get next pos cdownloadqueue movecat getheadposition cpartfile cur_file getat cur_file cur_file getcategory cur_file setcategory cur_file setcategory cur_file setcategory getnext void c download queue set auto cat c part file newfile if the prefs get cat count 1 return c string cat ext for int ix 1 ix the prefs get cat count ix cat ext the prefs get category ix autocat if cat ext is empty continue if the prefs get category ix ac regexpeval simple string comparison int cur pos 0 cat ext make lower c string fullname newfile get file name fullname make lower c string cmp ext cat ext tokenize t cur pos while cmp ext is empty hoax 69 allow wildcards in autocat string thanks to bluecow khaos and slug filler if cmp ext find t 1 cmp ext find t 1 use wildcards if path match spec fullname cmp ext newfile set category ix return else if fullname find cmp ext 1 newfile set category ix return cmp ext cat ext tokenize t cur pos else regular expression evaluation if regular expression match cat ext newfile get file name newfile set category ix cdownloadqueue setautocat cpartfile theprefs getcatcount cstring catext theprefs getcatcount catext theprefs getcategory catext isempty theprefs getcategory ac_regexpeval curpos catext makelower cstring getfilename makelower cstring cmpext catext _t curpos cmpext isempty hoax_69 slugfiller cmpext _t cmpext _t pathmatchspec cmpext setcategory cmpext setcategory cmpext catext _t curpos regularexpressionmatch catext getfilename setcategory void c download queue send local src request c part file sender assert m localserverreqqueue find sender m localserverreqqueue add tail sender cdownloadqueue sendlocalsrcrequest cpartfile m_localserverreqqueue m_localserverreqqueue addtail void c download queue remove local server request c part file p file position pos1 pos2 for pos1 m localserverreqqueue get head position pos2 pos1 null m localserverreqqueue get next pos1 if m localserverreqqueue get at pos2 p file m localserverreqqueue remove at pos2 p file m blocalsrcreqqueued false could break here fail safe go through entire list cdownloadqueue removelocalserverrequest cpartfile pfile m_localserverreqqueue getheadposition m_localserverreqqueue getnext m_localserverreqqueue getat pfile m_localserverreqqueue removeat pfile m_blocalsrcreqqueued void c download queue reset local server requests m dwnexttcpsrcreq 0 m localserverreqqueue remove all position pos filelist get head position while pos null c part file p file filelist get next pos uint u state p file get status if u state ps ready u state ps empty p file resume file p file m blocalsrcreqqueued false cdownloadqueue resetlocalserverrequests m_dwnexttcpsrcreq m_localserverreqqueue removeall getheadposition cpartfile pfile getnext ustate pfile getstatus ustate ps_ready ustate ps_empty pfile resumefile pfile m_blocalsrcreqqueued bool c download queue do kademlia file request return get tick count lastkademliafilerequest kademliaasktime cdownloadqueue dokademliafilerequest gettickcount void c download queue kademlia search file uint32 searchid const kademlia cu int128 pcontactid const kademlia cu int128 pbuddyid uint8 type uint32 ip uint16 tcp uint16 udp uint32 serverip uint16 serverport safty measure to make sure we are looking for these sources c part file temp get file by kad file searchid searchid if temp return do we need more sources if temp is stopped temp get max sources temp get source count return uint32 ed2 kip ntohl ip if the app ipfilter is filtered ed2 kip if the prefs get log filteredi ps add debug log line false t i pfiltered source ip s s received from kademlia ipstr ed2 kip the app ipfilter get last hit return if ip kademlia c kademlia getip address ed2 kip the app serverconnect get clientid tcp the prefs get port return c up down client ctemp null switch type case 4 case 1 non firewalled users if tcp if the prefs get verbose add debug log line false t ignored source ip s received from kademlia no tcp port received ipstr ip return ctemp new c up down client temp tcp ip 0 0 false ctemp set source from sf kademlia ctemp set serverip serverip ctemp set server port serverport ctemp set kad port udp byte cid 16 pcontactid to byte array cid ctemp set user hash cid break case 2 don t use this type some clients will process it wrong break case 5 case 3 this will be a firewaled client connected to kad only we set the clientid to 1 as a kad user only has 1 buddy ctemp new c up down client temp tcp 1 0 0 false the only reason we set the real ip is for when we get a callback from this firewalled source the compare method will match them ctemp set source from sf kademlia ctemp set kad port udp byte cid 16 pcontactid to byte array cid ctemp set user hash cid pbuddyid to byte array cid ctemp set buddyid cid ctemp set buddyip serverip ctemp set buddy port serverport break if ctemp check and add source temp ctemp cdownloadqueue kademliasearchfile cuint128 cuint128 cpartfile getfilebykadfilesearchid isstopped getmaxsources getsourcecount ed2kip theapp isfiltered ed2kip theprefs getlogfilteredips adddebuglogline _t ipfiltered ed2kip theapp getlasthit ckademlia getipaddress ed2kip theapp getclientid theprefs getport cupdownclient nonfirewalled theprefs getverbose adddebuglogline _t cupdownclient setsourcefrom sf_kademlia setserverip setserverport setkadport tobytearray setuserhash cupdownclient setsourcefrom sf_kademlia setkadport tobytearray setuserhash tobytearray setbuddyid setbuddyip setbuddyport checkandaddsource void c download queue stopudp requests cur udpserver null lastudpsearchtime get tick count lastfile null m isearchedservers 0 cdownloadqueue stopudprequests cur_udpserver gettickcount m_isearchedservers void c download queue sort by priority uint n filelist get count if n return uint i for i n 2 i heap sort i n 1 for i n i swap parts filelist find index 0 filelist find index i heap sort 0 i 1 cdownloadqueue sortbypriority getcount heapsort swapparts findindex findindex heapsort void c download queue check diskspace bool b not enough space left lastcheckdiskspacetime get tick count sorting the list could be done here but i prefer to see that function call in the calling functions sort by priority if disabled resume any previously paused files if the prefs is check diskspace enabled if b not enough space left avoid worse case if we already had disk full for position pos1 filelist get head position pos1 null c part file cur file filelist get next pos1 switch cur file get status case ps paused case ps error case ps completing case ps complete continue cur file resume file insufficient return uint64 n total available space main b not enough space left 0 get free disk spacex the prefs get temp dir b not enough space left avoid worse case if we already had disk full if the prefs get min free disk space 0 for position pos1 filelist get head position pos1 null c part file cur file filelist get next pos1 uint64 n total available space b not enough space left 0 the prefs get temp dir count 1 n total available space main get free disk spacex cur file get temp path switch cur file get status case ps paused case ps error case ps completing case ps complete continue pause the file only if it would grow in size and would exceed the currently available free space uint64 n space to go cur file get needed space if n space to go n total available space n total available space n space to go cur file resume file insufficient else cur file pause file true b insufficient else for position pos1 filelist get head position pos1 null c part file cur file filelist get next pos1 switch cur file get status case ps paused case ps error case ps completing case ps complete continue uint64 n total available space b not enough space left 0 the prefs get temp dir count 1 n total available space main get free disk spacex cur file get temp path if n total available space the prefs get min free disk space if cur file is normal file normal files pause the file only if it would still grow uint64 n space to grow cur file get needed space if n space to grow 0 cur file pause file true b insufficient else compressed sparse files always pause the file cur file pause file true b insufficient else doesn t work this way resuming the file without checking if there is a chance to successfully flush any available buffered file data will pause the file right after it was resumed and disturb the stop paused file function cur file resume file insufficient cdownloadqueue checkdiskspace bnotenoughspaceleft gettickcount sortbypriority theprefs ischeckdiskspaceenabled bnotenoughspaceleft getheadposition cpartfile cur_file getnext cur_file getstatus ps_paused ps_error ps_completing ps_complete cur_file resumefileinsufficient ntotalavailablespacemain bnotenoughspaceleft getfreediskspacex theprefs gettempdir bnotenoughspaceleft theprefs getminfreediskspace getheadposition cpartfile cur_file getnext ntotalavailablespace bnotenoughspaceleft theprefs gettempdircount ntotalavailablespacemain getfreediskspacex cur_file gettemppath cur_file getstatus ps_paused ps_error ps_completing ps_complete nspacetogo cur_file getneededspace nspacetogo ntotalavailablespace ntotalavailablespace nspacetogo cur_file resumefileinsufficient cur_file pausefile binsufficient getheadposition cpartfile cur_file getnext cur_file getstatus ps_paused ps_error ps_completing ps_complete ntotalavailablespace bnotenoughspaceleft theprefs gettempdircount ntotalavailablespacemain getfreediskspacex cur_file gettemppath ntotalavailablespace theprefs getminfreediskspace cur_file isnormalfile nspacetogrow cur_file getneededspace nspacetogrow cur_file pausefile binsufficient cur_file pausefile binsufficient stoppausedfile cur_file resumefileinsufficient void c download queue check diskspace timed if lastcheckdiskspacetime get tick count lastcheckdiskspacetime diskspacerechecktime check diskspace cdownloadqueue checkdiskspacetimed gettickcount checkdiskspace void c download queue export part met files overview const c string str file list path the prefs get app dir t downloads txt c string str tmp file list path str file list path path rename extension str tmp file list path get buffer max path t tmp str tmp file list path release buffer c safe buffered file file c file exception fexp if file open str tmp file list path c file mode create c file mode write c file type binary c file share deny write fexp c string str error tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error t failed to create part met file list s str error return write unicode byte order mark 0xfeff fputwc 0xfeff file m pstream try file printf t date s r n c time get current time format t c if the prefs get temp dir count 1 file printf t directory s r n the prefs get temp dir file printf t r n file printf t part file ted2k link r n file printf t r n for position pos filelist get head position pos 0 const c part file p part file filelist get next pos if p part file get status true ps complete c string str part file path p part file get file path tchar sz nam max fname tchar sz ext max ext tsplitpath str part file path null null sz nam sz ext if the prefs get temp dir count 1 file printf t s s t s r n sz nam sz ext createed2k link p part file else file printf t s t s r n p part file get full name createed2k link p part file if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush flush file stream buffers to disk buffers if commit fileno file m pstream 0 commit disk buffers to disk afx throw file exception c file exception hardio get last error file get file name file close c string str bak file list path str file list path path rename extension str bak file list path get buffer max path t bak str bak file list path release buffer if taccess str bak file list path 0 0 c file remove str bak file list path if taccess str file list path 0 0 c file rename str file list path str bak file list path c file rename str tmp file list path str file list path catch c file exception e c string str error tchar sz error max cfexp errormsg if e get error message sz error arrsize sz error str error t str error sz error log error t failed to write part met file list s str error e delete file abort void tremove file get file path cdownloadqueue exportpartmetfilesoverview cstring strfilelistpath theprefs getappdir _t cstring strtmpfilelistpath strfilelistpath pathrenameextension strtmpfilelistpath getbuffer max_path _t strtmpfilelistpath releasebuffer csafebufferedfile cfileexception strtmpfilelistpath cfile modecreate cfile modewrite cfile typebinary cfile sharedenywrite cstring strerror szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror _t strerror m_pstream _t ctime getcurrenttime _t theprefs gettempdircount _t theprefs gettempdir _t _t _t getheadposition cpartfile ppartfile getnext ppartfile getstatus ps_complete cstring strpartfilepath ppartfile getfilepath sznam _max_fname szext _max_ext _tsplitpath strpartfilepath sznam szext theprefs gettempdircount _t sznam szext createed2klink ppartfile _t ppartfile getfullname createed2klink ppartfile theprefs getcommitfiles theprefs getcommitfiles theapp isrunning _commit _fileno m_pstream afxthrowfileexception cfileexception getlasterror getfilename cstring strbakfilelistpath strfilelistpath pathrenameextension strbakfilelistpath getbuffer max_path _t strbakfilelistpath releasebuffer _taccess strbakfilelistpath cfile strbakfilelistpath _taccess strfilelistpath cfile strfilelistpath strbakfilelistpath cfile strtmpfilelistpath strfilelistpath cfileexception cstring strerror szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror _t strerror _tremove getfilepath void c download queue on connection state bool b connected for position pos filelist get head position pos 0 c part file p part file filelist get next pos if p part file get status ps ready p part file get status ps empty p part file set active b connected cdownloadqueue onconnectionstate bconnected getheadposition cpartfile ppartfile getnext ppartfile getstatus ps_ready ppartfile getstatus ps_empty ppartfile setactive bconnected void c download queue add to resolved c part file p file s unresolved hostname puh if p file puh m srcwnd add to resolve p file get file hash puh str hostname puh n port puh strurl cdownloadqueue addtoresolved cpartfile pfile sunresolvedhostname pfile m_srcwnd addtoresolve pfile getfilehash strhostname nport c string c download queue get optimal temp dir uint n cat em file size n file size shortcut if the prefs tempdir get count 1 return the prefs get temp dir c map int int sint64 sint64 map needed space on drive c map int int sint64 sint64 map free space on drive sint64 ll buffer 0 sint64 ll highest free space 0 int n highest free space drive 1 first collect the free space on drives for int i 0 i the prefs tempdir get count i const int n drive number get path drive number the prefs get temp dir i if map free space on drive lookup n drive number ll buffer continue ll buffer get free disk spacex the prefs get temp dir i the prefs get min free disk space map free space on drive set at n drive number ll buffer if ll buffer ll highest free space n highest free space drive n drive number ll highest free space ll buffer now get the space we would need to download all files in the current queue position pos filelist get head position while pos null c part file p cur file filelist get next pos const int n drive number get path drive number p cur file get temp path sint64 ll needed for completion 0 switch p cur file get status false case ps ready case ps empty case ps waitingforhash case ps insufficient ll needed for completion p cur file get file size p cur file get real file size if ll needed for completion 0 ll needed for completion 0 ll buffer 0 map needed space on drive lookup n drive number ll buffer ll buffer ll needed for completion map needed space on drive set at n drive number ll buffer sint64 ll highest total space 0 int n highest total space dir 1 int n highest free space dir 1 int n any available dir 1 first round 0 on same drive as incomming and enough space for all downloading second round 1 enough space for all downloading third round 2 most actual free space for int i 0 i the prefs tempdir get count i const int n drive number get path drive number the prefs get temp dir i ll buffer 0 sint64 ll available space 0 map free space on drive lookup n drive number ll available space map needed space on drive lookup n drive number ll buffer ll available space ll buffer no condition can be met for a large file on a fat volume if n file size old max emule file size is file onfat volume the prefs get temp dir i condition 0 needs to be same drive and enough space if get path drive number the prefs get cat path n cat n drive number ll available space sint64 n file size this one is perfect return the prefs get temp dir i condition 1 needs to have enough space for downloading if ll available space sint64 n file size ll available space ll highest total space ll highest total space ll available space n highest total space dir i condition 2 first one which has the highest actualy free space if n drive number n highest free space drive n highest free space dir 1 n highest free space dir i condition 3 any directory which can be used for this file ak not fat for large files if n any available dir 1 n any available dir i if n highest total space dir 1 condtion 0 was apperently too much take 1 return the prefs get temp dir n highest total space dir else if n highest free space dir 1 condtion 1 could not be met too take 2 return the prefs get temp dir n highest free space dir else if n any available dir 1 return the prefs get temp dir n any available dir else so was condtion 2 and 3 take 4 wait there is no 3 this must be a bug assert false return the prefs get temp dir cstring cdownloadqueue getoptimaltempdir ncat emfilesize nfilesize theprefs getcount theprefs gettempdir cmap mapneededspaceondrive cmap mapfreespaceondrive llbuffer llhighestfreespace nhighestfreespacedrive theprefs getcount ndrivenumber getpathdrivenumber theprefs gettempdir mapfreespaceondrive ndrivenumber llbuffer llbuffer getfreediskspacex theprefs gettempdir theprefs getminfreediskspace mapfreespaceondrive setat ndrivenumber llbuffer llbuffer llhighestfreespace nhighestfreespacedrive ndrivenumber llhighestfreespace llbuffer getheadposition cpartfile pcurfile getnext ndrivenumber getpathdrivenumber pcurfile gettemppath llneededforcompletion pcurfile getstatus ps_ready ps_empty ps_waitingforhash ps_insufficient llneededforcompletion pcurfile getfilesize pcurfile getrealfilesize llneededforcompletion llneededforcompletion llbuffer mapneededspaceondrive ndrivenumber llbuffer llbuffer llneededforcompletion mapneededspaceondrive setat ndrivenumber llbuffer llhighesttotalspace nhighesttotalspacedir nhighestfreespacedir nanyavailabledir theprefs getcount ndrivenumber getpathdrivenumber theprefs gettempdir llbuffer llavailablespace mapfreespaceondrive ndrivenumber llavailablespace mapneededspaceondrive ndrivenumber llbuffer llavailablespace llbuffer nfilesize old_max_emule_file_size isfileonfatvolume theprefs gettempdir getpathdrivenumber theprefs getcatpath ncat ndrivenumber llavailablespace nfilesize theprefs gettempdir llavailablespace nfilesize llavailablespace llhighesttotalspace llhighesttotalspace llavailablespace nhighesttotalspacedir ndrivenumber nhighestfreespacedrive nhighestfreespacedir nhighestfreespacedir nanyavailabledir nanyavailabledir nhighesttotalspacedir theprefs gettempdir nhighesttotalspacedir nhighestfreespacedir theprefs gettempdir nhighestfreespacedir nanyavailabledir theprefs gettempdir nanyavailabledir theprefs gettempdir bool c download queue send nextudp packet if filelist is empty the app serverconnect isudp socket available the app serverconnect is connected return false c server p connected server the app serverconnect get current server if p connected server p connected server the app serverlist get server by address p connected server get address p connected server get port if cur udpserver while cur udpserver the app serverlist get next server cur udpserver null if cur udpserver p connected server continue if cur udpserver get failed count the prefs get dead server retries continue break if cur udpserver null stopudp requests return false m crequestssenttoserver 0 bool b get sources2 packet cur udpserver getudp flags srv udpflg ext getsources2 0 bool b server supports large files cur udpserver supports large filesudp loop until the packet is filled or a packet was sent bool b sent packet false c safe mem file data glob get sources 20 int i files 0 int i large files 0 while is max files perudp server packet reached i files i large files b sent packet get next file to search sources for c part file nextfile null while b sent packet nextfile nextfile get status ps ready nextfile get status ps empty if lastfile null we just started the global source searching or have switched the server get first file to search sources for nextfile filelist get head lastfile nextfile else position pos filelist find lastfile if pos 0 the last file is no longer in the dl list may have been finished or canceld get first file to search sources for nextfile filelist get head lastfile nextfile else filelist get next pos if pos 0 finished asking the current server for all files if there are pending requests for the current server send them if data glob get sources get length 0 if send glob get sourcesudp packet data glob get sources b get sources2 packet i files i large files b sent packet true data glob get sources set length 0 i files 0 i large files 0 get next server to ask while cur udpserver the app serverlist get next server cur udpserver null if cur udpserver p connected server continue if cur udpserver get failed count the prefs get dead server retries continue break m crequestssenttoserver 0 if cur udpserver null finished asking all servers for all files if the prefs get debug serverudp level 0 the prefs get debug server sources level 0 debug t finished udp search processing for all servers u n the app serverlist get server count stopudp requests return false finished processed all file all servers m isearchedservers if we already sent a packet switch to the next file at next function call if b sent packet lastfile null break b get sources2 packet cur udpserver getudp flags srv udpflg ext getsources2 0 b server supports large files cur udpserver supports large filesudp have selected a new server get first file to search sources for nextfile filelist get head lastfile nextfile else nextfile filelist get at pos lastfile nextfile if b sent packet nextfile nextfile get source count nextfile get max source per fileudp b server supports large files nextfile is large file if b get sources2 packet if nextfile is large file getsources2 packet large file hash 16 ind 4 0 size 8 i large files data glob get sources write hash16 nextfile get file hash data glob get sources writeu int32 0 data glob get sources writeu int64 nextfile get file size else getsources2 packet hash 16 size 4 data glob get sources write hash16 nextfile get file hash data glob get sources writeu int32 uint32 uint64 nextfile get file size else getsources packet hash 16 data glob get sources write hash16 nextfile get file hash i files if the prefs get debug serverudp level 0 the prefs get debug server sources level 0 debug t queued s to server 21s 3u of 3u buff u u s n b get sources2 packet t op globgetsources2 t op globgetsources1 ipstr cur udpserver get address cur udpserver get port m isearchedservers 1 the app serverlist get server count i files i large files dbg get file info nextfile get file hash assert data glob get sources get length 0 b sent packet if b sent packet data glob get sources get length 0 send glob get sourcesudp packet data glob get sources b get sources2 packet i files i large files send max 35 udp request to one server per interval if we have more than 35 files we rotate the list and use it as queue if m crequestssenttoserver max requests per server if the prefs get debug serverudp level 0 the prefs get debug server sources level 0 debug t rotating file list n move the last 35 files to the head if filelist get count max requests per server for int i 0 i max requests per server i filelist add head filelist remove tail and next server while cur udpserver the app serverlist get next server cur udpserver null if cur udpserver p connected server continue if cur udpserver get failed count the prefs get dead server retries continue break m crequestssenttoserver 0 if cur udpserver null if the prefs get debug serverudp level 0 the prefs get debug server sources level 0 debug t finished udp search processing for all servers u n the app serverlist get server count stopudp requests return false finished processed all file all servers m isearchedservers lastfile null return true cdownloadqueue sendnextudppacket isempty theapp isudpsocketavailable theapp isconnected cserver pconnectedserver theapp getcurrentserver pconnectedserver pconnectedserver theapp getserverbyaddress pconnectedserver getaddress pconnectedserver getport cur_udpserver cur_udpserver theapp getnextserver cur_udpserver cur_udpserver pconnectedserver cur_udpserver getfailedcount theprefs getdeadserverretries cur_udpserver stopudprequests m_crequestssenttoserver bgetsources2packet cur_udpserver getudpflags srv_udpflg_ext_getsources2 bserversupportslargefiles cur_udpserver supportslargefilesudp bsentpacket csafememfile dataglobgetsources ifiles ilargefiles ismaxfilesperudpserverpacketreached ifiles ilargefiles bsentpacket cpartfile bsentpacket getstatus ps_ready getstatus ps_empty gethead gethead getnext dataglobgetsources getlength sendglobgetsourcesudppacket dataglobgetsources bgetsources2packet ifiles ilargefiles bsentpacket dataglobgetsources setlength ifiles ilargefiles cur_udpserver theapp getnextserver cur_udpserver cur_udpserver pconnectedserver cur_udpserver getfailedcount theprefs getdeadserverretries m_crequestssenttoserver cur_udpserver theprefs getdebugserverudplevel theprefs getdebugserversourceslevel _t theapp getservercount stopudprequests m_isearchedservers bsentpacket bgetsources2packet cur_udpserver getudpflags srv_udpflg_ext_getsources2 bserversupportslargefiles cur_udpserver supportslargefilesudp gethead getat bsentpacket getsourcecount getmaxsourceperfileudp bserversupportslargefiles islargefile bgetsources2packet islargefile hash_16 ind_4 size_8 ilargefiles dataglobgetsources writehash16 getfilehash dataglobgetsources writeuint32 dataglobgetsources writeuint64 getfilesize hash_16 size_4 dataglobgetsources writehash16 getfilehash dataglobgetsources writeuint32 getfilesize hash_16 dataglobgetsources writehash16 getfilehash ifiles theprefs getdebugserverudplevel theprefs getdebugserversourceslevel _t bgetsources2packet _t op__globgetsources2 _t op__globgetsources1 cur_udpserver getaddress cur_udpserver getport m_isearchedservers theapp getservercount ifiles ilargefiles dbggetfileinfo getfilehash dataglobgetsources getlength bsentpacket bsentpacket dataglobgetsources getlength sendglobgetsourcesudppacket dataglobgetsources bgetsources2packet ifiles ilargefiles m_crequestssenttoserver max_requests_per_server theprefs getdebugserverudplevel theprefs getdebugserversourceslevel _t getcount max_requests_per_server max_requests_per_server addhead removetail cur_udpserver theapp getnextserver cur_udpserver cur_udpserver pconnectedserver cur_udpserver getfailedcount theprefs getdeadserverretries m_crequestssenttoserver cur_udpserver theprefs getdebugserverudplevel theprefs getdebugserversourceslevel _t theapp getservercount stopudprequests m_isearchedservers void c download queue process local requests if m localserverreqqueue is empty m dwnexttcpsrcreq get tick count c safe mem file data tcp frame 22 const int i max files per tcp frame 15 int i files 0 while m localserverreqqueue is empty i files i max files per tcp frame find the file with the longest waitingtime position pos1 pos2 uint32 dw best wait time 0xffffffff position pos next request null c part file cur file for pos1 m localserverreqqueue get head position pos2 pos1 null m localserverreqqueue get next pos1 cur file m localserverreqqueue get at pos2 if cur file get status ps ready cur file get status ps empty uint8 n priority cur file get down priority if n priority pr high assert 0 n priority pr high if cur file m lastsearchtime pr high n priority dw best wait time dw best wait time cur file m lastsearchtime pr high n priority pos next request pos2 else m localserverreqqueue remove at pos2 cur file m blocalsrcreqqueued false if the prefs get debug source exchange add debug log line false t sx send local server source request for file s not sent because of status s cur file get file name cur file get partfile status if pos next request null cur file m localserverreqqueue get at pos next request cur file m blocalsrcreqqueued false cur file m lastsearchtime get tick count m localserverreqqueue remove at pos next request if cur file is large file the app serverconnect get current server null the app serverconnect get current server supports large filestcp assert false debug log error t large file s on local requestqueue for server without support for large files cur file get file name continue i files create request packet c safe mem file sm packet sm packet write hash16 cur file get file hash if cur file is large file sm packet writeu int32 uint32 uint64 cur file get file size else sm packet writeu int32 0 indicates that this is a large file and a uint64 follows sm packet writeu int64 cur file get file size packet packet new packet sm packet op edonkeyprot op getsources if the prefs get debug servertcp level 0 debug t sending op getsources 2u 2u s n i files i max files per tcp frame dbg get file info cur file get file hash data tcp frame write packet get packet packet get real packet size delete packet if the prefs get debug source exchange add debug log line false t sx send local server source request file s cur file get file name int i size int data tcp frame get length if i size 0 create one packet which contains all buffered op getsources ed2k packets to be sent with one tcp frame server credits 16 i max files per tcp frame 1 241 packet packet new packet new char i size uint data tcp frame get length true false data tcp frame seek 0 c file begin data tcp frame read packet get packet i size the stats add up data overhead server packet size the app serverconnect send packet packet true next tcp frame with up to 15 source requests is allowed to be sent in m dwnexttcpsrcreq get tick count sec2ms i max files per tcp frame 16 4 cdownloadqueue processlocalrequests m_localserverreqqueue isempty m_dwnexttcpsrcreq gettickcount csafememfile datatcpframe imaxfilespertcpframe ifiles m_localserverreqqueue isempty ifiles imaxfilespertcpframe dwbestwaittime posnextrequest cpartfile cur_file m_localserverreqqueue getheadposition m_localserverreqqueue getnext cur_file m_localserverreqqueue getat cur_file getstatus ps_ready cur_file getstatus ps_empty npriority cur_file getdownpriority npriority pr_high npriority pr_high cur_file m_lastsearchtime pr_high npriority dwbestwaittime dwbestwaittime cur_file m_lastsearchtime pr_high npriority posnextrequest m_localserverreqqueue removeat cur_file m_blocalsrcreqqueued theprefs getdebugsourceexchange adddebuglogline _t sxsend cur_file getfilename cur_file getpartfilestatus posnextrequest cur_file m_localserverreqqueue getat posnextrequest cur_file m_blocalsrcreqqueued cur_file m_lastsearchtime gettickcount m_localserverreqqueue removeat posnextrequest cur_file islargefile theapp getcurrentserver theapp getcurrentserver supportslargefilestcp debuglogerror _t cur_file getfilename ifiles csafememfile smpacket smpacket writehash16 cur_file getfilehash cur_file islargefile smpacket writeuint32 cur_file getfilesize smpacket writeuint32 smpacket writeuint64 cur_file getfilesize smpacket op_edonkeyprot op_getsources theprefs getdebugservertcplevel _t op__getsources ifiles imaxfilespertcpframe dbggetfileinfo cur_file getfilehash datatcpframe getpacket getrealpacketsize theprefs getdebugsourceexchange adddebuglogline _t sxsend cur_file getfilename isize datatcpframe getlength isize op_getsources imaxfilespertcpframe isize datatcpframe getlength datatcpframe cfile datatcpframe getpacket isize thestats addupdataoverheadserver theapp sendpacket m_dwnexttcpsrcreq gettickcount imaxfilespertcpframe bool c download queue is max files perudp server packet reached uint32 n files uint32 n included large files const if cur udpserver cur udpserver getudp flags srv udpflg ext getsources const int n bytes per normal file cur udpserver getudp flags srv udpflg ext getsources2 0 bytes per file g2 bytes per file g1 const int n used bytes n files n bytes per normal file n included large files additional bytes per largefile if n included large files 0 assert cur udpserver supports large filesudp assert cur udpserver getudp flags srv udpflg ext getsources2 return m crequestssenttoserver max requests per server n used bytes max udp packet data else assert n included large files 0 return n files 0 cdownloadqueue ismaxfilesperudpserverpacketreached nfiles nincludedlargefiles cur_udpserver cur_udpserver getudpflags srv_udpflg_ext_getsources nbytespernormalfile cur_udpserver getudpflags srv_udpflg_ext_getsources2 bytes_per_file_g2 bytes_per_file_g1 nusedbytes nfiles nbytespernormalfile nincludedlargefiles additional_bytes_per_largefile nincludedlargefiles cur_udpserver supportslargefilesudp cur_udpserver getudpflags srv_udpflg_ext_getsources2 m_crequestssenttoserver max_requests_per_server nusedbytes max_udp_packet_data nincludedlargefiles nfiles bool c download queue send glob get sourcesudp packet c safe mem file data bool b ext2 packet uint32 n files uint32 n included large files bool b sent packet false if cur udpserver int i packet size int data get length packet packet data data null if b ext2 packet assert i packet size 0 uint32 i packet size n files 20 n included large files 8 packet opcode op globgetsources2 else assert i packet size 0 uint32 i packet size n files 16 n included large files 0 packet opcode op globgetsources if the prefs get debug serverudp level 0 debug t sending s to server 21s 3u of 3u filei ds u u large n packet opcode op globgetsources2 t op globgetsources2 t op globgetsources1 ipstr cur udpserver get address cur udpserver get port m isearchedservers 1 the app serverlist get server count n files n included large files the stats add up data overhead server packet size the app serverconnect sendudp packet packet cur udpserver false m crequestssenttoserver n files b sent packet true return b sent packet cdownloadqueue sendglobgetsourcesudppacket csafememfile bext2packet nfiles nincludedlargefiles bsentpacket cur_udpserver ipacketsize getlength bext2packet ipacketsize ipacketsize nfiles nincludedlargefiles op_globgetsources2 ipacketsize ipacketsize nfiles nincludedlargefiles op_globgetsources theprefs getdebugserverudplevel _t fileids op_globgetsources2 _t op__globgetsources2 _t op__globgetsources1 cur_udpserver getaddress cur_udpserver getport m_isearchedservers theapp getservercount nfiles nincludedlargefiles thestats addupdataoverheadserver theapp sendudppacket cur_udpserver m_crequestssenttoserver nfiles bsentpacket bsentpacket bool c download queue compare parts position pos1 position pos2 c part file file1 filelist get at pos1 c part file file2 filelist get at pos2 return c part file right file has higher prio file1 file2 cdownloadqueue compareparts cpartfile getat cpartfile getat cpartfile rightfilehashigherprio void c download queue swap parts position pos1 position pos2 c part file file1 filelist get at pos1 c part file file2 filelist get at pos2 filelist set at pos1 file2 filelist set at pos2 file1 cdownloadqueue swapparts cpartfile getat cpartfile getat setat setat void c download queue heap sort uint first uint last uint r position pos1 filelist find index first for r first r uint int min r 1 last uint r2 r 1 1 position pos2 filelist find index r2 if r2 last position pos3 pos2 filelist get next pos3 if compare parts pos2 pos3 pos2 pos3 r2 if compare parts pos1 pos2 swap parts pos1 pos2 r r2 pos1 pos2 else break cdownloadqueue heapsort findindex int_min findindex getnext compareparts compareparts swapparts upload bandwidth throttler upload bandwidth throttler void m sentbytessincelastcall 0 m sentbytessincelastcalloverhead 0 m highestnumberoffullyactivatedslots 0 thread ended event new c event 0 1 pause event new c event true true do run true afx begin thread run proc lpvoid this uploadbandwidththrottler uploadbandwidththrottler m_sentbytessincelastcall m_sentbytessincelastcalloverhead m_highestnumberoffullyactivatedslots threadendedevent cevent pauseevent cevent dorun afxbeginthread runproc upload bandwidth throttler upload bandwidth throttler void end thread delete thread ended event delete pause event uploadbandwidththrottler uploadbandwidththrottler endthread threadendedevent pauseevent uint64 upload bandwidth throttler get number of sent bytes since last call and reset send locker lock uint64 number of sent bytes since last call m sentbytessincelastcall m sentbytessincelastcall 0 send locker unlock return number of sent bytes since last call uploadbandwidththrottler getnumberofsentbytessincelastcallandreset sendlocker numberofsentbytessincelastcall m_sentbytessincelastcall m_sentbytessincelastcall sendlocker numberofsentbytessincelastcall uint64 upload bandwidth throttler get number of sent bytes overhead since last call and reset send locker lock uint64 number of sent bytes since last call m sentbytessincelastcalloverhead m sentbytessincelastcalloverhead 0 send locker unlock return number of sent bytes since last call uploadbandwidththrottler getnumberofsentbytesoverheadsincelastcallandreset sendlocker numberofsentbytessincelastcall m_sentbytessincelastcalloverhead m_sentbytessincelastcalloverhead sendlocker numberofsentbytessincelastcall uint32 upload bandwidth throttler get highest number of fully activated slots since last call and reset send locker lock if m highestnumberoffullyactivatedslots uint32 m standardorder list get size the app queue debug log line true t upload bandwidth throttler throttler wants new slot when get method called m highestnumberoffullyactivatedslots i m standardorder list get size i tick i m highestnumberoffullyactivatedslots m standardorder list get size get tick count uint32 highest number of fully activated slots m highestnumberoffullyactivatedslots m highestnumberoffullyactivatedslots 0 send locker unlock return highest number of fully activated slots uploadbandwidththrottler gethighestnumberoffullyactivatedslotssincelastcallandreset sendlocker m_highestnumberoffullyactivatedslots m_standardorder_list getsize theapp queuedebuglogline _t uploadbandwidththrottler m_highestnumberoffullyactivatedslots m_standardorder_list getsize m_highestnumberoffullyactivatedslots m_standardorder_list getsize gettickcount highestnumberoffullyactivatedslots m_highestnumberoffullyactivatedslots m_highestnumberoffullyactivatedslots sendlocker highestnumberoffullyactivatedslots void upload bandwidth throttler add to standard list uint32 index throttled file socket socket if socket null send locker lock remove from standard list no lock socket if index uint32 m standardorder list get size index m standardorder list get size m standardorder list insert at index socket send locker unlock else if the prefs get verbose the app add debug log line true tried to add null socket to upload bandwidth throttler standard list prevented uploadbandwidththrottler addtostandardlist throttledfilesocket sendlocker removefromstandardlistnolock m_standardorder_list getsize m_standardorder_list getsize m_standardorder_list insertat sendlocker theprefs getverbose theapp adddebuglogline uploadbandwidththrottler bool upload bandwidth throttler remove from standard list throttled file socket socket bool return value send locker lock return value remove from standard list no lock socket send locker unlock return return value uploadbandwidththrottler removefromstandardlist throttledfilesocket returnvalue sendlocker returnvalue removefromstandardlistnolock sendlocker returnvalue void upload bandwidth throttler queue for sending control packet throttled control socket socket bool has sent get critical section temp queue locker lock if do run if has sent m tempcontrolqueuefirst list add tail socket else m tempcontrolqueue list add tail socket end critical section temp queue locker unlock uploadbandwidththrottler queueforsendingcontrolpacket throttledcontrolsocket hassent tempqueuelocker dorun hassent m_tempcontrolqueuefirst_list addtail m_tempcontrolqueue_list addtail tempqueuelocker void upload bandwidth throttler remove from all queues throttled file socket socket get critical section send locker lock if do run remove from all queues socket false and remove it from upload slots remove from standard list no lock socket end critical section send locker unlock uploadbandwidththrottler removefromallqueues throttledfilesocket sendlocker dorun removefromallqueues removefromstandardlistnolock sendlocker void upload bandwidth throttler end thread send locker lock signal the thread to stop looping and exit do run false send locker unlock pause false wait for the thread to signal that it has stopped looping thread ended event lock uploadbandwidththrottler endthread sendlocker dorun sendlocker threadendedevent void upload bandwidth throttler pause bool paused if paused pause event reset event else pause event set event uploadbandwidththrottler pauseevent resetevent pauseevent setevent uint32 upload bandwidth throttler get slot limit uint32 current up speed uint32 up per client upload client datarate if throttler doesn t require another slot go with a slightly more restrictive method if current up speed 20 1024 up per client current up speed 43 if up per client 7680 up per client 7680 now the final check uint16 n max slots if current up speed 12 1024 n max slots uint16 float current up speed up per client else if current up speed 7 1024 n max slots min up clients allowed 2 else if current up speed 3 1024 n max slots min up clients allowed 1 else n max slots min up clients allowed return max n max slots min up clients allowed uploadbandwidththrottler getslotlimit currentupspeed upperclient upload_client_datarate currentupspeed upperclient currentupspeed upperclient upperclient nmaxslots currentupspeed nmaxslots currentupspeed upperclient currentupspeed nmaxslots min_up_clients_allowed currentupspeed nmaxslots min_up_clients_allowed nmaxslots min_up_clients_allowed nmaxslots min_up_clients_allowed uint afx cdecl upload bandwidth throttler run proc lpvoid p param dbg set thread name upload bandwidth throttler init thread locale upload bandwidth throttler upload bandwidth throttler upload bandwidth throttler p param return upload bandwidth throttler run internal afx_cdecl uploadbandwidththrottler runproc pparam dbgsetthreadname uploadbandwidththrottler initthreadlocale uploadbandwidththrottler uploadbandwidththrottler uploadbandwidththrottler pparam uploadbandwidththrottler runinternal uint upload bandwidth throttler run internal dword last loop tick time get time sint64 real bytes to spend 0 uint32 allowed data rate 0 uint32 remembered slot counter 0 dword last tick reached bandwidth time get time uint32 n estiminated limit 0 int n slots busy level 0 dword n upload start time 0 uint32 number of consecutive up changes 0 uint32 number of consecutive down changes 0 uint32 changes count 0 uint32 loops count 0 bool estimate changed log false bool lots of log false while do run pause event lock dword time since last loop time get time last loop tick get current speed from upload speed sense allowed data rate the app last common route finder get upload check busy level for all the slots wsaewouldblock status uint32 c busy 0 uint32 n can send 0 send locker lock for int i 0 i m standardorder list get size i 3 uint i get slot limit the app uploadqueue get datarate i if m standardorder list i null m standardorder list i has queues n can send if m standardorder list i is busy c busy send locker unlock if this is kept the loop above can be a little optimized don t count n can send just use n can send get slot limit the app uploadqueue get datarate if the app uploadqueue n can send max n can send get slot limit the app uploadqueue get datarate when no upload limit has been set in options try to guess a good upload limit bool b upload unlimited the prefs get max upload unlimited if b upload unlimited loops count if lots of log the app queue debug log line false t throttler busy i i n slots busy level i guessed limit 0 5f changes count i loops count i c busy n can send n slots busy level float n estiminated limit 1024 00f changes count loops count if n can send 0 float f busy percent float c busy float n can send 100 if c busy 2 f busy percent 75 00f n slots busy level 255 n slots busy level changes count if the prefs get verbose lots of log n slots busy level 25 0 the app queue debug log line false t throttler n slots busy level i guessed limit 0 5f changes count i loops count i n slots busy level float n estiminated limit 1024 00f changes count loops count else if c busy 2 f busy percent 25 00f n slots busy level 255 n slots busy level changes count if the prefs get verbose lots of log n slots busy level 25 0 the app queue debug log line false t throttler n slots busy level i guessed limit 0 5f changes count i loops count i n slots busy level float n estiminated limit 1024 00f changes count loops count if n upload start time 0 if m standardorder list get size 3 n upload start time time get time else if time get time n upload start time sec2ms 60 if the app uploadqueue if n estiminated limit 0 no autolimit was set yet if n slots busy level 250 sockets indicated that the bw limit has been reached n estiminated limit the app uploadqueue get datarate allowed data rate min n estiminated limit allowed data rate n slots busy level 200 if the prefs get verbose estimate changed log the app queue debug log line false t throttler set inital estimated limit to 0 5f changes count i loops count i float n estiminated limit 1024 00f changes count loops count changes count 0 loops count 0 else if n slots busy level 250 if changes count 500 changes count 300 loops count 1000 loops count 2000 number of consecutive down changes 0 number of consecutive down changes uint32 change delta calculate change delta number of consecutive down changes don t lower speed below 1 k bytes s if n estiminated limit change delta 1024 if n estiminated limit 1024 change delta n estiminated limit 1024 else change delta 0 assert n estiminated limit change delta 1024 n estiminated limit change delta if the prefs get verbose estimate changed log the app queue debug log line false t throttler reduced limit i with i bytes to 0 5f changes count i loops count i number of consecutive down changes change delta float n estiminated limit 1024 00f changes count loops count number of consecutive up changes 0 n slots busy level 0 changes count 0 loops count 0 else if n slots busy level 250 if changes count 500 changes count 300 loops count 1000 loops count 2000 number of consecutive up changes 0 number of consecutive up changes uint32 change delta calculate change delta number of consecutive up changes don t raise speed unless we are under current allowed data rate if n estiminated limit change delta allowed data rate if n estiminated limit allowed data rate change delta allowed data rate n estiminated limit else change delta 0 assert n estiminated limit allowed data rate n estiminated limit change delta allowed data rate n estiminated limit allowed data rate change delta 0 n estiminated limit change delta if the prefs get verbose estimate changed log the app queue debug log line false t throttler increased limit i with i bytes to 0 5f changes count i loops count i number of consecutive up changes change delta float n estiminated limit 1024 00f changes count loops count number of consecutive down changes 0 n slots busy level 0 changes count 0 loops count 0 allowed data rate min n estiminated limit allowed data rate if c busy n can send m standardorder list get size 0 allowed data rate 0 if n slots busy level 125 b upload unlimited n slots busy level 125 if the prefs get verbose lots of log the app queue debug log line false t throttler n slots busy level i guessed limit 0 5f changes count i loops count i set due to all slots busy n slots busy level float n estiminated limit 1024 00f changes count loops count uint32 min frag size 1300 uint32 double send size min frag size 2 send two packages at a time so they can share an ack if allowed data rate 6 1024 min frag size 536 double send size min frag size don t send two packages at a time at very low speeds to give them a smoother load define time between upload loops 1 uint32 sleep time if allowed data rate ui32 max real bytes to spend 1000 allowed data rate 0 n estiminated limit 0 we could send at once but sleep a while to not suck up all cpu sleep time time between upload loops else if allowed data rate 0 sleep time max uint32 ceil double double send size n estiminated limit time between upload loops else sleep for just as long as we need to get back to having one byte to send sleep time max uint32 ceil double real bytes to spend 1000 allowed data rate time between upload loops if time since last loop sleep time sleep sleep time time since last loop const dword this loop tick time get time time since last loop this loop tick last loop tick calculate how many bytes we can spend sint64 bytes to spend 0 if allowed data rate ui32 max prevent overflow if time since last loop 0 no time has passed so don t add any bytes shouldn t happen bytes to spend 0 real bytes to spend 1000 else if i64 max time since last loop allowed data rate i64 max allowed data rate time since last loop real bytes to spend if time since last loop sleep time 2000 the app queue debug log line false t upload bandwidth throttler time since last loop too long time ims wanted ims max ims time since last loop sleep time sleep time 2000 time since last loop sleep time 2000 last loop tick this loop tick time since last loop real bytes to spend allowed data rate time since last loop bytes to spend real bytes to spend 1000 uploadbandwidththrottler runinternal lastlooptick timegettime realbytestospend alloweddatarate rememberedslotcounter lasttickreachedbandwidth timegettime nestiminatedlimit nslotsbusylevel nuploadstarttime numberofconsecutiveupchanges numberofconsecutivedownchanges changescount loopscount estimatechangedlog lotsoflog dorun pauseevent timesincelastloop timegettime lastlooptick uploadspeedsense alloweddatarate theapp lastcommonroutefinder getupload cbusy ncansend sendlocker m_standardorder_list getsize getslotlimit theapp getdatarate m_standardorder_list m_standardorder_list hasqueues ncansend m_standardorder_list isbusy cbusy sendlocker ncansend ncansend getslotlimit theapp getdatarate theapp ncansend ncansend getslotlimit theapp getdatarate buploadunlimited theprefs getmaxupload buploadunlimited loopscount lotsoflog theapp queuedebuglogline _t nslotsbusylevel changescount loopscount cbusy ncansend nslotsbusylevel nestiminatedlimit changescount loopscount ncansend fbusypercent cbusy ncansend cbusy fbusypercent nslotsbusylevel nslotsbusylevel changescount theprefs getverbose lotsoflog nslotsbusylevel theapp queuedebuglogline _t nslotsbusylevel changescount loopscount nslotsbusylevel nestiminatedlimit changescount loopscount cbusy fbusypercent nslotsbusylevel nslotsbusylevel changescount theprefs getverbose lotsoflog nslotsbusylevel theapp queuedebuglogline _t nslotsbusylevel changescount loopscount nslotsbusylevel nestiminatedlimit changescount loopscount nuploadstarttime m_standardorder_list getsize nuploadstarttime timegettime timegettime nuploadstarttime theapp nestiminatedlimit nslotsbusylevel nestiminatedlimit theapp getdatarate alloweddatarate nestiminatedlimit alloweddatarate nslotsbusylevel theprefs getverbose estimatechangedlog theapp queuedebuglogline _t changescount loopscount nestiminatedlimit changescount loopscount changescount loopscount nslotsbusylevel changescount changescount loopscount loopscount numberofconsecutivedownchanges numberofconsecutivedownchanges changedelta calculatechangedelta numberofconsecutivedownchanges kbytes nestiminatedlimit changedelta nestiminatedlimit changedelta nestiminatedlimit changedelta nestiminatedlimit changedelta nestiminatedlimit changedelta theprefs getverbose estimatechangedlog theapp queuedebuglogline _t changescount loopscount numberofconsecutivedownchanges changedelta nestiminatedlimit changescount loopscount numberofconsecutiveupchanges nslotsbusylevel changescount loopscount nslotsbusylevel changescount changescount loopscount loopscount numberofconsecutiveupchanges numberofconsecutiveupchanges changedelta calculatechangedelta numberofconsecutiveupchanges alloweddatarate nestiminatedlimit changedelta alloweddatarate nestiminatedlimit alloweddatarate changedelta alloweddatarate nestiminatedlimit changedelta nestiminatedlimit alloweddatarate nestiminatedlimit changedelta alloweddatarate nestiminatedlimit alloweddatarate changedelta nestiminatedlimit changedelta theprefs getverbose estimatechangedlog theapp queuedebuglogline _t changescount loopscount numberofconsecutiveupchanges changedelta nestiminatedlimit changescount loopscount numberofconsecutivedownchanges nslotsbusylevel changescount loopscount alloweddatarate nestiminatedlimit alloweddatarate cbusy ncansend m_standardorder_list getsize alloweddatarate nslotsbusylevel buploadunlimited nslotsbusylevel theprefs getverbose lotsoflog theapp queuedebuglogline _t nslotsbusylevel changescount loopscount nslotsbusylevel nestiminatedlimit changescount loopscount minfragsize doublesendsize minfragsize alloweddatarate minfragsize doublesendsize minfragsize time_between_upload_loops sleeptime alloweddatarate _ui32_max realbytestospend alloweddatarate nestiminatedlimit sleeptime time_between_upload_loops alloweddatarate sleeptime doublesendsize nestiminatedlimit time_between_upload_loops sleeptime realbytestospend alloweddatarate time_between_upload_loops timesincelastloop sleeptime sleeptime timesincelastloop thislooptick timegettime timesincelastloop thislooptick lastlooptick bytestospend alloweddatarate _ui32_max timesincelastloop bytestospend realbytestospend _i64_max timesincelastloop alloweddatarate _i64_max alloweddatarate timesincelastloop realbytestospend timesincelastloop sleeptime theapp queuedebuglogline _t uploadbandwidththrottler timesincelastloop sleeptime sleeptime timesincelastloop sleeptime lastlooptick thislooptick timesincelastloop realbytestospend alloweddatarate timesincelastloop bytestospend realbytestospend void upload bandwidth throttler remove from all queues throttled control socket socket bool lock if lock get critical section send locker lock if do run remove this socket from control packet queue position pos1 pos2 for pos1 m controlqueue list get head position pos2 pos1 null m controlqueue list get next pos1 throttled control socket socketin queue m controlqueue list get at pos2 if socketin queue socket m controlqueue list remove at pos2 position pos1 pos2 for pos1 m controlqueuefirst list get head position pos2 pos1 null m controlqueuefirst list get next pos1 throttled control socket socketin queue m controlqueuefirst list get at pos2 if socketin queue socket m controlqueuefirst list remove at pos2 temp queue locker lock position pos1 pos2 for pos1 m tempcontrolqueue list get head position pos2 pos1 null m tempcontrolqueue list get next pos1 throttled control socket socketin queue m tempcontrolqueue list get at pos2 if socketin queue socket m tempcontrolqueue list remove at pos2 position pos1 pos2 for pos1 m tempcontrolqueuefirst list get head position pos2 pos1 null m tempcontrolqueuefirst list get next pos1 throttled control socket socketin queue m tempcontrolqueuefirst list get at pos2 if socketin queue socket m tempcontrolqueuefirst list remove at pos2 temp queue locker unlock if lock end critical section send locker unlock uploadbandwidththrottler removefromallqueues throttledcontrolsocket sendlocker dorun m_controlqueue_list getheadposition m_controlqueue_list getnext throttledcontrolsocket socketinqueue m_controlqueue_list getat socketinqueue m_controlqueue_list removeat m_controlqueuefirst_list getheadposition m_controlqueuefirst_list getnext throttledcontrolsocket socketinqueue m_controlqueuefirst_list getat socketinqueue m_controlqueuefirst_list removeat tempqueuelocker m_tempcontrolqueue_list getheadposition m_tempcontrolqueue_list getnext throttledcontrolsocket socketinqueue m_tempcontrolqueue_list getat socketinqueue m_tempcontrolqueue_list removeat m_tempcontrolqueuefirst_list getheadposition m_tempcontrolqueuefirst_list getnext throttledcontrolsocket socketinqueue m_tempcontrolqueuefirst_list getat socketinqueue m_tempcontrolqueuefirst_list removeat tempqueuelocker sendlocker bool upload bandwidth throttler remove from standard list no lock throttled file socket socket find the slot int slot counter 0 bool found socket false while slot counter m standardorder list get size found socket false if m standardorder list get at slot counter socket remove the slot m standardorder list remove at slot counter found socket true else slot counter if found socket m highestnumberoffullyactivatedslots uint32 m standardorder list get size m highestnumberoffullyactivatedslots m standardorder list get size return found socket uploadbandwidththrottler removefromstandardlistnolock throttledfilesocket slotcounter foundsocket slotcounter m_standardorder_list getsize foundsocket m_standardorder_list getat slotcounter m_standardorder_list removeat slotcounter foundsocket slotcounter foundsocket m_highestnumberoffullyactivatedslots m_standardorder_list getsize m_highestnumberoffullyactivatedslots m_standardorder_list getsize foundsocket uint32 upload bandwidth throttler calculate change delta uint32 number of consecutive changes const switch number of consecutive changes case 0 return 50 case 1 return 50 case 2 return 128 case 3 return 256 case 4 return 512 case 5 return 512 256 case 6 return 1 1024 case 7 return 1 1024 256 default return 1 1024 512 uploadbandwidththrottler calculatechangedelta numberofconsecutivechanges numberofconsecutivechanges c shared file list c shared file list c server connect in server server in server output 0 m files map init hash table 1031 m keywords new c publish keyword list m lastpublished2k 0 m lastpublished2kflag true m currfilesrc 0 m currfilenotes 0 m lastpublishkadsrc 0 m lastpublishkadnotes 0 m currfilekey 0 find shared files csharedfilelist csharedfilelist cserverconnect in_server in_server m_files_map inithashtable m_keywords cpublishkeywordlist m_lastpublished2k m_lastpublished2kflag m_currfilesrc m_currfilenotes m_lastpublishkadsrc m_lastpublishkadnotes m_currfilekey findsharedfiles c shared file list c shared file list while waitingforhash list is empty unknownfile struct nextfile waitingforhash list remove head delete nextfile slugfiller safe hash while currentlyhashing list is empty unknownfile struct nextfile currentlyhashing list remove head delete nextfile slugfiller safe hash delete m keywords csharedfilelist csharedfilelist waitingforhash_list isempty unknownfile_struct waitingforhash_list removehead safehash currentlyhashing_list isempty unknownfile_struct currentlyhashing_list removehead safehash m_keywords void c shared file list send list to server if m files map is empty server is connected return c server p cur server server get current server c safe mem file files 1024 cc key buf key c known file cur file cur file2 position pos pos2 c typed ptr list c ptr list c known file sorted list bool added false for pos m files map get start position pos 0 m files map get next assoc pos buf key cur file added false insertsort into sorted list if cur file get publisheded2k cur file is large file p cur server null p cur server supports large filestcp for pos2 sorted list get head position pos2 0 added sorted list get next pos2 if get real prio sorted list get at pos2 get up priority get real prio cur file get up priority sorted list insert before pos2 cur file added true if added sorted list add tail cur file add to packet uint32 limit p cur server p cur server get soft files 0 if limit 0 limit 200 limit 200 if uint32 sorted list get count limit limit sorted list get count if limit 0 m lastpublished2kflag false return files writeu int32 limit uint32 count 0 for pos sorted list get head position pos 0 count limit count c known file file sorted list get next pos create offered file packet file files p cur server file set publisheded2k true sorted list remove all packet packet new packet files packet opcode op offerfiles compress packet this kind of data is highly compressable n 1 md4 and at least 3 string meta data tags and 1 integer meta data tag the min amount of data needed for one published file is 100 bytes this function is called once when connecting to a server and when a file becomes shareable so it s called rarely if the compressed size is still the original size we send the uncompressed packet therefor we always try to compress the packet if p cur server p cur server gettcp flags srv tcpflg compression uint u uncompr size packet size packet pack packet if the prefs get debug servertcp level 0 debug t sending op offerfiles compressed uncompr size u compr size u files u n u uncompr size packet size limit else if the prefs get debug servertcp level 0 debug t sending op offerfiles size u files u n packet size limit the stats add up data overhead server packet size if the prefs get verbose add debug log line false t server sendlist packet size u packet size server send packet packet true csharedfilelist sendlisttoserver m_files_map isempty isconnected cserver pcurserver getcurrentserver csafememfile cckey bufkey cknownfile cur_file cur_file2 ctypedptrlist cptrlist cknownfile sortedlist m_files_map getstartposition m_files_map getnextassoc bufkey cur_file sortedlist cur_file getpublisheded2k cur_file islargefile pcurserver pcurserver supportslargefilestcp sortedlist getheadposition sortedlist getnext getrealprio sortedlist getat getuppriority getrealprio cur_file getuppriority sortedlist insertbefore cur_file sortedlist addtail cur_file pcurserver pcurserver getsoftfiles sortedlist getcount sortedlist getcount m_lastpublished2kflag writeuint32 sortedlist getheadposition cknownfile sortedlist getnext createofferedfilepacket pcurserver setpublisheded2k sortedlist removeall op_offerfiles pcurserver pcurserver gettcpflags srv_tcpflg_compression uuncomprsize packpacket theprefs getdebugservertcplevel _t op__offerfiles uuncomprsize theprefs getdebugservertcplevel _t op__offerfiles thestats addupdataoverheadserver theprefs getverbose adddebuglogline _t sendpacket void c shared file list reload m keywords remove all keyword references find shared files m keywords purge unreferenced keywords if output output reload file list csharedfilelist m_keywords removeallkeywordreferences findsharedfiles m_keywords purgeunreferencedkeywords reloadfilelist bool c shared file list safe addk file c known file toadd bool b only add bool b added false remove from hashing toadd slugfiller safe hash hashed ok remove from list in case it was on the list b added add file toadd if b only add return b added if b added output output add file toadd m lastpublished2kflag true return b added csharedfilelist safeaddkfile cknownfile bonlyadd badded removefromhashing safehash badded addfile bonlyadd badded badded addfile m_lastpublished2kflag badded void c shared file list republish file c known file p file c server p cur server server get current server if p cur server p cur server gettcp flags srv tcpflg compression m lastpublished2kflag true p file set publisheded2k false fixme this creates a wrong no for the ed2k shared info in the listview until the file is shared again csharedfilelist republishfile cknownfile pfile cserver pcurserver getcurrentserver pcurserver pcurserver gettcpflags srv_tcpflg_compression m_lastpublished2kflag pfile setpublisheded2k void c shared file list set output ctrl c shared files ctrl in ctrl output in ctrl output reload file list hash next file slugfiller safe hash if hashing not yet started start it now csharedfilelist setoutputctrl csharedfilesctrl in_ctrl in_ctrl reloadfilelist hashnextfile safehash void c shared file list remove file c known file p file c single lock listlock m mutwritelist listlock lock bool b result m files map remove key cc key p file get file hash listlock unlock if b result true output remove file p file m unsharedfiles map set at cs key p file get file hash true m keywords remove keywords p file csharedfilelist removefile cknownfile pfile csinglelock m_mutwritelist bresult m_files_map removekey cckey pfile getfilehash bresult removefile pfile m_unsharedfiles_map setat cskey pfile getfilehash m_keywords removekeywords pfile c known file c shared file list get file byid const uchar hash const if hash c known file found file cc key key hash if m files map lookup key found file return found file return null cknownfile csharedfilelist getfilebyid cknownfile found_file cckey m_files_map found_file found_file c known file c shared file list get file by index int index int count 0 c known file cur file cc key buf key for position pos m files map get start position pos 0 m files map get next assoc pos buf key cur file if index count return cur file count return 0 cknownfile csharedfilelist getfilebyindex cknownfile cur_file cckey bufkey m_files_map getstartposition m_files_map getnextassoc bufkey cur_file cur_file bool c shared file list is file ptr in list const c known file file const if file position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file if file cur file return true return false csharedfilelist isfileptrinlist cknownfile m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file cur_file c server p server c up down client p client uint u emule ver p client p client is emule client p client get version 0 note this function is used for creating the offered file packet for servers and for clients files write hash16 cur file get file hash this function is used for offering files to the local server and for sending shared files to some other client in each case we send our ip port only if we have a highid newer eservers also support 2 special ip port values which are used to hold basic file status info uint32 n clientid 0 uint16 n client port 0 if p server we use the tcp compression server feature flag as indicator for a newer server if p server gettcp flags srv tcpflg compression if cur file is part file publishing an incomplete file n clientid 0xfcfcfcfc n client port 0xfcfc else publishing a complete file n clientid 0xfbfbfbfb n client port 0xfbfb else check ed2k id state if the app serverconnect is connected the app serverconnect is lowid n clientid the app getid n client port the prefs get port else if the app is connected the app is firewalled n clientid the app getid n client port the prefs get port files writeu int32 n clientid files writeu int16 n client port trace t publishing file hash s clientip s client port u n md4str cur file get file hash ipstr n clientid n client port c simple array c tag tags tags add new c tag ft filename cur file get file name if cur file is large file tags add new c tag ft filesize uint32 uint64 cur file get file size else we send 2 32 bit tags to servers but a real 64 bit tag to other clients if p server null if p server supports large filestcp assert false tags add new c tag ft filesize 0 false else tags add new c tag ft filesize uint32 uint64 cur file get file size tags add new c tag ft filesize hi uint32 uint64 cur file get file size 32 else if p client supports large files assert false tags add new c tag ft filesize 0 false else tags add new c tag ft filesize cur file get file size true eserver 17 6 supports e mule file rating tag there is no tcp capabilities bit available to determine whether the server is really supporting it this is by intention lug that s why we always send it if cur file get file rating tags add new c tag ft filerating cur file get file rating note archives and cd images are published searched with file type pro bool b added file type false if p server p server gettcp flags srv tcpflg typetaginteger send integer file type tags to newer servers eed2k file type e file type geted2k file type searchid geted2k file typeid cur file get file name if e file type ed2kft audio e file type ed2kft cdimage tags add new c tag ft filetype uint e file type b added file type true if b added file type send string file type tags to newer servers in case there is no integer type available for the file type e g emulecollection older servers all clients c string stred2k file type geted2k file type search term geted2k file typeid cur file get file name if stred2k file type is empty tags add new c tag ft filetype stred2k file type b added file type true eserver 16 4 does not need the ft fileformat tag at all nor does any e mule client this tag was used for older very old e donkey servers only we send it only to non e mule clients if p server null u emule ver 0 c string str ext int i ext cur file get file name reverse find t if i ext 1 str ext cur file get file name mid i ext if str ext is empty str ext str ext mid 1 if str ext is empty str ext make lower tags add new c tag ft fileformat str ext file extension without a only send verified meta data to servers clients if cur file get meta data ver 0 static const struct bool b send to server uint8 n name uint8 ned2k type lpcstr pszed2k name ametatags artist album and title are disabled because they should be already part of the filename and would therefore be redundant information sent to the servers and the servers count the amount of sent data false ft media artist tagtype string ft ed2k media artist false ft media album tagtype string ft ed2k media album false ft media title tagtype string ft ed2k media title true ft media length tagtype string ft ed2k media length true ft media bitrate tagtype uint32 ft ed2k media bitrate true ft media codec tagtype string ft ed2k media codec for int i 0 i arrsize ametatags i if p server null ametatags i b send to server continue c tag p tag cur file get tag ametatags i n name if p tag null skip string tags with empty string values if p tag is str p tag get str is empty continue skip integer tags with 0 values if p tag is int p tag get int 0 continue if ametatags i ned2k type tagtype string p tag is str if p server p server gettcp flags srv tcpflg newtags tags add new c tag ametatags i n name p tag get str else tags add new c tag ametatags i pszed2k name p tag get str else if ametatags i ned2k type tagtype uint32 p tag is int if p server p server gettcp flags srv tcpflg newtags tags add new c tag ametatags i n name p tag get int else tags add new c tag ametatags i pszed2k name p tag get int else if ametatags i n name ft media length p tag is int assert ametatags i ned2k type tagtype string all eserver versions and e mule versions 0 42 4 support the media length tag with type integer if p server null p server gettcp flags srv tcpflg compression u emule ver make client version 0 42 4 if p server p server gettcp flags srv tcpflg newtags tags add new c tag ametatags i n name p tag get int else tags add new c tag ametatags i pszed2k name p tag get int else c string str value sec to time length p tag get int str value tags add new c tag ametatags i pszed2k name str value else assert 0 e utf8 str e str encode if p server null p server gettcp flags srv tcpflg unicode eserver doesn t properly support searching with ascii 7 strings in bom utf8 published strings e str encode utf8str optbom e str encode utf8str raw else if p client p client get unicode support e str encode utf8str none else e str encode utf8str raw files writeu int32 tags get size for int i 0 i tags get size i const c tag p tag tags i trace t s n p tag get full info dbg get file meta tag name if p server p server gettcp flags srv tcpflg newtags u emule ver make client version 0 42 7 p tag write new ed2k tag files e str encode else p tag write tag to file files e str encode delete p tag cserver pserver cupdownclient pclient uemulever pclient pclient isemuleclient pclient getversion _and_ writehash16 cur_file getfilehash nclientid nclientport pserver pserver gettcpflags srv_tcpflg_compression cur_file ispartfile nclientid nclientport nclientid nclientport theapp isconnected theapp islowid nclientid theapp nclientport theprefs getport theapp isconnected theapp isfirewalled nclientid theapp nclientport theprefs getport writeuint32 nclientid writeuint16 nclientport _t clientport cur_file getfilehash nclientid nclientport csimplearray ctag ctag ft_filename cur_file getfilename cur_file islargefile ctag ft_filesize cur_file getfilesize pserver pserver supportslargefilestcp ctag ft_filesize ctag ft_filesize cur_file getfilesize ctag ft_filesize_hi cur_file getfilesize pclient supportslargefiles ctag ft_filesize ctag ft_filesize cur_file getfilesize emule cur_file getfilerating ctag ft_filerating cur_file getfilerating baddedfiletype pserver pserver gettcpflags srv_tcpflg_typetaginteger eed2kfiletype efiletype geted2kfiletypesearchid geted2kfiletypeid cur_file getfilename efiletype ed2kft_audio efiletype ed2kft_cdimage ctag ft_filetype efiletype baddedfiletype baddedfiletype cstring stred2kfiletype geted2kfiletypesearchterm geted2kfiletypeid cur_file getfilename stred2kfiletype isempty ctag ft_filetype stred2kfiletype baddedfiletype ft_fileformat emule edonkey emule pserver uemulever cstring strext iext cur_file getfilename reversefind _t iext strext cur_file getfilename iext strext isempty strext strext strext isempty strext makelower ctag ft_fileformat strext cur_file getmetadataver bsendtoserver nname ned2ktype pszed2kname _ametatags ft_media_artist tagtype_string ft_ed2k_media_artist ft_media_album tagtype_string ft_ed2k_media_album ft_media_title tagtype_string ft_ed2k_media_title ft_media_length tagtype_string ft_ed2k_media_length ft_media_bitrate tagtype_uint32 ft_ed2k_media_bitrate ft_media_codec tagtype_string ft_ed2k_media_codec _ametatags pserver _ametatags bsendtoserver ctag ptag cur_file gettag _ametatags nname ptag ptag isstr ptag getstr isempty ptag isint ptag getint _ametatags ned2ktype tagtype_string ptag isstr pserver pserver gettcpflags srv_tcpflg_newtags ctag _ametatags nname ptag getstr ctag _ametatags pszed2kname ptag getstr _ametatags ned2ktype tagtype_uint32 ptag isint pserver pserver gettcpflags srv_tcpflg_newtags ctag _ametatags nname ptag getint ctag _ametatags pszed2kname ptag getint _ametatags nname ft_media_length ptag isint _ametatags ned2ktype tagtype_string emule pserver pserver gettcpflags srv_tcpflg_compression uemulever make_client_version pserver pserver gettcpflags srv_tcpflg_newtags ctag _ametatags nname ptag getint ctag _ametatags pszed2kname ptag getint cstring strvalue sectotimelength ptag getint strvalue ctag _ametatags pszed2kname strvalue eutf8str estrencode pserver pserver gettcpflags srv_tcpflg_unicode estrencode utf8stroptbom estrencode utf8strraw pclient pclient getunicodesupport estrencode utf8strnone estrencode utf8strraw writeuint32 getsize getsize ctag ptag _t ptag getfullinfo dbggetfilemetatagname pserver pserver gettcpflags srv_tcpflg_newtags uemulever make_client_version ptag writenewed2ktag estrencode ptag writetagtofile estrencode ptag uint64 c shared file list get datasize uint64 pbytes largest const pbytes largest 0 khaos uint64 fsize fsize 0 cc key buf key c known file cur file for position pos m files map get start position pos 0 m files map get next assoc pos buf key cur file fsize uint64 cur file get file size khaos if this file is bigger than all the others well duh if cur file get file size pbytes largest pbytes largest cur file get file size khaos return fsize csharedfilelist getdatasize pbyteslargest pbyteslargest cckey bufkey cknownfile cur_file m_files_map getstartposition m_files_map getnextassoc bufkey cur_file cur_file getfilesize cur_file getfilesize pbyteslargest pbyteslargest cur_file getfilesize void c shared file list update file c known file toupdate output update file toupdate csharedfilelist updatefile cknownfile updatefile void c shared file list add files from directory const c string rstr directory c file find ff c string searchpath searchpath format t s rstr directory bool end ff find file searchpath 0 if end return while end end ff find next file if ff is directory ff is dots ff is system ff is temporary ff get length 0 ff get length max emule file size continue ignore real lnk files tchar sz ext max ext tsplitpath ff get file name null null null sz ext if tcsicmp sz ext t lnk 0 shfileinfo info if sh get file info ff get file path 0 info sizeof info shgfi attributes info dw attributes sfgao link c com ptr i shell link p shell link if succeeded p shell link co create instance clsid shelllink c comqi ptr i persist file p persist file p shell link if p persist file uses conversion if succeeded p persist file load t2cole ff get file path stgm read tchar sz resolved path max path if p shell link get path sz resolved path arrsize sz resolved path null 0 noerror trace t hs did not share file s not supported file type n function ff get file path continue ignore real thumbs db files seems that lot of ppl have thumbs db files without the system file attribute if ff get file name compare no case t thumbs db 0 if that s a valid storage file we declare it as a thumbs db file uses conversion c com ptr i storage p storage if stg open storage t2cw ff get file path null stgm read stgm share deny write null 0 p storage s ok c com ptr i enumstatstg p enumstatstg if succeeded p storage enum elements 0 null 0 p enumstatstg statstg statstg 0 if p enumstatstg next 1 statstg 0 s ok co task mem free statstg pwcs name statstg pwcs name null trace t hs did not share file s not supported file type n function ff get file path continue c time lwtime try ff get last write time lwtime catch c exception ex ex delete uint32 fdate uint lwtime get time if fdate 0 fdate uint 1 if fdate 1 if the prefs get verbose add debug log line false t failed to get file date of s ff get file path else adjustntfs daylight file time fdate ff get file path c known file toadd the app knownfiles find known file ff get file name fdate ff get length if toadd cc key key toadd get file hash c known file p file in map if m files map lookup key p file in map trace t hs file already in shared file list s s n function md4str p file in map get file hash p file in map get file path trace t hs file to add s s n function md4str toadd get file hash ff get file path if p file in map is kind of runtime class c part file the app downloadqueue is part file p file in map log warning get res string ids err dupl files p file in map get file path ff get file path else toadd set path rstr directory toadd set file path ff get file path add file toadd else not in knownfilelist start adding thread to hash file if the hashing of this file isnt already waiting slugfiller safe hash don t double hash my way if is hashing rstr directory ff get file name the prefs is temp file rstr directory ff get file name unknownfile struct tohash new unknownfile struct tohash str directory rstr directory tohash str name ff get file name waitingforhash list add tail tohash else trace t hs did not share file s already hashing or temp file n function ff get file path slugfiller safe hash ff close csharedfilelist addfilesfromdirectory cstring rstrdirectory cfilefind cstring _t rstrdirectory findfile findnextfile isdirectory isdots issystem istemporary getlength getlength max_emule_file_size szext _max_ext _tsplitpath getfilename szext _tcsicmp szext _t shgetfileinfo getfilepath shgfi_attributes dwattributes sfgao_link ccomptr ishelllink pshelllink pshelllink cocreateinstance clsid_shelllink ccomqiptr ipersistfile ppersistfile pshelllink ppersistfile uses_conversion ppersistfile getfilepath stgm_read szresolvedpath max_path pshelllink getpath szresolvedpath szresolvedpath _t __function__ getfilepath getfilename comparenocase _t uses_conversion ccomptr istorage pstorage stgopenstorage getfilepath stgm_read stgm_share_deny_write pstorage s_ok ccomptr ienumstatstg penumstatstg pstorage enumelements penumstatstg penumstatstg s_ok cotaskmemfree pwcsname pwcsname _t __function__ getfilepath ctime getlastwritetime cexception gettime theprefs getverbose adddebuglogline _t getfilepath adjustntfsdaylightfiletime getfilepath cknownfile theapp findknownfile getfilename getlength cckey getfilehash cknownfile pfileinmap m_files_map pfileinmap _t __function__ pfileinmap getfilehash pfileinmap getfilepath _t __function__ getfilehash getfilepath pfileinmap iskindof runtime_class cpartfile theapp ispartfile pfileinmap logwarning getresstring ids_err_dupl_files pfileinmap getfilepath getfilepath setpath rstrdirectory setfilepath getfilepath addfile safehash ishashing rstrdirectory getfilename theprefs istempfile rstrdirectory getfilename unknownfile_struct unknownfile_struct strdirectory rstrdirectory strname getfilename waitingforhash_list addtail _t __function__ getfilepath safehash void c shared file list add file from newly created collection const c string path const c string file name johntodo i do not have much knowledge on the hashing process is this safe for me to do if is hashing path file name unknownfile struct tohash new unknownfile struct tohash str directory path tohash str name file name waitingforhash list add tail tohash hash next file csharedfilelist addfilefromnewlycreatedcollection cstring cstring filename ishashing filename unknownfile_struct unknownfile_struct strdirectory strname filename waitingforhash_list addtail hashnextfile void c shared file list hash failed unknownfile struct hashed for position pos currentlyhashing list get head position pos 0 position pos last pos const unknownfile struct p file currentlyhashing list get next pos if p file str name compare no case hashed str name compare directories p file str directory hashed str directory currentlyhashing list remove at pos last delete p file hash next file start next hash if possible but only if a previous hash finished break delete hashed csharedfilelist hashfailed unknownfile_struct currentlyhashing_list getheadposition poslast unknownfile_struct pfile currentlyhashing_list getnext pfile strname comparenocase strname comparedirectories pfile strdirectory strdirectory currentlyhashing_list removeat poslast pfile hashnextfile void c shared file list file hashing finished c known file file file hashing finished for a shared file none partfile reading shared directories at startup and hashing files which were not found in known met reading shared directories during runtime user hit reload button added a shared directory assert is file ptr in list file assert the app knownfiles is file ptr in list file c known file found file get file byid file get file hash if found file null safe addk file file the app knownfiles safe addk file file else trace t hs file already in shared file list s s n function md4str found file get file hash found file get file path trace t hs file to add s s n function md4str file get file hash file get file path log warning get res string ids err dupl files found file get file path file get file path remove from hashing file if is file ptr in list file the app knownfiles is file ptr in list file delete file else assert 0 csharedfilelist filehashingfinished cknownfile isfileptrinlist theapp isfileptrinlist cknownfile found_file getfilebyid getfilehash found_file safeaddkfile theapp safeaddkfile _t __function__ found_file getfilehash found_file getfilepath _t __function__ getfilehash getfilepath logwarning getresstring ids_err_dupl_files found_file getfilepath getfilepath removefromhashing isfileptrinlist theapp isfileptrinlist void c shared file list cleared2k publish info c known file cur file cc key buf key m lastpublished2kflag true for position pos m files map get start position pos 0 m files map get next assoc pos buf key cur file cur file set publisheded2k false csharedfilelist cleared2kpublishinfo cknownfile cur_file cckey bufkey m_lastpublished2kflag m_files_map getstartposition m_files_map getnextassoc bufkey cur_file cur_file setpublisheded2k void c shared file list clear kad source publish info c known file cur file cc key buf key for position pos m files map get start position pos 0 m files map get next assoc pos buf key cur file cur file set last publish time kad src 0 0 csharedfilelist clearkadsourcepublishinfo cknownfile cur_file cckey bufkey m_files_map getstartposition m_files_map getnextassoc bufkey cur_file cur_file setlastpublishtimekadsrc void c shared file list process publish if m lastpublished2kflag get tick count m lastpublished2k ed2krepublishtime return send list to server m lastpublished2k get tick count csharedfilelist m_lastpublished2kflag gettickcount m_lastpublished2k sendlisttoserver m_lastpublished2k gettickcount void c shared file list publish variables to save cpu uint t now time null bool is firewalled the app is firewalled if kademlia c kademlia is connected is firewalled is firewalled the app clientlist get buddy status connected get count kademlia c kademlia get publish we are connected to kad we are either open or have a buddy and kad is ready to start publishing if kademlia c kademlia get total store key kademliatotalstorekey we are not at the max simultaneous keyword publishes if t now m keywords get next publish time enough time has passed since last keyword publish get the next keyword which has to be re published c publish keyword p pub kw m keywords get next keyword if p pub kw we have the next keyword to check if it can be published debug check to make sure things are going well assert p pub kw get ref count 0 if t now p pub kw get next publish time this keyword can be published kademlia c search p search kademlia c search manager prepare lookup kademlia c search storekeyword false p pub kw get kadid if p search p search was created which means no search was already being done with this hashid this also means that it was checked to see if network load wasn t a factor this sets the filename into the search object so we can show it in the gui p search set file name p pub kw get keyword add all file i ds which relate to the current keyword to be published const c simple known file array a files p pub kw get references uint32 count 0 for int f 0 f a files get size f debug check to make sure things are working well assert valid a files f johntodo why is this happening i think it may have to do with downloading a file that is already in the known file list assert is file ptr in list a files f only publish complete files as someone else should have the full file to publish these keywords as a side effect this may help reduce people finding incomplete files in the network if a files f is part file is file ptr in list a files f count p search add fileid kademlia cu int128 a files f get file hash if count 150 we only publish up to 150 files per keyword publish then rotate the list p pub kw rotate references f break if count start our keyword publish p search prepare packet p pub kw set next publish time t now kademliarepublishtimek p pub kw inc published count kademlia c search manager start search p search else there were no valid files to publish with this keyword delete p search m keywords set next publish time kademliapublishtime t now if kademlia c kademlia get total store src kademliatotalstoresrc if t now m lastpublishkadsrc if m currfilesrc get count m currfilesrc 0 c known file p cur known file get file by index m currfilesrc if p cur known file if p cur known file publish src if kademlia c search manager prepare lookup kademlia c search storefile true kademlia cu int128 p cur known file get file hash null p cur known file set last publish time kad src 0 0 m currfilesrc even if we did not publish a source reset the timer so that this list is processed only every kademliapublishtime seconds m lastpublishkadsrc kademliapublishtime t now if kademlia c kademlia get total store notes kademliatotalstorenotes if t now m lastpublishkadnotes if m currfilenotes get count m currfilenotes 0 c known file p cur known file get file by index m currfilenotes if p cur known file if p cur known file publish notes if kademlia c search manager prepare lookup kademlia c search storenotes true kademlia cu int128 p cur known file get file hash null p cur known file set last publish time kad notes 0 m currfilenotes even if we did not publish a source reset the timer so that this list is processed only every kademliapublishtime seconds m lastpublishkadnotes kademliapublishtime t now csharedfilelist tnow isfirewalled theapp isfirewalled ckademlia isconnected isfirewalled isfirewalled theapp getbuddystatus getcount ckademlia getpublish ckademlia gettotalstorekey tnow m_keywords getnextpublishtime cpublishkeyword ppubkw m_keywords getnextkeyword ppubkw ppubkw getrefcount tnow ppubkw getnextpublishtime csearch psearch csearchmanager preparelookup csearch ppubkw getkadid psearch psearch psearch setfilename ppubkw getkeyword ids csimpleknownfilearray afiles ppubkw getreferences afiles getsize assert_valid afiles isfileptrinlist afiles afiles ispartfile isfileptrinlist afiles psearch addfileid cuint128 afiles getfilehash ppubkw rotatereferences psearch preparepacket ppubkw setnextpublishtime tnow ppubkw incpublishedcount csearchmanager startsearch psearch psearch m_keywords setnextpublishtime tnow ckademlia gettotalstoresrc tnow m_lastpublishkadsrc m_currfilesrc getcount m_currfilesrc cknownfile pcurknownfile getfilebyindex m_currfilesrc pcurknownfile pcurknownfile publishsrc csearchmanager preparelookup csearch cuint128 pcurknownfile getfilehash pcurknownfile setlastpublishtimekadsrc m_currfilesrc m_lastpublishkadsrc tnow ckademlia gettotalstorenotes tnow m_lastpublishkadnotes m_currfilenotes getcount m_currfilenotes cknownfile pcurknownfile getfilebyindex m_currfilenotes pcurknownfile pcurknownfile publishnotes csearchmanager preparelookup csearch cuint128 pcurknownfile getfilehash pcurknownfile setlastpublishtimekadnotes m_currfilenotes m_lastpublishkadnotes tnow void c shared file list add keywords c known file p file m keywords add keywords p file csharedfilelist addkeywords cknownfile pfile m_keywords addkeywords pfile void c shared file list remove keywords c known file p file m keywords remove keywords p file csharedfilelist removekeywords cknownfile pfile m_keywords removekeywords pfile void c shared file list delete part file instances const this is only allowed during shut down assert the app m app state app state shutingdown assert the app knownfiles position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file if cur file is kind of runtime class c part file if the app downloadqueue is part file cur file the app knownfiles is file ptr in list cur file delete cur file this is only allowed during shut down csharedfilelist deletepartfileinstances theapp m_app_state app_state_shutingdown theapp m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file cur_file iskindof runtime_class cpartfile theapp ispartfile cur_file theapp isfileptrinlist cur_file cur_file bool c shared file list is unshared file const uchar au file hash const bool b found if au file hash cs key key au file hash if m unsharedfiles map lookup key b found return true return false csharedfilelist isunsharedfile aufilehash bfound aufilehash cskey aufilehash m_unsharedfiles_map bfound void c shared file list copy shared file map c map cc key const cc key c known file c known file files map if m files map is empty position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file files map set at key cur file csharedfilelist copysharedfilemap cmap cckey cckey cknownfile cknownfile files_map m_files_map isempty m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file files_map setat cur_file bool c shared file list add file c known file p file assert p file get hash count p file geted2k part hash count assert p file is kind of runtime class c part file static downcast c part file p file hashsetneeded cc key key p file get file hash c known file p file in map if m files map lookup key p file in map trace t hs file already in shared file list s s s n function md4str p file in map get file hash p file in map get file name p file in map get file path trace t hs file to add s s s n function md4str p file get file hash p file get file name p file get file path if p file in map is kind of runtime class c part file the app downloadqueue is part file p file in map log warning get res string ids err dupl files p file in map get file path p file get file path return false m unsharedfiles map remove key cs key p file get file hash c single lock listlock m mutwritelist listlock lock m files map set at key p file listlock unlock bool b keywords need updated true if p file is part file p file m pcollection c collection has collection extention p file get file name p file m pcollection new c collection if p file m pcollection init collection from file p file get file path p file get file name delete p file m pcollection p file m pcollection null else if p file m pcollection get collection author key string is empty if the collection has a key resetting the file name will cause the key to be added into the wordlist to be stored into kad p file set file name p file get file name during the initial startup sharedfiles is not accessable to set file name which will then not call add keywords but when it is accessable we don t allow it to readd them if the app sharedfiles b keywords need updated false if b keywords need updated m keywords add keywords p file return true csharedfilelist addfile cknownfile pfile pfile gethashcount pfile geted2kparthashcount pfile iskindof runtime_class cpartfile static_downcast cpartfile pfile cckey pfile getfilehash cknownfile pfileinmap m_files_map pfileinmap _t __function__ pfileinmap getfilehash pfileinmap getfilename pfileinmap getfilepath _t __function__ pfile getfilehash pfile getfilename pfile getfilepath pfileinmap iskindof runtime_class cpartfile theapp ispartfile pfileinmap logwarning getresstring ids_err_dupl_files pfileinmap getfilepath pfile getfilepath m_unsharedfiles_map removekey cskey pfile getfilehash csinglelock m_mutwritelist m_files_map setat pfile bkeywordsneedupdated pfile ispartfile pfile m_pcollection ccollection hascollectionextention pfile getfilename pfile m_pcollection ccollection pfile m_pcollection initcollectionfromfile pfile getfilepath pfile getfilename pfile m_pcollection pfile m_pcollection pfile m_pcollection getcollectionauthorkeystring isempty pfile setfilename pfile getfilename setfilename addkeywords theapp bkeywordsneedupdated bkeywordsneedupdated m_keywords addkeywords pfile void c shared file list find shared files if m files map is empty c single lock listlock m mutwritelist position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file if cur file is kind of runtime class c part file the app downloadqueue is part file cur file the app knownfiles is file ptr in list cur file taccess cur file get file path 0 0 continue m unsharedfiles map set at cs key cur file get file hash true listlock lock m files map remove key key listlock unlock assert the app downloadqueue if the app downloadqueue the app downloadqueue add part files to share read partfiles khaos kmod fix shared files loaded multiple times c string list l sadded c string temp dir c string ltemp dir temp dir the prefs get incoming dir if temp dir right 1 t temp dir t add files from directory temp dir temp dir make lower l sadded add head temp dir for int ix 1 ix the prefs get cat count ix temp dir c string the prefs get cat path ix if temp dir right 1 t temp dir t ltemp dir temp dir ltemp dir make lower if l sadded find ltemp dir null l sadded add head ltemp dir add files from directory temp dir for position pos the prefs shareddir list get head position pos 0 temp dir the prefs shareddir list get next pos if temp dir right 1 t temp dir t ltemp dir temp dir ltemp dir make lower if l sadded find ltemp dir null l sadded add head ltemp dir add files from directory temp dir khaos kmod if waitingforhash list is empty add log line false get res string ids sharedfound m files map get count else add log line false get res string ids sharedfoundhashing m files map get count waitingforhash list get count hash next file csharedfilelist findsharedfiles m_files_map isempty csinglelock m_mutwritelist m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file cur_file iskindof runtime_class cpartfile theapp ispartfile cur_file theapp isfileptrinlist cur_file _taccess cur_file getfilepath m_unsharedfiles_map setat cskey cur_file getfilehash m_files_map removekey theapp theapp theapp addpartfilestoshare cstringlist l_sadded cstring tempdir cstring ltempdir tempdir theprefs getincomingdir tempdir _t tempdir _t addfilesfromdirectory tempdir tempdir makelower l_sadded addhead tempdir theprefs getcatcount tempdir cstring theprefs getcatpath tempdir _t tempdir _t ltempdir tempdir ltempdir makelower l_sadded ltempdir l_sadded addhead ltempdir addfilesfromdirectory tempdir theprefs shareddir_list getheadposition tempdir theprefs shareddir_list getnext tempdir _t tempdir _t ltempdir tempdir ltempdir makelower l_sadded ltempdir l_sadded addhead ltempdir addfilesfromdirectory tempdir waitingforhash_list isempty addlogline getresstring ids_sharedfound m_files_map getcount addlogline getresstring ids_sharedfoundhashing m_files_map getcount waitingforhash_list getcount hashnextfile void c shared file list hash next file slugfiller safe hash if the app emuledlg is window the app emuledlg m hwnd wait for the dialog to open return if the app emuledlg the app emuledlg is running the app emuledlg sharedfileswnd sharedfilesctrl show files count if currentlyhashing list is empty one hash at a time return slugfiller safe hash if waitingforhash list is empty return unknownfile struct nextfile waitingforhash list remove head currentlyhashing list add tail nextfile slugfiller safe hash keep track c add file thread addfilethread c add file thread afx begin thread runtime class c add file thread thread priority below normal 0 create suspended addfilethread set values this nextfile str directory nextfile str name addfilethread resume thread slugfiller safe hash nextfile deleting handled elsewhere delete nextfile csharedfilelist hashnextfile safehash theapp iswindow theapp m_hwnd theapp theapp isrunning theapp showfilescount currentlyhashing_list isempty safehash waitingforhash_list isempty unknownfile_struct waitingforhash_list removehead currentlyhashing_list addtail safehash caddfilethread caddfilethread afxbeginthread runtime_class caddfilethread thread_priority_below_normal create_suspended setvalues strdirectory strname resumethread safehash slugfiller safe hash bool c shared file list is hashing const c string rstr directory const c string rstr name for position pos waitingforhash list get head position pos 0 const unknownfile struct p file waitingforhash list get next pos if p file str name compare no case rstr name compare directories p file str directory rstr directory return true for position pos currentlyhashing list get head position pos 0 const unknownfile struct p file currentlyhashing list get next pos if p file str name compare no case rstr name compare directories p file str directory rstr directory return true return false safehash csharedfilelist ishashing cstring rstrdirectory cstring rstrname waitingforhash_list getheadposition unknownfile_struct pfile waitingforhash_list getnext pfile strname comparenocase rstrname comparedirectories pfile strdirectory rstrdirectory currentlyhashing_list getheadposition unknownfile_struct pfile currentlyhashing_list getnext pfile strname comparenocase rstrname comparedirectories pfile strdirectory rstrdirectory void c shared file list remove from hashing c known file hashed for position pos currentlyhashing list get head position pos 0 position pos last pos const unknownfile struct p file currentlyhashing list get next pos if p file str name compare no case hashed get file name compare directories p file str directory hashed get path currentlyhashing list remove at pos last delete p file hash next file start next hash if possible but only if a previous hash finished return csharedfilelist removefromhashing cknownfile currentlyhashing_list getheadposition poslast unknownfile_struct pfile currentlyhashing_list getnext pfile strname comparenocase getfilename comparedirectories pfile strdirectory getpath currentlyhashing_list removeat poslast pfile hashnextfile c client credits list c client credits list m nlastsaved get tick count load list initalize crypting cclientcreditslist cclientcreditslist m_nlastsaved gettickcount loadlist initalizecrypting c client credits list c client credits list save list c client credits cur credit cc key tmpkey 0 position pos m mapclients get start position while pos m mapclients get next assoc pos tmpkey cur credit delete cur credit delete m psignkey cclientcreditslist cclientcreditslist savelist cclientcredits cur_credit cckey m_mapclients getstartposition m_mapclients getnextassoc cur_credit cur_credit m_psignkey uint32 dw forip uint8 by chaip kind assert p target assert pach signature if crypto available p target ident state is notavailable return false bool b result try string source ss pubkey byte p target get secure ident p target get secid key len true 0 rsassa pkcs1v15 sha verifier pubkey ss pubkey 4 additional bytes random data send from this client 5 bytes v2 byte aby buffer maxpubkeysize 9 memcpy aby buffer m abymypublickey m nmypublickeylen uint32 challenge p target m dwcryptrndchallengefor assert challenge 0 pokeu int32 aby buffer m nmypublickeylen challenge v2 security improvments not supported by 29b not used as default by 29c uint8 n ch ip size 0 if by chaip kind 0 n ch ip size 5 uint32 challengeip 0 switch by chaip kind case crypt cip localclient challengeip dw forip break case crypt cip remoteclient if the app serverconnect get clientid 0 the app serverconnect is lowid if the prefs get log secure ident add debug log line false t warning maybe secure hash ident fails because localip is unknown challengeip the app serverconnect get localip else challengeip the app serverconnect get clientid break case crypt cip noneclient maybe not supported in future versions challengeip 0 break pokeu int32 aby buffer m nmypublickeylen 4 challengeip pokeu int8 aby buffer m nmypublickeylen 4 4 by chaip kind v2 end b result pubkey verify message aby buffer m nmypublickeylen 4 n ch ip size pach signature n input size catch if the prefs get verbose add debug log line false t error unknown exception in hs function assert 0 b result false if b result if p target ident state is idneeded p target ident state is idfailed else p target verified dw forip return b result dwforip bychaipkind ptarget pachsignature cryptoavailable ptarget identstate is_notavailable bresult stringsource ss_pubkey ptarget getsecureident ptarget getsecidkeylen rsassa_pkcs1v15_sha_verifier ss_pubkey abybuffer abybuffer m_abymypublickey m_nmypublickeylen ptarget m_dwcryptrndchallengefor pokeuint32 abybuffer m_nmypublickeylen nchipsize bychaipkind nchipsize bychaipkind crypt_cip_localclient dwforip crypt_cip_remoteclient theapp getclientid theapp islowid theprefs getlogsecureident adddebuglogline _t securehash theapp getlocalip theapp getclientid crypt_cip_noneclient pokeuint32 abybuffer m_nmypublickeylen pokeuint8 abybuffer m_nmypublickeylen bychaipkind bresult verifymessage abybuffer m_nmypublickeylen nchipsize pachsignature ninputsize theprefs getverbose adddebuglogline _t __function__ bresult bresult ptarget identstate is_idneeded ptarget identstate is_idfailed ptarget dwforip bresult c client credits c client credits list get credit const uchar key c client credits result cc key tkey key if m mapclients lookup tkey result result new c client credits key m mapclients set at cc key result get key result result set last seen return result cclientcredits cclientcreditslist getcredit cclientcredits cckey m_mapclients cclientcredits m_mapclients setat cckey getkey setlastseen void c client credits list process if get tick count m nlastsaved min2ms 13 save list cclientcreditslist gettickcount m_nlastsaved savelist bool c client credits list crypto available return m nmypublickeylen 0 m psignkey 0 the prefs is secure ident enabled cclientcreditslist cryptoavailable m_nmypublickeylen m_psignkey theprefs issecureidentenabled void c client credits list load list c string str file name the prefs get config dir clients met filename const int i open flags c file mode read c file os sequential scan c file type binary c file share deny write c safe buffered file file c file exception fexp if file open str file name i open flags fexp if fexp m cause c file exception file not found c string str error get res string ids err loadcreditfile tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return setvbuf file m pstream null iofbf 16384 try uint8 version file readu int8 if version creditfile version version creditfile version 29 log warning get res string ids err creditfileold file close return everything is ok lets see if the backup exist c string str bak file name str bak file name format t s clients met filename t bak the prefs get config dir dword dw bak file size 0 bool b create backup true handle h bak file create file str bak file name generic read file share read null open existing file attribute normal null if h bak file invalid handle value ok the backup exist get the size dw bak file size get file size h bak file null debug if dw bak file size dword file get length the size of the backup was larger then the org file something is wrong here don t overwrite old backup b create backup false else backup is smaller or the same size as org file proceed with copying of file close handle h bak file else the backup doesn t exist create it if b create backup file close close the file before copying if copy file str file name str bak file name false log error get res string ids err makebakcreditfile reopen file c file exception fexp if file open str file name i open flags fexp c string str error get res string ids err loadcreditfile tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return setvbuf file m pstream null iofbf 16384 file seek 1 c file begin set filepointer behind file version byte uint count file readu int32 m mapclients init hash table count 5000 todo should be prime number and 20 larger const uint32 dw expired time null 12960000 today 150 day uint32 c deleted 0 for uint i 0 i count i credit struct newcstruct new credit struct memset newcstruct 0 sizeof credit struct if version creditfile version 29 file read newcstruct sizeof creditstruct 29a else file read newcstruct sizeof credit struct if newcstruct n last seen dw expired c deleted delete newcstruct continue c client credits newcredits new c client credits newcstruct m mapclients set at cc key newcredits get key newcredits file close if c deleted 0 add log line false get res string ids creditfileloaded get res string ids creditsexpired count c deleted c deleted else add log line false get res string ids creditfileloaded count catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids creditfilecorrupt else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err creditfileread buffer error delete cclientcreditslist loadlist cstring strfilename theprefs getconfigdir clients_met_filename iopenflags cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite csafebufferedfile cfileexception strfilename iopenflags m_cause cfileexception filenotfound cstring strerror getresstring ids_err_loadcreditfile szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf readuint8 creditfile_version creditfile_version_29 logwarning getresstring ids_err_creditfileold cstring strbakfilename strbakfilename _t clients_met_filename _t theprefs getconfigdir dwbakfilesize bcreatebackup hbakfile createfile strbakfilename generic_read file_share_read open_existing file_attribute_normal hbakfile invalid_handle_value dwbakfilesize getfilesize hbakfile dwbakfilesize getlength bcreatebackup closehandle hbakfile bcreatebackup copyfile strfilename strbakfilename logerror getresstring ids_err_makebakcreditfile cfileexception strfilename iopenflags cstring strerror getresstring ids_err_loadcreditfile szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf cfile readuint32 m_mapclients inithashtable dwexpired cdeleted creditstruct creditstruct creditstruct creditfile_version_29 creditstruct_29a creditstruct nlastseen dwexpired cdeleted cclientcredits cclientcredits m_mapclients setat cckey getkey cdeleted addlogline getresstring ids_creditfileloaded getresstring ids_creditsexpired cdeleted cdeleted addlogline getresstring ids_creditfileloaded cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_creditfilecorrupt max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_creditfileread void c client credits list save list if the prefs get log file saving add debug log line false t saving clients credit list file s clients met filename m nlastsaved get tick count c string name the prefs get config dir clients met filename c file file no buffering needed here since we swap out the entire array c file exception fexp if file open name c file mode write c file mode create c file type binary c file share deny write fexp c string str error get res string ids err failed creditsave tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return uint32 count m mapclients get count byte p buffer new byte count sizeof credit struct c client credits cur credit cc key tempkey 0 position pos m mapclients get start position count 0 while pos m mapclients get next assoc pos tempkey cur credit if cur credit get uploaded total cur credit get downloaded total memcpy p buffer count sizeof credit struct cur credit get data struct sizeof credit struct count try uint8 version creditfile version file write version 1 file write count 4 file write p buffer count sizeof credit struct if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush file close catch c file exception error c string str error get res string ids err failed creditsave tchar sz error max cfexp errormsg if error get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error error delete delete p buffer cclientcreditslist savelist theprefs getlogfilesaving adddebuglogline _t clients_met_filename m_nlastsaved gettickcount cstring theprefs getconfigdir clients_met_filename cfile cfileexception cfile modewrite cfile modecreate cfile typebinary cfile sharedenywrite cstring strerror getresstring ids_err_failed_creditsave szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_mapclients getcount pbuffer creditstruct cclientcredits cur_credit cckey m_mapclients getstartposition m_mapclients getnextassoc cur_credit cur_credit getuploadedtotal cur_credit getdownloadedtotal pbuffer creditstruct cur_credit getdatastruct creditstruct creditfile_version pbuffer creditstruct theprefs getcommitfiles theprefs getcommitfiles theapp isrunning cfileexception cstring strerror getresstring ids_err_failed_creditsave szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror pbuffer void c client credits list initalize crypting m nmypublickeylen 0 memset m abymypublickey 0 80 not really needed better for debugging tho m psignkey null if the prefs is secure ident enabled return check if keyfile is there bool b create new key false handle h key file create file the prefs get config dir t cryptkey dat generic read file share read null open existing file attribute normal null if h key file invalid handle value if get file size h key file null 0 b create new key true close handle h key file else b create new key true if b create new key create key pair load key try load private key file source filesource c stringa the prefs get config dir t cryptkey dat true new base64 decoder m psignkey new rsassa pkcs1v15 sha signer filesource calculate and store public key rsassa pkcs1v15 sha verifier pubkey m psignkey array sink asink m abymypublickey 80 pubkey der encode asink m nmypublickeylen uint8 asink total put length asink message end catch delete m psignkey m psignkey null log error log statusbar get res string ids crypt initfailed assert 0 debug checkcrypting cclientcreditslist initalizecrypting m_nmypublickeylen m_abymypublickey m_psignkey theprefs issecureidentenabled bcreatenewkey hkeyfile createfile theprefs getconfigdir _t generic_read file_share_read open_existing file_attribute_normal hkeyfile invalid_handle_value getfilesize hkeyfile bcreatenewkey closehandle hkeyfile bcreatenewkey bcreatenewkey createkeypair filesource cstringa theprefs getconfigdir _t base64decoder m_psignkey rsassa_pkcs1v15_sha_signer rsassa_pkcs1v15_sha_verifier m_psignkey arraysink m_abymypublickey derencode m_nmypublickeylen totalputlength messageend m_psignkey m_psignkey logerror log_statusbar getresstring ids_crypt_initfailed debug_checkcrypting bool c client credits list create key pair try auto seeded random pool rng invertiblersa function privkey privkey initialize rng rsakeysize base64 encoder privkeysink new file sink c stringa the prefs get config dir t cryptkey dat privkey der encode privkeysink privkeysink message end if the prefs get log secure ident add debug log line false t created new rsa keypair catch if the prefs get verbose add debug log line false t failed to create new rsa keypair assert false return false return true cclientcreditslist createkeypair autoseededrandompool invertiblersafunction base64encoder filesink cstringa theprefs getconfigdir _t derencode messageend theprefs getlogsecureident adddebuglogline _t theprefs getverbose adddebuglogline _t c clientudp socket c clientudp socket m bwouldblock false m port 0 cclientudpsocket cclientudpsocket m_bwouldblock m_port c clientudp socket c clientudp socket the app upload bandwidth throttler remove from all queues this zz upload band with throttler udp position pos controlpacket queue get head position while pos udp pack p controlpacket queue get next pos delete p packet delete p cclientudpsocket cclientudpsocket theapp uploadbandwidththrottler removefromallqueues uploadbandwiththrottler controlpacket_queue getheadposition udppack controlpacket_queue getnext bool c clientudp socket create bool ret true if the prefs getudp port ret c async socket create the prefs getudp port sock dgram fd read fd write the prefs get bind addrw false if ret m port the prefs getudp port if ret m port the prefs getudp port return ret cclientudpsocket theprefs getudpport casyncsocket theprefs getudpport sock_dgram fd_read fd_write theprefs getbindaddrw m_port theprefs getudpport m_port theprefs getudpport bool c clientudp socket rebind if the prefs getudp port m port return false close return create cclientudpsocket theprefs getudpport m_port bool c clientudp socket send packet packet packet uint32 dwip uint16 n port udp pack newpending new udp pack newpending dwip dwip newpending n port n port newpending packet packet newpending dw time get tick count zz upload band with throttler udp send locker lock controlpacket queue add tail newpending send locker unlock the app upload bandwidth throttler queue for sending control packet this return true zz upload band with throttler udp cclientudpsocket sendpacket nport udppack udppack nport nport dwtime gettickcount uploadbandwiththrottler sendlocker controlpacket_queue addtail sendlocker theapp uploadbandwidththrottler queueforsendingcontrolpacket uploadbandwiththrottler socket sent bytes c clientudp socket send control data uint32 max number of bytes to send uint32 min frag size zz upload band with throttler udp zz upload band with throttler udp note this function is invoked from a different thread send locker lock uint32 sent bytes 0 zz upload band with throttler udp while controlpacket queue is empty is busy sent bytes max number of bytes to send zz upload band with throttler udp udp pack cur packet controlpacket queue get head if get tick count cur packet dw time udpmaxqueuetime char sendbuffer new char cur packet packet size 2 memcpy sendbuffer cur packet packet getudp header 2 memcpy sendbuffer 2 cur packet packet p buffer cur packet packet size if send to sendbuffer cur packet packet size 2 cur packet dwip cur packet n port sent bytes cur packet packet size 2 zz upload band with throttler udp controlpacket queue remove head delete cur packet packet delete cur packet delete sendbuffer else controlpacket queue remove head delete cur packet packet delete cur packet zz upload band with throttler udp if is busy controlpacket queue is empty the app upload bandwidth throttler queue for sending control packet this send locker unlock socket sent bytes return val true 0 sent bytes return return val zz upload band with throttler udp socketsentbytes cclientudpsocket sendcontroldata maxnumberofbytestosend minfragsize uploadbandwiththrottler uploadbandwiththrottler sendlocker sentbytes uploadbandwiththrottler controlpacket_queue isempty isbusy sentbytes maxnumberofbytestosend uploadbandwiththrottler udppack cur_packet controlpacket_queue gethead gettickcount cur_packet dwtime cur_packet cur_packet getudpheader cur_packet pbuffer cur_packet sendto cur_packet cur_packet cur_packet nport sentbytes cur_packet uploadbandwiththrottler controlpacket_queue removehead cur_packet cur_packet controlpacket_queue removehead cur_packet cur_packet uploadbandwiththrottler isbusy controlpacket_queue isempty theapp uploadbandwidththrottler queueforsendingcontrolpacket sendlocker socketsentbytes returnval sentbytes returnval uploadbandwiththrottler bool c clientudp socket process packet const byte packet uint size uint8 opcode uint32 ip uint16 port switch opcode case op reaskcallbackudp if the prefs get debug clientudp level 0 debug recv op reaskcallbackudp null null ip the stats add down data overhead other size c up down client buddy the app clientlist get buddy if buddy if size 17 buddy socket null break if md4cmp packet buddy get buddyid pokeu int32 const cast byte packet 10 ip pokeu int16 const cast byte packet 14 port packet response new packet op emuleprot response opcode op reaskcallbacktcp response p buffer new char size memcpy response p buffer packet 10 size 10 response size size 10 if the prefs get debug clienttcp level 0 debug send op reaskcallbacktcp buddy the stats add up data overhead file request response size buddy socket send packet response break case op reaskfileping the stats add down data overhead file request size c safe mem file data in packet size uchar reqfilehash 16 data in read hash16 reqfilehash c known file reqfile the app sharedfiles get file byid reqfilehash if reqfile if the prefs get debug clientudp level 0 debug recv op reaskfileping null reqfilehash ip debug send op filenotfound null packet response new packet op filenotfound 0 op emuleprot the stats add up data overhead file request response size send packet response ip port break c up down client sender the app uploadqueue getwaitingclientbyip udp ip port if sender if the prefs get debug clientudp level 0 debug recv op reaskfileping sender reqfilehash make sure we are still thinking about the same file if md4cmp reqfilehash sender get upload fileid 0 sender add asked count sender set last up request i messed up when i first added extended info to udp i should have originally used the entire process extened info the first time so now i am forced to check udp version to see if we are sending all the extended info for now on we should not have to change anything here if we change anything to the extended info data as this will be taken care of in process extended info update extended info if sender getudp version 3 sender process extended info data in reqfile update our complete source counts else if sender getudp version 2 uint16 n complete count last sender get up complete sources count uint16 n complete count new data in readu int16 sender set up complete sources count n complete count new if n complete count last n complete count new reqfile update parts info c safe mem file data out 128 if sender getudp version 3 if reqfile is part file c part file reqfile write part status data out else data out writeu int16 0 data out writeu int16 uint16 the app uploadqueue get waiting position sender if the prefs get debug clientudp level 0 debug send op reaskack sender packet response new packet data out op emuleprot response opcode op reaskack the stats add up data overhead file request response size the app clientudp send packet response ip port else debug log error t client udp socket reask file ping reqfile does not match trace t reqfile s n dbg get file info reqfile get file hash trace t sender get request file s n sender get request file dbg get file info sender get request file get file hash t null else if the prefs get debug clientudp level 0 debug recv op reaskfileping null reqfilehash ip if uint32 the app uploadqueue get waiting user count 50 the prefs get queue size if the prefs get debug clientudp level 0 debug send op queuefull null packet response new packet op queuefull 0 op emuleprot the stats add up data overhead file request response size send packet response ip port break case op queuefull the stats add down data overhead file request size c up down client sender the app downloadqueue getdownloadclientbyip udp ip port if the prefs get debug clientudp level 0 debug recv op queuefull sender null ip if sender sender set remote queue full true sender udp reaskack 0 break case op reaskack the stats add down data overhead file request size c up down client sender the app downloadqueue getdownloadclientbyip udp ip port if the prefs get debug clientudp level 0 debug recv op reaskack sender null ip if sender c safe mem file data in packet size if sender getudp version 3 sender process file status true data in sender get request file uint16 n rank data in readu int16 sender set remote queue full false sender udp reaskack n rank sender add asked count down break case op filenotfound the stats add down data overhead file request size c up down client sender the app downloadqueue getdownloadclientbyip udp ip port if the prefs get debug clientudp level 0 debug recv op filenotfound sender null ip if sender sender udp reaskfnf may delete sender sender null break case op porttest if the prefs get debug clientudp level 0 debug recv op porttest null null ip the stats add down data overhead other size if size 1 if packet 0 0x12 bool ret the app listensocket send port test reply 1 true add debug log line true t udp portcheck packet arrived ack sent back status i ret break default the stats add down data overhead other size if the prefs get debug clientudp level 0 c up down client sender the app downloadqueue getdownloadclientbyip udp ip port debug t unknown client udp packet host s u s opcode 0x 02x size u n ipstr ip port sender sender dbg get client info t opcode size return false return true cclientudpsocket processpacket op_reaskcallbackudp theprefs getdebugclientudplevel debugrecv op_reaskcallbackudp thestats adddowndataoverheadother cupdownclient theapp getbuddy getbuddyid pokeuint32 const_cast pokeuint16 const_cast op_emuleprot op_reaskcallbacktcp pbuffer pbuffer theprefs getdebugclienttcplevel debugsend op__reaskcallbacktcp thestats addupdataoverheadfilerequest sendpacket op_reaskfileping thestats adddowndataoverheadfilerequest csafememfile data_in data_in readhash16 cknownfile theapp getfilebyid theprefs getdebugclientudplevel debugrecv op_reaskfileping debugsend op__filenotfound op_filenotfound op_emuleprot thestats addupdataoverheadfilerequest sendpacket cupdownclient theapp getwaitingclientbyip_udp theprefs getdebugclientudplevel debugrecv op_reaskfileping getuploadfileid addaskedcount setlastuprequest processextenedinfo udpversion processextendedinfo getudpversion processextendedinfo data_in getudpversion ncompletecountlast getupcompletesourcescount ncompletecountnew data_in readuint16 setupcompletesourcescount ncompletecountnew ncompletecountlast ncompletecountnew updatepartsinfo csafememfile data_out getudpversion ispartfile cpartfile writepartstatus data_out data_out writeuint16 data_out writeuint16 theapp getwaitingposition theprefs getdebugclientudplevel debugsend op__reaskack data_out op_emuleprot op_reaskack thestats addupdataoverheadfilerequest theapp sendpacket debuglogerror _t reaskfileping _t dbggetfileinfo getfilehash _t getrequestfile getrequestfile dbggetfileinfo getrequestfile getfilehash _t theprefs getdebugclientudplevel debugrecv op_reaskfileping theapp getwaitingusercount theprefs getqueuesize theprefs getdebugclientudplevel debugsend op__queuefull op_queuefull op_emuleprot thestats addupdataoverheadfilerequest sendpacket op_queuefull thestats adddowndataoverheadfilerequest cupdownclient theapp getdownloadclientbyip_udp theprefs getdebugclientudplevel debugrecv op_queuefull setremotequeuefull udpreaskack op_reaskack thestats adddowndataoverheadfilerequest cupdownclient theapp getdownloadclientbyip_udp theprefs getdebugclientudplevel debugrecv op_reaskack csafememfile data_in getudpversion processfilestatus data_in getrequestfile nrank data_in readuint16 setremotequeuefull udpreaskack nrank addaskedcountdown op_filenotfound thestats adddowndataoverheadfilerequest cupdownclient theapp getdownloadclientbyip_udp theprefs getdebugclientudplevel debugrecv op_filenotfound udpreaskfnf op_porttest theprefs getdebugclientudplevel debugrecv op_porttest thestats adddowndataoverheadother theapp sendporttestreply adddebuglogline _t thestats adddowndataoverheadother theprefs getdebugclientudplevel cupdownclient theapp getdownloadclientbyip_udp _t dbggetclientinfo _t void c clientudp socket on send int n error code if n error code if the prefs get verbose debug log error t error client udp socket error on send event s get error message n error code 1 return zz upload band with throttler udp send locker lock m bwouldblock false if controlpacket queue is empty the app upload bandwidth throttler queue for sending control packet this send locker unlock zz upload band with throttler udp cclientudpsocket onsend nerrorcode nerrorcode theprefs getverbose debuglogerror _t geterrormessage nerrorcode uploadbandwiththrottler sendlocker m_bwouldblock controlpacket_queue isempty theapp uploadbandwidththrottler queueforsendingcontrolpacket sendlocker uploadbandwiththrottler void c clientudp socket on receive int n error code if n error code if the prefs get verbose debug log error t error client udp socket error on receive event s get error message n error code 1 byte buffer 5000 sockaddr in sock addr 0 int i sock addr len sizeof sock addr int length receive from buffer sizeof buffer sockaddr sock addr i sock addr len if length 1 the app ipfilter is filtered sock addr sin addr s un s addr the app clientlist is banned client sock addr sin addr s un s addr c string str error try switch buffer 0 case op emuleprot if length 2 process packet buffer 2 length 2 buffer 1 sock addr sin addr s un s addr ntohs sock addr sin port else throw c string t e mule packet too short break case op kademliapackedprot the stats add down data overhead kad length if length 2 uint32 n new size length 10 300 byte unpack new byte n new size u longf unpackedsize n new size 2 int iz lib result uncompress unpack 2 unpackedsize buffer 2 length 2 if iz lib result z ok unpack 0 op kademliaheader unpack 1 buffer 1 try kademlia c kademlia process packet unpack unpackedsize 2 ntohl sock addr sin addr s un s addr ntohs sock addr sin port catch delete unpack throw else delete unpack c string str error str error format t failed to uncompress kad packet zip error d hs iz lib result z error iz lib result throw str error delete unpack else throw c string t kad packet compressed too short break case op kademliaheader the stats add down data overhead kad length if length 2 kademlia c kademlia process packet buffer length ntohl sock addr sin addr s un s addr ntohs sock addr sin port else throw c string t kad packet too short break default c string str error str error format t unknown protocol 0x 02x buffer 0 throw str error catch c file exception error error delete str error t invalid packet received catch c memory exception error error delete str error t memory exception catch c string error str error error catch kademlia cio exception error error delete str error t invalid packet received catch c exception error error delete str error t general packet error catch str error t unknown exception assert 0 if the prefs get verbose str error is empty c string str client info c up down client client if buffer 0 op emuleprot client the app clientlist findclientbyip udp sock addr sin addr s un s addr ntohs sock addr sin port else client the app clientlist findclientbyip kadport sock addr sin addr s un s addr ntohs sock addr sin port if client str client info client dbg get client info else str client info format t s u ipstr sock addr sin addr ntohs sock addr sin port debug log warning t client udp socket prot 0x 02x opcode 0x 02x size u s s buffer 0 buffer 1 length str error str client info else if length socket error dword dw error wsa get last error if dw error wsaeconnreset depending on local and remote os and depending on used local remote router we may receive wsaeconnreset errors according some kb articles this is a special way of winsock to report that a sent udp packet was not received by the remote host because it was not listening on the specified port no e mule running there todo so actually we should do something with this information and drop the related kad node or e mule client if the prefs get verbose dw error wsaeconnreset c string str client info if i sock addr len 0 sock addr sin addr s un s addr 0 sock addr sin addr s un s addr inaddr none str client info format t from s u ipstr sock addr sin addr ntohs sock addr sin port debug log error t error client udp socket failed to receive data s s str client info get error message dw error 1 cclientudpsocket onreceive nerrorcode nerrorcode theprefs getverbose debuglogerror _t geterrormessage nerrorcode sockaddr_in sockaddr isockaddrlen sockaddr receivefrom sockaddr isockaddrlen theapp isfiltered sockaddr sin_addr s_un s_addr theapp isbannedclient sockaddr sin_addr s_un s_addr cstring strerror op_emuleprot processpacket sockaddr sin_addr s_un s_addr sockaddr sin_port cstring _t emule op_kademliapackedprot thestats adddowndataoverheadkad nnewsize nnewsize ulongf nnewsize izlibresult izlibresult z_ok op_kademliaheader ckademlia processpacket sockaddr sin_addr s_un s_addr sockaddr sin_port cstring strerror strerror _t izlibresult zerror izlibresult strerror cstring _t op_kademliaheader thestats adddowndataoverheadkad ckademlia processpacket sockaddr sin_addr s_un s_addr sockaddr sin_port cstring _t cstring strerror strerror _t strerror cfileexception strerror _t cmemoryexception strerror _t cstring strerror cioexception strerror _t cexception strerror _t strerror _t theprefs getverbose strerror isempty cstring strclientinfo cupdownclient op_emuleprot theapp findclientbyip_udp sockaddr sin_addr s_un s_addr sockaddr sin_port theapp findclientbyip_kadport sockaddr sin_addr s_un s_addr sockaddr sin_port strclientinfo dbggetclientinfo strclientinfo _t sockaddr sin_addr sockaddr sin_port debuglogwarning _t strerror strclientinfo socket_error dwerror wsagetlasterror dwerror emule emule theprefs getverbose dwerror cstring strclientinfo isockaddrlen sockaddr sin_addr s_un s_addr sockaddr sin_addr s_un s_addr inaddr_none strclientinfo _t sockaddr sin_addr sockaddr sin_port debuglogerror _t strclientinfo geterrormessage dwerror int c clientudp socket send to char lp buf int n buf len uint32 dwip uint16 n port note this function is invoked from a different thread uint32 result c async socket send to lp buf n buf len n port ipstr dwip if result uint32 socket error uint32 error get last error if error wsaewouldblock m bwouldblock true return 1 if the prefs get verbose debug log error t error client udp socket failed to send data to s u s ipstr dwip n port get error message error 1 return 0 cclientudpsocket sendto lpbuf nbuflen nport casyncsocket sendto lpbuf nbuflen nport socket_error getlasterror m_bwouldblock theprefs getverbose debuglogerror _t nport geterrormessage c abstract file c abstract file md4clr m abyfilehash m nfilesize uint64 0 m urating 0 m bcommentloaded false m uuserrating 0 m bhascomment false cabstractfile cabstractfile m_abyfilehash m_nfilesize m_urating m_bcommentloaded m_uuserrating m_bhascomment c abstract file c abstract file const c abstract file p abstract file m strfilename p abstract file m strfilename md4cpy m abyfilehash p abstract file get file hash m nfilesize p abstract file m nfilesize m strcomment p abstract file m strcomment m urating p abstract file m urating m bcommentloaded p abstract file m bcommentloaded m uuserrating p abstract file m uuserrating m bhascomment p abstract file m bhascomment m strfiletype p abstract file m strfiletype const c typed ptr list c ptr list kademlia c entry list p abstract file get notes for position pos list get head position pos null kademlia c entry entry list get next pos m kadnotes add tail entry copy copy tags p abstract file get tags cabstractfile cabstractfile cabstractfile pabstractfile m_strfilename pabstractfile m_strfilename m_abyfilehash pabstractfile getfilehash m_nfilesize pabstractfile m_nfilesize m_strcomment pabstractfile m_strcomment m_urating pabstractfile m_urating m_bcommentloaded pabstractfile m_bcommentloaded m_uuserrating pabstractfile m_uuserrating m_bhascomment pabstractfile m_bhascomment m_strfiletype pabstractfile m_strfiletype ctypedptrlist cptrlist centry pabstractfile getnotes getheadposition centry getnext m_kadnotes addtail copytags pabstractfile gettags c abstract file c abstract file clear tags for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos delete entry cabstractfile cabstractfile cleartags m_kadnotes getheadposition centry m_kadnotes getnext void c abstract file set file name lpctstr psz file name bool b replace invalid file system chars bool b auto set file type m strfilename psz file name if b replace invalid file system chars m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t m strfilename replace t t if b auto set file type set file type get file type by name m strfilename cabstractfile setfilename pszfilename breplaceinvalidfilesystemchars bautosetfiletype m_strfilename pszfilename breplaceinvalidfilesystemchars m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t m_strfilename _t _t bautosetfiletype setfiletype getfiletypebyname m_strfilename void c abstract file set file type lpctstr psz file type m strfiletype psz file type cabstractfile setfiletype pszfiletype m_strfiletype pszfiletype c string c abstract file get file type display str const c string str file type display str get file type display str fromed2k file type get file type if str file type display str is empty str file type display str get file type return str file type display str cstring cabstractfile getfiletypedisplaystr cstring strfiletypedisplaystr getfiletypedisplaystrfromed2kfiletype getfiletype strfiletypedisplaystr isempty strfiletypedisplaystr getfiletype strfiletypedisplaystr void c abstract file set file hash const uchar puc file hash md4cpy m abyfilehash puc file hash cabstractfile setfilehash pucfilehash m_abyfilehash pucfilehash bool c abstract file has null hash const return isnulmd4 m abyfilehash cabstractfile hasnullhash m_abyfilehash uint32 c abstract file get int tag value uint8 tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid tagname p tag is int return p tag get int return null cabstractfile getinttagvalue getsize ctag ptag ptag getnameid ptag isint ptag getint uint32 c abstract file get int tag value lpcstr tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid 0 p tag is int cmped2k tag name p tag get name tagname 0 return p tag get int return null cabstractfile getinttagvalue getsize ctag ptag ptag getnameid ptag isint cmped2ktagname ptag getname ptag getint bool c abstract file get int tag value uint8 tagname uint32 ru value const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid tagname p tag is int ru value p tag get int return true return false cabstractfile getinttagvalue ruvalue getsize ctag ptag ptag getnameid ptag isint ruvalue ptag getint uint64 c abstract file get int64 tag value uint8 tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid tagname p tag is int64 true return p tag get int64 return null cabstractfile getint64tagvalue getsize ctag ptag ptag getnameid ptag isint64 ptag getint64 uint64 c abstract file get int64 tag value lpcstr tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid 0 p tag is int64 true cmped2k tag name p tag get name tagname 0 return p tag get int64 return null cabstractfile getint64tagvalue getsize ctag ptag ptag getnameid ptag isint64 cmped2ktagname ptag getname ptag getint64 bool c abstract file get int64 tag value uint8 tagname uint64 ru value const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid tagname p tag is int64 true ru value p tag get int64 return true return false cabstractfile getint64tagvalue ruvalue getsize ctag ptag ptag getnameid ptag isint64 ruvalue ptag getint64 void c abstract file set int tag value uint8 tagname uint32 u value for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid tagname p tag is int p tag set int u value return c tag p tag new c tag tagname u value taglist add p tag cabstractfile setinttagvalue uvalue getsize ctag ptag ptag getnameid ptag isint ptag setint uvalue ctag ptag ctag uvalue ptag void c abstract file set int64 tag value uint8 tagname uint64 u value for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid tagname p tag is int64 true p tag set int64 u value return c tag p tag new c tag tagname u value taglist add p tag cabstractfile setint64tagvalue uvalue getsize ctag ptag ptag getnameid ptag isint64 ptag setint64 uvalue ctag ptag ctag uvalue ptag const c string c abstract file get str tag value uint8 tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid tagname p tag is str return p tag get str static const c string strempty return strempty cstring cabstractfile getstrtagvalue getsize ctag ptag ptag getnameid ptag isstr ptag getstr cstring _strempty _strempty const c string c abstract file get str tag value lpcstr tagname const for int i 0 i taglist get size i const c tag p tag taglist i if p tag get nameid 0 p tag is str cmped2k tag name p tag get name tagname 0 return p tag get str static const c string strempty return strempty cstring cabstractfile getstrtagvalue getsize ctag ptag ptag getnameid ptag isstr cmped2ktagname ptag getname ptag getstr cstring _strempty _strempty void c abstract file set str tag value uint8 tagname lpctstr psz value for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid tagname p tag is str p tag set str psz value return c tag p tag new c tag tagname psz value taglist add p tag cabstractfile setstrtagvalue pszvalue getsize ctag ptag ptag getnameid ptag isstr ptag setstr pszvalue ctag ptag ctag pszvalue ptag c tag c abstract file get tag uint8 tagname uint8 tagtype const for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid tagname p tag get type tagtype return p tag return null ctag cabstractfile gettag getsize ctag ptag ptag getnameid ptag gettype ptag c tag c abstract file get tag lpcstr tagname uint8 tagtype const for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid 0 p tag get type tagtype cmped2k tag name p tag get name tagname 0 return p tag return null ctag cabstractfile gettag getsize ctag ptag ptag getnameid ptag gettype cmped2ktagname ptag getname ptag c tag c abstract file get tag uint8 tagname const for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid tagname return p tag return null ctag cabstractfile gettag getsize ctag ptag ptag getnameid ptag c tag c abstract file get tag lpcstr tagname const for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid 0 cmped2k tag name p tag get name tagname 0 return p tag return null ctag cabstractfile gettag getsize ctag ptag ptag getnameid cmped2ktagname ptag getname ptag void c abstract file add tag unique c tag p tag for int i 0 i taglist get size i const c tag p cur tag taglist i if p cur tag get nameid 0 p cur tag get nameid p tag get nameid p cur tag get name null p tag get name null cmped2k tag name p cur tag get name p tag get name 0 p cur tag get type p tag get type delete p cur tag taglist set at i p tag return taglist add p tag cabstractfile addtagunique ctag ptag getsize ctag pcurtag pcurtag getnameid pcurtag getnameid ptag getnameid pcurtag getname ptag getname cmped2ktagname pcurtag getname ptag getname pcurtag gettype ptag gettype pcurtag setat ptag ptag void c abstract file clear tags for int i 0 i taglist get size i delete taglist i taglist remove all cabstractfile cleartags getsize removeall void c abstract file copy tags const c array c tag c tag tags for int i 0 i tags get size i taglist add new c tag tags get at i cabstractfile copytags carray ctag ctag getsize ctag getat const c string c abstract file get file comment const if m bcommentloaded load comment return m strcomment cstring cabstractfile getfilecomment m_bcommentloaded loadcomment m_strcomment uint c abstract file get file rating const if m bcommentloaded load comment return m urating cabstractfile getfilerating m_bcommentloaded loadcomment m_urating void c abstract file load comment c ini ini the prefs get file comments file path md4str get file hash m strcomment ini get stringutf8 t comment left maxfilecommentlen m urating ini get int t rate 0 m bcommentloaded true cabstractfile loadcomment cini theprefs getfilecommentsfilepath getfilehash m_strcomment getstringutf8 _t m_urating getint _t m_bcommentloaded bool c abstract file add note kademlia c entry p entry for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos if entry m usourceid p entry m usourceid assert entry p entry return false m kadnotes add head p entry update file rating comment avail return true cabstractfile addnote centry pentry m_kadnotes getheadposition centry m_kadnotes getnext m_usourceid pentry m_usourceid pentry m_kadnotes addhead pentry updatefileratingcommentavail void c up down client start download set download state ds downloading init transferred down mini set down start time m lastpartasked uint16 1 send block requests cupdownclient startdownload setdownloadstate ds_downloading inittransferreddownmini setdownstarttime m_lastpartasked sendblockrequests void c up down client check download timeout if is downloading from peer cache m ppcdownsocket m ppcdownsocket is connected assert downloadtimeout m ppcdownsocket get time out if get tick count m dwlastblockreceived downloadtimeout on peer cache down socket timeout else if get tick count m dwlastblockreceived downloadtimeout assert socket null if socket null assert socket is raw data mode if socket is raw data mode send cancel transfer set download state ds onqueue t timeout more than 100 seconds since last complete block was received cupdownclient checkdownloadtimeout isdownloadingfrompeercache m_ppcdownsocket m_ppcdownsocket isconnected m_ppcdownsocket gettimeout gettickcount m_dwlastblockreceived onpeercachedownsockettimeout gettickcount m_dwlastblockreceived israwdatamode israwdatamode sendcanceltransfer setdownloadstate ds_onqueue _t void c up down client send cancel transfer packet packet if socket null is ed2k client assert 0 return if get sent cancel transfer if the prefs get debug clienttcp level 0 debug send op canceltransfer this bool b delete packet packet p cancel transfer packet if packet p cancel transfer packet packet b delete packet false else p cancel transfer packet new packet op canceltransfer 0 b delete packet true the stats add up data overhead file request p cancel transfer packet size socket send packet p cancel transfer packet b delete packet true set sent cancel transfer 1 if m ppcdownsocket m ppcdownsocket safe delete m ppcdownsocket null set peer cache down state pcds none cupdownclient sendcanceltransfer ised2kclient getsentcanceltransfer theprefs getdebugclienttcplevel debugsend op__canceltransfer bdeletepacket pcanceltransferpacket pcanceltransferpacket bdeletepacket pcanceltransferpacket op_canceltransfer bdeletepacket thestats addupdataoverheadfilerequest pcanceltransferpacket sendpacket pcanceltransferpacket bdeletepacket setsentcanceltransfer m_ppcdownsocket m_ppcdownsocket safe_delete m_ppcdownsocket setpeercachedownstate pcds_none void setip uint32 val only use this when you know the real ip or when your clearing it m dwuserip val m nconnectip val m_dwuserip m_nconnectip bool has valid hash const return const int m achuserhash 0 0 const int m achuserhash 1 0 const int m achuserhash 2 0 const int m achuserhash 3 0 hasvalidhash m_achuserhash m_achuserhash m_achuserhash m_achuserhash void c up down client process emule queue rank const uchar packet uint size if size 12 throw get res string ids err badsize uint16 rank peeku int16 packet if the prefs get debug clienttcp level 0 debug t qr u n rank no prev qr available for e mule clients set remote queue full false set remote queue rank rank get download state ds onqueue check queue rank flood cupdownclient processemulequeuerank getresstring ids_err_badsize peekuint16 theprefs getdebugclienttcplevel _t emule setremotequeuefull setremotequeuerank getdownloadstate ds_onqueue checkqueuerankflood void c up down client process edonkey queue rank const uchar packet uint size c safe mem file data packet size uint32 rank data readu int32 if the prefs get debug clienttcp level 0 debug t qr u prev d n rank is remote queue full uint 1 uint get remote queue rank set remote queue rank rank get download state ds onqueue check queue rank flood cupdownclient processedonkeyqueuerank csafememfile readuint32 theprefs getdebugclienttcplevel _t isremotequeuefull getremotequeuerank setremotequeuerank getdownloadstate ds_onqueue checkqueuerankflood void c up down client check queue rank flood if m fqueuerankpending 0 if get download state ds downloading if m funaskqueuerankrecv 3 note do not increase this nr without increasing the bits for m funaskqueuerankrecv m funaskqueuerankrecv if m funaskqueuerankrecv 3 if the app clientlist get bad requests this 2 the app clientlist track bad request this 1 if the app clientlist get bad requests this 2 the app clientlist track bad request this 2 reset so the client will not be rebanned right after the ban is lifted ban t qr flood throw c string the prefs get log banned clients t qr flood t else m fqueuerankpending 0 m funaskqueuerankrecv 0 cupdownclient checkqueuerankflood m_fqueuerankpending getdownloadstate ds_downloading m_funaskqueuerankrecv m_funaskqueuerankrecv m_funaskqueuerankrecv m_funaskqueuerankrecv theapp getbadrequests theapp trackbadrequest theapp getbadrequests theapp trackbadrequest _t cstring theprefs getlogbannedclients _t _t m_fqueuerankpending m_funaskqueuerankrecv bool c up down client compare const c up down client tocomp bool b ignore userhash const compare only the user hash if b ignore userhash has valid hash tocomp has valid hash return md4cmp this get user hash tocomp get user hash if has lowid user is firewalled must do two checks if getip 0 getip tocomp getip the ip of both match if get user port 0 get user port tocomp get user port ip user port matches return true if get kad port 0 get kad port tocomp get kad port ip kad port matches return true if get userid hybrid 0 get userid hybrid tocomp get userid hybrid get serverip 0 get serverip tocomp get serverip get server port 0 get server port tocomp get server port both have the same lowid same serverip and port return true if defined debug if has valid buddyid tocomp has valid buddyid johntodo this is for future use to see if this will be needed if md4cmp get buddyid tocomp get buddyid return true endif both ip and server do not match return false user is not firewalled if get user port 0 user has a port lets check the rest if getip 0 tocomp getip 0 both clients have a verified ip if getip tocomp getip get user port tocomp get user port ip and user port match return true else one of the two clients do not have a verified ip if get userid hybrid tocomp get userid hybrid get user port tocomp get user port id and port match return true if get kad port 0 user has a kad port if getip 0 tocomp getip 0 both clients have a verified ip if getip tocomp getip get kad port tocomp get kad port ip and kad port match return true else one of the users do not have a verified ip if get userid hybrid tocomp get userid hybrid get kad port tocomp get kad port id and kad prot match return true no matches return false cupdownclient cupdownclient bignoreuserhash bignoreuserhash hasvalidhash hasvalidhash getuserhash getuserhash haslowid getuserport getuserport getuserport userport getkadport getkadport getkadport kadport getuseridhybrid getuseridhybrid getuseridhybrid getserverip getserverip getserverip getserverport getserverport getserverport _debug hasvalidbuddyid hasvalidbuddyid getbuddyid getbuddyid getuserport getuserport getuserport userport getuseridhybrid getuseridhybrid getuserport getuserport getkadport getkadport getkadport kadport getuseridhybrid getuseridhybrid getkadport getkadport kadprot uint get session up const return m ntransferredup m ncursessionup void reset session up m ncursessionup m ntransferredup m addedpayloadqueuesession 0 m ncurqueuesessionpayloadup 0 getsessionup m_ntransferredup m_ncursessionup resetsessionup m_ncursessionup m_ntransferredup m_addedpayloadqueuesession m_ncurqueuesessionpayloadup uint get session down const return m ntransferreddown m ncursessiondown void reset session down m ncursessiondown m ntransferreddown getsessiondown m_ntransferreddown m_ncursessiondown resetsessiondown m_ncursessiondown m_ntransferreddown void draw up status bar cdc dc rect rect bool onlygreyrect bool b flat const bool is up part available uint i part const return i part m nuppartcount m abyuppartstatus false m abyuppartstatus i part 0 drawupstatusbar bflat isuppartavailable ipart ipart m_nuppartcount m_abyuppartstatus m_abyuppartstatus ipart void c up down client set download state e download state n new state lpctstr psz reason if m ndownloadstate n new state switch n new state case ds connecting m dwlasttriedtoconnect get tick count break case ds toomanyconnskad this client had already been set to ds connecting so we reset this time so it isn t stuck at toomanyconns for 20mins m dwlasttriedtoconnect get tick count 20 60 1000 break case ds waitcallbackkad case ds waitcallback break case ds noneededparts since tcp asks never sets reask time if the result is ds noneededparts if we set this we will not reask for that file until some time has passed set last asked time dont swap to reqfile default switch m ndownloadstate case ds waitcallback case ds waitcallbackkad break default m dwlasttriedtoconnect get tick count 20 60 1000 break break if reqfile if n new state ds downloading if the prefs get log ul dl events add debug log line dlp verylow false t download session started user s in set download state new state i dbg get client info n new state reqfile add downloading source this else if m ndownloadstate ds downloading reqfile remove downloading source this if n new state ds downloading socket socket set time out connection timeout 4 if m ndownloadstate ds downloading if socket socket set time out connection timeout if the prefs get log ul dl events switch n new state case ds noneededparts psz reason t nnp you don t need any parts from this client if the prefs get log ul dl events add debug log line dlp verylow false t download session ended s user s in set download state new state i length s transferred s psz reason dbg get client info n new state cast seconds tohm get down time difference false 1000 cast itox bytes get session down false false reset session down khaos extended statistics successful failed download sessions if m btransferreddownmini n new state ds error the prefs add2 down successful sessions increment our counters for successful sessions cumulative and session else the prefs add2 down failed sessions increment our counters failed sessions cumulative and session the prefs add2 downs avg time get down time difference 1000 khaos m ndownloadstate edownloadstate n new state clear download block requests m ndowndatarate 0 m avarageddr list remove all m nsumforavgdowndatarate 0 if n new state ds none delete m abypartstatus m abypartstatus null m npartcount 0 if socket n new state ds error socket disable download limit m ndownloadstate edownloadstate n new state if get download state ds downloading if is emule client set remote queue full false set remote queue rank 0 set asked count down 0 update displayed info true cupdownclient setdownloadstate edownloadstate nnewstate pszreason m_ndownloadstate nnewstate nnewstate ds_connecting m_dwlasttriedtoconnect gettickcount ds_toomanyconnskad ds_connecting m_dwlasttriedtoconnect gettickcount ds_waitcallbackkad ds_waitcallback ds_noneededparts ds_noneededparts setlastaskedtime dontswapto m_ndownloadstate ds_waitcallback ds_waitcallbackkad m_dwlasttriedtoconnect gettickcount nnewstate ds_downloading theprefs getloguldlevents adddebuglogline dlp_verylow _t setdownloadstate dbggetclientinfo nnewstate adddownloadingsource m_ndownloadstate ds_downloading removedownloadingsource nnewstate ds_downloading settimeout connection_timeout m_ndownloadstate ds_downloading settimeout connection_timeout theprefs getloguldlevents nnewstate ds_noneededparts pszreason _t theprefs getloguldlevents adddebuglogline dlp_verylow _t setdownloadstate pszreason dbggetclientinfo nnewstate castsecondstohm getdowntimedifference castitoxbytes getsessiondown resetsessiondown m_btransferreddownmini nnewstate ds_error theprefs add2downsuccessfulsessions theprefs add2downfailedsessions theprefs add2downsavgtime getdowntimedifference m_ndownloadstate _edownloadstate nnewstate cleardownloadblockrequests m_ndowndatarate m_avarageddr_list removeall m_nsumforavgdowndatarate nnewstate ds_none m_abypartstatus m_abypartstatus m_npartcount nnewstate ds_error disabledownloadlimit m_ndownloadstate _edownloadstate nnewstate getdownloadstate ds_downloading isemuleclient setremotequeuefull setremotequeuerank setaskedcountdown updatedisplayedinfo uint32 c up down client get last asked time const c part file part file const c part file file c part file part file if file null file reqfile dword last changed tick return m filereasktimes lookup file last changed tick last changed tick 0 cupdownclient getlastaskedtime cpartfile partfile cpartfile cpartfile partfile lastchangedtick m_filereasktimes lastchangedtick lastchangedtick void set last asked time m filereasktimes set at reqfile get tick count bool is part available uint i part const return i part m npartcount m abypartstatus false m abypartstatus i part 0 setlastaskedtime m_filereasktimes setat gettickcount ispartavailable ipart ipart m_npartcount m_abypartstatus m_abypartstatus ipart void c up down client set remote queue rank uint nr bool b update display m nremotequeuerank nr update displayed info b update display cupdownclient setremotequeuerank bupdatedisplay m_nremotequeuerank updatedisplayedinfo bupdatedisplay void c up down client draw status bar cdc dc lpcrect rect bool onlygreyrect bool b flat const if g blowcolordesktop b flat true colorref cr neither if b flat if g blowcolordesktop cr neither rgb 192 192 192 else cr neither rgb 224 224 224 else cr neither rgb 240 240 240 assert reqfile s statusbar set file size reqfile get file size s statusbar set height rect bottom rect top s statusbar set width rect right rect left s statusbar fill cr neither if onlygreyrect reqfile m abypartstatus colorref cr both colorref cr client only colorref cr pending colorref cr next pending if g blowcolordesktop cr both rgb 0 0 0 cr client only rgb 0 0 255 cr pending rgb 0 255 0 cr next pending rgb 255 255 0 else if b flat cr both rgb 0 0 0 cr client only rgb 0 100 255 cr pending rgb 0 150 0 cr next pending rgb 255 208 0 else cr both rgb 104 104 104 cr client only rgb 0 100 255 cr pending rgb 0 150 0 cr next pending rgb 255 208 0 char pc next pending blks null if m ndownloadstate ds downloading pc next pending blks new char m npartcount memset pc next pending blks n m npartcount do not use strnset for uninitialized memory for position pos m pendingblocks list get head position pos 0 uint u part uint m pendingblocks list get next pos block start offset partsize if u part m npartcount pc next pending blks u part y for uint i 0 i m npartcount i if m abypartstatus i uint64 u end if partsize uint64 i 1 reqfile get file size u end reqfile get file size else u end partsize uint64 i 1 if reqfile is complete partsize uint64 i partsize uint64 i 1 1 false s statusbar fill range partsize uint64 i u end cr both else if m ndownloadstate ds downloading m nlastblockoffset partsize uint64 i m nlastblockoffset u end s statusbar fill range partsize uint64 i u end cr pending else if pc next pending blks null pc next pending blks i y s statusbar fill range partsize uint64 i u end cr next pending else s statusbar fill range partsize uint64 i u end cr client only delete pc next pending blks s statusbar draw dc rect left rect top b flat cupdownclient drawstatusbar bflat g_blowcolordesktop bflat crneither bflat g_blowcolordesktop crneither crneither crneither s_statusbar setfilesize getfilesize s_statusbar setheight s_statusbar setwidth s_statusbar crneither m_abypartstatus crboth crclientonly crpending crnextpending g_blowcolordesktop crboth crclientonly crpending crnextpending bflat crboth crclientonly crpending crnextpending crboth crclientonly crpending crnextpending pcnextpendingblks m_ndownloadstate ds_downloading pcnextpendingblks m_npartcount pcnextpendingblks m_npartcount _strnset m_pendingblocks_list getheadposition upart m_pendingblocks_list getnext startoffset upart m_npartcount pcnextpendingblks upart m_npartcount m_abypartstatus uend getfilesize uend getfilesize uend iscomplete s_statusbar fillrange uend crboth m_ndownloadstate ds_downloading m_nlastblockoffset m_nlastblockoffset uend s_statusbar fillrange uend crpending pcnextpendingblks pcnextpendingblks s_statusbar fillrange uend crnextpending s_statusbar fillrange uend crclientonly pcnextpendingblks s_statusbar bflat bool c up down client ask for download if the app listensocket too many sockets socket socket is connected if get download state ds toomanyconns set download state ds toomanyconns return true if m budppending m nfailedudppackets the app downloadqueue add failedudp file reasks m budppending false swap to another file t a4af check before tcp file reask c up down client ask for download true false false null true true set download state ds connecting return try to connect cupdownclient askfordownload theapp toomanysockets isconnected getdownloadstate ds_toomanyconns setdownloadstate ds_toomanyconns m_budppending m_nfailedudppackets theapp addfailedudpfilereasks m_budppending swaptoanotherfile _t cupdownclient askfordownload setdownloadstate ds_connecting trytoconnect void c up down client send file request normally asktime has already been reset here but then swap to another file will return without much work so check to make sure swap to another file t a4af check before tcp file reask c up down client send file request true false false null true true assert reqfile null if reqfile return add asked count down c safe mem file data file req 16 16 data file req write hash16 reqfile get file hash if support multi packet if support ext multi packet data file req writeu int64 reqfile get file size if the prefs get debug clienttcp level 0 debug send op multipacket ext this reqfile get file hash else if the prefs get debug clienttcp level 0 debug send op multipacket this reqfile get file hash op requestfilename ext info if the prefs get debug clienttcp level 0 debug send op mpreqfilename this reqfile get file hash data file req writeu int8 op requestfilename if get extended requests version 0 reqfile write part status data file req if get extended requests version 1 reqfile write complete sources count data file req op setreqfileid if the prefs get debug clienttcp level 0 debug send op mpsetreqfileid this reqfile get file hash if reqfile get part count 1 data file req writeu int8 op setreqfileid if is emule client set remote queue full true set remote queue rank 0 op requestsources if is source request allowed if the prefs get debug clienttcp level 0 debug send op mpreqsources this reqfile get file hash if get last asked for sources 0 debug t first source request n else debug t last source request was before s n cast seconds tohm get tick count get last asked for sources 1000 data file req writeu int8 op requestsources reqfile set last answered time timeout set last asked for sources if the prefs get debug source exchange add debug log line false t sx send client source request s file s dbg get client info reqfile get file name op aichfilehashreq if is supportingaich if the prefs get debug clienttcp level 0 debug send op mpaichfilehashreq this reqfile get file hash data file req writeu int8 op aichfilehashreq packet packet new packet data file req op emuleprot packet opcode support ext multi packet op multipacket ext op multipacket the stats add up data overhead file request packet size socket send packet packet true else this is extended information if get extended requests version 0 reqfile write part status data file req if get extended requests version 1 reqfile write complete sources count data file req if the prefs get debug clienttcp level 0 debug send op filerequest this reqfile get file hash packet packet new packet data file req packet opcode op requestfilename the stats add up data overhead file request packet size socket send packet packet true 26 jul 2003 removed requesting the file status for files partsize for better compatibility with ed2k protocol e donkey hybrid if the remote client answers the op requestfilename with op reqfilenameanswer the file is shared by the remote client if we know that the file is shared we know also that the file is complete and don t need to request the file status if reqfile get part count 1 if the prefs get debug clienttcp level 0 debug send op setreqfileid this reqfile get file hash c safe mem file data set req fileid 16 data set req fileid write hash16 reqfile get file hash packet new packet data set req fileid packet opcode op setreqfileid the stats add up data overhead file request packet size socket send packet packet true if is emule client set remote queue full true set remote queue rank 0 if is source request allowed if the prefs get debug clienttcp level 0 debug send op requestsources this reqfile get file hash if get last asked for sources 0 debug t first source request n else debug t last source request was before s n cast seconds tohm get tick count get last asked for sources 1000 reqfile set last answered time timeout packet packet new packet op requestsources 16 op emuleprot md4cpy packet p buffer reqfile get file hash the stats add up data overhead source exchange packet size socket send packet packet true true set last asked for sources if the prefs get debug source exchange add debug log line false t sx send client source request s file s dbg get client info reqfile get file name if is supportingaich if the prefs get debug clienttcp level 0 debug send op aichfilehashreq this reqfile get file hash packet packet new packet op aichfilehashreq 16 op emuleprot md4cpy packet p buffer reqfile get file hash the stats add up data overhead file request packet size socket send packet packet true true set last asked time cupdownclient sendfilerequest swaptoanotherfile swaptoanotherfile _t cupdownclient sendfilerequest addaskedcountdown csafememfile datafilereq datafilereq writehash16 getfilehash supportmultipacket supportextmultipacket datafilereq writeuint64 getfilesize theprefs getdebugclienttcplevel debugsend op__multipacket_ext getfilehash theprefs getdebugclienttcplevel debugsend op__multipacket getfilehash op_requestfilename extinfo theprefs getdebugclienttcplevel debugsend op__mpreqfilename getfilehash datafilereq writeuint8 op_requestfilename getextendedrequestsversion writepartstatus datafilereq getextendedrequestsversion writecompletesourcescount datafilereq op_setreqfileid theprefs getdebugclienttcplevel debugsend op__mpsetreqfileid getfilehash getpartcount datafilereq writeuint8 op_setreqfileid isemuleclient setremotequeuefull setremotequeuerank op_requestsources issourcerequestallowed theprefs getdebugclienttcplevel debugsend op__mpreqsources getfilehash getlastaskedforsources _t _t castsecondstohm gettickcount getlastaskedforsources datafilereq writeuint8 op_requestsources setlastansweredtimetimeout setlastaskedforsources theprefs getdebugsourceexchange adddebuglogline _t sxsend dbggetclientinfo getfilename op_aichfilehashreq issupportingaich theprefs getdebugclienttcplevel debugsend op__mpaichfilehashreq getfilehash datafilereq writeuint8 op_aichfilehashreq datafilereq op_emuleprot supportextmultipacket op_multipacket_ext op_multipacket thestats addupdataoverheadfilerequest sendpacket getextendedrequestsversion writepartstatus datafilereq getextendedrequestsversion writecompletesourcescount datafilereq theprefs getdebugclienttcplevel debugsend op__filerequest getfilehash datafilereq op_requestfilename thestats addupdataoverheadfilerequest sendpacket edonkeyhybrid op_requestfilename op_reqfilenameanswer getpartcount theprefs getdebugclienttcplevel debugsend op__setreqfileid getfilehash csafememfile datasetreqfileid datasetreqfileid writehash16 getfilehash datasetreqfileid op_setreqfileid thestats addupdataoverheadfilerequest sendpacket isemuleclient setremotequeuefull setremotequeuerank issourcerequestallowed theprefs getdebugclienttcplevel debugsend op__requestsources getfilehash getlastaskedforsources _t _t castsecondstohm gettickcount getlastaskedforsources setlastansweredtimetimeout op_requestsources op_emuleprot pbuffer getfilehash thestats addupdataoverheadsourceexchange sendpacket setlastaskedforsources theprefs getdebugsourceexchange adddebuglogline _t sxsend dbggetclientinfo getfilename issupportingaich theprefs getdebugclienttcplevel debugsend op__aichfilehashreq getfilehash op_aichfilehashreq op_emuleprot pbuffer getfilehash thestats addupdataoverheadfilerequest sendpacket setlastaskedtime void c up down client send startup load req if socket null reqfile null assert 0 return set download state ds onqueue if the prefs get debug clienttcp level 0 debug send op startuploadreq this c safe mem file data startup load req 16 data startup load req write hash16 reqfile get file hash packet packet new packet data startup load req packet opcode op startuploadreq the stats add up data overhead file request packet size socket send packet packet true true m fqueuerankpending 1 m funaskqueuerankrecv 0 cupdownclient sendstartuploadreq setdownloadstate ds_onqueue theprefs getdebugclienttcplevel debugsend op__startuploadreq csafememfile datastartuploadreq datastartuploadreq writehash16 getfilehash datastartuploadreq op_startuploadreq thestats addupdataoverheadfilerequest sendpacket m_fqueuerankpending m_funaskqueuerankrecv void c up down client process file info c safe mem file data c part file file if file null throw get res string ids err wrongfileid t process file info file null if reqfile null throw get res string ids err wrongfileid t process file info reqfile null if file reqfile throw get res string ids err wrongfileid t process file info reqfile file m strclientfilename data read string get unicode support utf8str none if the prefs get debug clienttcp level 0 debug t filename s n m strclientfilename 26 jul 2003 removed requesting the file status for files partsize for better compatibility with ed2k protocol e donkey hybrid if the remote client answers the op requestfilename with op reqfilenameanswer the file is shared by the remote client if we know that the file is shared we know also that the file is complete and don t need to request the file status if reqfile get part count 1 delete m abypartstatus m abypartstatus null m npartcount reqfile get part count m abypartstatus new uint8 m npartcount memset m abypartstatus 1 m npartcount m bcompletesource true if the prefs get debug clienttcp level 0 int i needed 0 for uint i 0 i m npartcount i if reqfile is complete uint64 i partsize uint64 i 1 partsize 1 false i needed char psz new char m npartcount 1 for uint i 0 i m npartcount i psz i m abypartstatus i psz i 0 debug t parts u hs needed u n m npartcount psz i needed delete psz update displayed info reqfile update available parts count even if the file is partsize we may need the hashset for that file if the file size partsize if reqfile hashsetneeded if socket if the prefs get debug clienttcp level 0 debug send op hashsetrequest this reqfile get file hash packet packet new packet op hashsetrequest 16 md4cpy packet p buffer reqfile get file hash the stats add up data overhead file request packet size socket send packet packet true true set download state ds reqhashset m fhashsetrequesting 1 reqfile hashsetneeded false else assert 0 else send startup load req reqfile update parts info cupdownclient processfileinfo csafememfile cpartfile getresstring ids_err_wrongfileid _t processfileinfo getresstring ids_err_wrongfileid _t processfileinfo getresstring ids_err_wrongfileid _t processfileinfo m_strclientfilename readstring getunicodesupport utf8strnone theprefs getdebugclienttcplevel _t m_strclientfilename edonkeyhybrid op_requestfilename op_reqfilenameanswer getpartcount m_abypartstatus m_abypartstatus m_npartcount getpartcount m_abypartstatus m_npartcount m_abypartstatus m_npartcount m_bcompletesource theprefs getdebugclienttcplevel ineeded m_npartcount iscomplete ineeded m_npartcount m_npartcount m_abypartstatus _t m_npartcount ineeded updatedisplayedinfo updateavailablepartscount _may_ theprefs getdebugclienttcplevel debugsend op__hashsetrequest getfilehash op_hashsetrequest pbuffer getfilehash thestats addupdataoverheadfilerequest sendpacket setdownloadstate ds_reqhashset m_fhashsetrequesting sendstartuploadreq updatepartsinfo void c up down client process file status bool b udp packet c safe mem file data c part file file if reqfile file reqfile if reqfile null throw get res string ids err wrongfileid t process file status reqfile null throw get res string ids err wrongfileid t process file status reqfile file uint16 ned2k part count data readu int16 delete m abypartstatus m abypartstatus null bool b parts needed false int i needed 0 if ned2k part count m npartcount reqfile get part count m abypartstatus new uint8 m npartcount memset m abypartstatus 1 m npartcount b parts needed true m bcompletesource true if b udp packet the prefs get debug clientudp level 0 the prefs get debug clienttcp level 0 for uint i 0 i m npartcount i if reqfile is complete uint64 i partsize uint64 i 1 partsize 1 false i needed else if reqfile geted2k part count ned2k part count if the prefs get verbose debug log warning t file name s m strclientfilename debug log warning t file status s dbg get file status ned2k part count data c string str error str error format t process file status wrong part number recv u expected u s ned2k part count reqfile geted2k part count dbg get file info reqfile get file hash m npartcount 0 throw str error m npartcount reqfile get part count m bcompletesource false m abypartstatus new uint8 m npartcount uint done 0 while done m npartcount uint8 toread data readu int8 for uint i 0 i 8 i m abypartstatus done toread i 1 1 0 if m abypartstatus done if reqfile is complete uint64 done partsize uint64 done 1 partsize 1 false b parts needed true i needed done if done m npartcount break if b udp packet the prefs get debug clientudp level 0 the prefs get debug clienttcp level 0 tchar psz new tchar m npartcount 1 for uint i 0 i m npartcount i psz i m abypartstatus i t t psz i t 0 debug t parts u s needed u n m npartcount psz i needed delete psz update displayed info b udp packet reqfile update available parts count note this function is invoked from tcp and udp socket if b udp packet if b parts needed set download state ds noneededparts swap to another file t a4af for nnp file c up down client process file status tcp true false false null true true else if reqfile hashsetneeded if we are using the e mule filerequest packets this is taken care of in the multipacket if socket if the prefs get debug clienttcp level 0 debug send op hashsetrequest this reqfile get file hash packet packet new packet op hashsetrequest 16 md4cpy packet p buffer reqfile get file hash the stats add up data overhead file request packet size socket send packet packet true true set download state ds reqhashset m fhashsetrequesting 1 reqfile hashsetneeded false else assert 0 else send startup load req else if b parts needed set download state ds noneededparts swap to another file t a4af for nnp file c up down client process file status udp true false false null true false else set download state ds onqueue reqfile update parts info cupdownclient processfilestatus budppacket csafememfile cpartfile getresstring ids_err_wrongfileid _t processfilestatus getresstring ids_err_wrongfileid _t processfilestatus ned2kpartcount readuint16 m_abypartstatus m_abypartstatus bpartsneeded ineeded ned2kpartcount m_npartcount getpartcount m_abypartstatus m_npartcount m_abypartstatus m_npartcount bpartsneeded m_bcompletesource budppacket theprefs getdebugclientudplevel theprefs getdebugclienttcplevel m_npartcount iscomplete ineeded geted2kpartcount ned2kpartcount theprefs getverbose debuglogwarning _t filename m_strclientfilename debuglogwarning _t filestatus dbggetfilestatus ned2kpartcount cstring strerror strerror _t processfilestatus ned2kpartcount geted2kpartcount dbggetfileinfo getfilehash m_npartcount strerror m_npartcount getpartcount m_bcompletesource m_abypartstatus m_npartcount m_npartcount readuint8 m_abypartstatus m_abypartstatus iscomplete bpartsneeded ineeded m_npartcount budppacket theprefs getdebugclientudplevel theprefs getdebugclienttcplevel m_npartcount m_npartcount m_abypartstatus _t _t _t _t m_npartcount ineeded updatedisplayedinfo budppacket updateavailablepartscount budppacket bpartsneeded setdownloadstate ds_noneededparts swaptoanotherfile _t cupdownclient processfilestatus emule theprefs getdebugclienttcplevel debugsend op__hashsetrequest getfilehash op_hashsetrequest pbuffer getfilehash thestats addupdataoverheadfilerequest sendpacket setdownloadstate ds_reqhashset m_fhashsetrequesting sendstartuploadreq bpartsneeded setdownloadstate ds_noneededparts swaptoanotherfile _t cupdownclient processfilestatus setdownloadstate ds_onqueue updatepartsinfo void c up down client process hash set const uchar packet uint32 size if m fhashsetrequesting throw c string t unwanted hashset if reqfile md4cmp packet reqfile get file hash check failed file id reqs packet throw get res string ids err wrongfileid t process hash set c safe mem file data packet size if reqfile load hashset from file data true m fhashsetrequesting 0 else reqfile hashsetneeded true throw get res string ids err badhashset send startup load req cupdownclient processhashset m_fhashsetrequesting cstring _t getfilehash checkfailedfileidreqs getresstring ids_err_wrongfileid _t processhashset csafememfile loadhashsetfromfile m_fhashsetrequesting getresstring ids_err_badhashset sendstartuploadreq void c up down client process accept upload m fqueuerankpending 1 if reqfile reqfile is stopped reqfile get status ps ready reqfile get status ps empty set sent cancel transfer 0 if get download state ds onqueue pc todo if remote client does not answer the peer cache query within a timeout automatically fall back to ed2k download if support peer cache client knows peercache protocol the prefs is peer cache download enabled user has enabled peercache downloads the app m ppeercache is cache available we have found our cache and its usable the app m ppeercache is clientpc compatible get version get client soft the client version is accepted by the cache send peer cache file request request made start download else send cancel transfer set download state reqfile null reqfile is stopped ds none ds onqueue cupdownclient processacceptupload m_fqueuerankpending isstopped getstatus ps_ready getstatus ps_empty setsentcanceltransfer getdownloadstate ds_onqueue peercache supportpeercache theprefs ispeercachedownloadenabled theapp m_ppeercache iscacheavailable theapp m_ppeercache isclientpccompatible getversion getclientsoft sendpeercachefilerequest startdownload sendcanceltransfer setdownloadstate isstopped ds_none ds_onqueue bool c up down client add request for another file c part file file for position pos m othernoneeded list get head position pos 0 if m othernoneeded list get next pos file return false for position pos m otherrequests list get head position pos 0 if m otherrequests list get next pos file return false m otherrequests list add tail file file a4a fsrclist add tail this enkeydev ottavio84 a4af return true cupdownclient addrequestforanotherfile cpartfile m_othernoneeded_list getheadposition m_othernoneeded_list getnext m_otherrequests_list getheadposition m_otherrequests_list getnext m_otherrequests_list addtail a4afsrclist addtail void c up down client create block requests int i max blocks assert i max blocks 1 i max blocks 3 if m downloadblocks list is empty uint16 count if i max blocks m pendingblocks list get count count uint16 i max blocks m pendingblocks list get count else count 0 requested block struct toadd new requested block struct count if reqfile get next requested block this toadd count for uint i 0 i count i m downloadblocks list add tail toadd i delete toadd while m pendingblocks list get count i max blocks m downloadblocks list is empty pending block struct pblock new pending block struct pblock block m downloadblocks list remove head m pendingblocks list add tail pblock cupdownclient createblockrequests imaxblocks imaxblocks imaxblocks m_downloadblocks_list isempty imaxblocks m_pendingblocks_list getcount imaxblocks m_pendingblocks_list getcount requested_block_struct requested_block_struct getnextrequestedblock m_downloadblocks_list addtail m_pendingblocks_list getcount imaxblocks m_downloadblocks_list isempty pending_block_struct pending_block_struct m_downloadblocks_list removehead m_pendingblocks_list addtail void c up down client send block requests if the prefs get debug clienttcp level 0 debug send op requestparts this reqfile null reqfile get file hash null m dwlastblockreceived get tick count if reqfile return prevent locking of too many blocks when we are on a slow probably standby trickle slot int block count 3 if is emule client m bycompatibleclient 0 reqfile get file size reqfile get completed size uint64 partsize 4 if there s less than two chunks left request fewer blocks for slow downloads so they don t lock blocks from faster clients only trust e mule clients to be able to handle less blocks than three if get download datarate 600 block count 1 else if get download datarate 1200 block count 2 create block requests block count if m pendingblocks list is empty send cancel transfer set download state ds noneededparts swap to another file t a4af for nnp file c up down client send block requests true false false null true true return bool bi64 offsets false position pos m pendingblocks list get head position for uint32 i 0 i 3 i if pos pending block struct pending m pendingblocks list get next pos assert pending block start offset pending block end offset if pending block start offset 0xffffffff pending block end offset 0xffffffff bi64 offsets true if supports large files assert false send cancel transfer set download state ds error break packet packet if bi64 offsets const int i packet size 16 3 8 3 8 64 packet new packet op requestparts i64 i packet size op emuleprot c safe mem file data const byte packet p buffer i packet size data write hash16 reqfile get file hash pos m pendingblocks list get head position for uint32 i 0 i 3 i if pos pending block struct pending m pendingblocks list get next pos assert pending block start offset pending block end offset assert pending z stream null assert pending total unzipped 0 pending fz stream error 0 pending f recovered 0 data writeu int64 pending block start offset else data writeu int64 0 pos m pendingblocks list get head position for uint32 i 0 i 3 i if pos requested block struct block m pendingblocks list get next pos block uint64 endpos block end offset 1 data writeu int64 endpos if the prefs get debug clienttcp level 0 c string str info str info format t block request u i str info dbg get block info block str info append format t complete s reqfile is complete block start offset block end offset false t yes note t no str info append format t pure gap s reqfile is pure gap block start offset block end offset t yes t no note str info append format t already req s reqfile is already requested block start offset block end offset t yes t no note str info t n debug str info else data writeu int64 0 if the prefs get debug clienttcp level 0 debug t block request u empty n i else const int i packet size 16 3 4 3 4 40 packet new packet op requestparts i packet size c safe mem file data const byte packet p buffer i packet size data write hash16 reqfile get file hash pos m pendingblocks list get head position for uint32 i 0 i 3 i if pos pending block struct pending m pendingblocks list get next pos assert pending block start offset pending block end offset assert pending z stream null assert pending total unzipped 0 pending fz stream error 0 pending f recovered 0 data writeu int32 uint32 pending block start offset else data writeu int32 0 pos m pendingblocks list get head position for uint32 i 0 i 3 i if pos requested block struct block m pendingblocks list get next pos block uint64 endpos block end offset 1 data writeu int32 uint32 endpos if the prefs get debug clienttcp level 0 c string str info str info format t block request u i str info dbg get block info block str info append format t complete s reqfile is complete block start offset block end offset false t yes note t no str info append format t pure gap s reqfile is pure gap block start offset block end offset t yes t no note str info append format t already req s reqfile is already requested block start offset block end offset t yes t no note str info t n debug str info else data writeu int32 0 if the prefs get debug clienttcp level 0 debug t block request u empty n i the stats add up data overhead file request packet size socket send packet packet true true cupdownclient sendblockrequests theprefs getdebugclienttcplevel debugsend op__requestparts getfilehash m_dwlastblockreceived gettickcount blockcount isemuleclient m_bycompatibleclient getfilesize getcompletedsize emule getdownloaddatarate blockcount getdownloaddatarate blockcount createblockrequests blockcount m_pendingblocks_list isempty sendcanceltransfer setdownloadstate ds_noneededparts swaptoanotherfile _t cupdownclient sendblockrequests bi64offsets m_pendingblocks_list getheadposition pending_block_struct m_pendingblocks_list getnext startoffset endoffset startoffset endoffset bi64offsets supportslargefiles sendcanceltransfer setdownloadstate ds_error bi64offsets ipacketsize op_requestparts_i64 ipacketsize op_emuleprot csafememfile pbuffer ipacketsize writehash16 getfilehash m_pendingblocks_list getheadposition pending_block_struct m_pendingblocks_list getnext startoffset endoffset zstream totalunzipped fzstreamerror frecovered writeuint64 startoffset writeuint64 m_pendingblocks_list getheadposition requested_block_struct m_pendingblocks_list getnext endoffset writeuint64 theprefs getdebugclienttcplevel cstring strinfo strinfo _t strinfo dbggetblockinfo strinfo appendformat _t iscomplete startoffset endoffset _t _t strinfo appendformat _t puregap ispuregap startoffset endoffset _t _t strinfo appendformat _t alreadyreq isalreadyrequested startoffset endoffset _t _t strinfo _t strinfo writeuint64 theprefs getdebugclienttcplevel _t ipacketsize op_requestparts ipacketsize csafememfile pbuffer ipacketsize writehash16 getfilehash m_pendingblocks_list getheadposition pending_block_struct m_pendingblocks_list getnext startoffset endoffset zstream totalunzipped fzstreamerror frecovered writeuint32 startoffset writeuint32 m_pendingblocks_list getheadposition requested_block_struct m_pendingblocks_list getnext endoffset writeuint32 theprefs getdebugclienttcplevel cstring strinfo strinfo _t strinfo dbggetblockinfo strinfo appendformat _t iscomplete startoffset endoffset _t _t strinfo appendformat _t puregap ispuregap startoffset endoffset _t _t strinfo appendformat _t alreadyreq isalreadyrequested startoffset endoffset _t _t strinfo _t strinfo writeuint32 theprefs getdebugclienttcplevel _t thestats addupdataoverheadfilerequest sendpacket void c up down client process block packet const uchar packet uint32 size bool packed bool bi64 offsets todo rewrite debugoutput uint32 n dbg start pos uint32 packet 16 if the prefs get debug clienttcp level 1 if packed debug t start u block size u size u s n n dbg start pos uint32 packet 16 4 size 24 dbg get file info packet else debug t start u end u size u s n n dbg start pos uint32 packet 16 4 uint32 packet 16 4 n dbg start pos dbg get file info packet ignore if no data required if get download state ds downloading get download state ds noneededparts trace s invalid download state n function return update stats m dwlastblockreceived get tick count read data from packet c safe mem file data packet size uchar fileid 16 data read hash16 fileid int n header size 16 check that this data is for the correct file if reqfile md4cmp packet reqfile get file hash throw get res string ids err wrongfileid t process block packet find the start end positions and size of this chunk of data uint64 n start pos uint64 n end pos uint32 n block size 0 if bi64 offsets n start pos data readu int64 n header size 8 else n start pos data readu int32 n header size 4 if packed n block size data readu int32 n header size 4 n end pos n start pos size n header size else if bi64 offsets n end pos data readu int64 n header size 8 else n end pos data readu int32 n header size 4 uint32 u transferred file data size size n header size check that packet size matches the declared data size header size 24 if n end pos n start pos size n end pos n start pos n header size throw get res string ids err baddatablock t process block packet khaos extended statistics information based on which client and remote port sent this data the new function adds the bytes to the grand total as well as the given client port b frompf is not relevant to downloaded data it is purely an uploads statistic the prefs add2 session transfer data get client soft get user port false false u transferred file data size false khaos m ndowndataratems u transferred file data size if credits credits add downloaded u transferred file data size getip move end back one should be inclusive n end pos loop through to find the reserved block that this is within for position pos m pendingblocks list get head position pos null position pos last pos pending block struct cur block m pendingblocks list get next pos if cur block block start offset n start pos cur block block end offset n start pos found reserved block if cur block fz stream error if the prefs get verbose add debug log line false t prc blk pkt ignoring u bytes of block starting at u because of errornous zstream state for file s s u transferred file data size n start pos reqfile get file name dbg get client info reqfile remove block from list cur block block start offset cur block block end offset return remember this start pos used to draw part downloading in list m nlastblockoffset n start pos occasionally packets are duplicated no point writing it twice this will be 0 in these cases or the length written otherwise uint32 len written 0 handle differently depending on whether packed or not if packed write to disk will be buffered in part file class len written reqfile write to buffer u transferred file data size packet n header size n start pos n end pos cur block block this else packed assert int size 0 create space to store unzipped data the size is only an initial guess will be resized in unzip if not big enough uint32 len unzipped size 2 don t get too big if len unzipped emblocksize 300 len unzipped emblocksize 300 byte unzipped new byte len unzipped try to unzip the packet int result unzip cur block packet n header size u transferred file data size unzipped len unzipped no block can be uncompressed to 2gb len unzipped is obviously errornous if result z ok int len unzipped 0 if len unzipped 0 write any unzipped data to disk assert int len unzipped 0 use the current start and end positions for the uncompressed data n start pos cur block block start offset cur block total unzipped len unzipped n end pos cur block block start offset cur block total unzipped 1 if n start pos cur block block end offset n end pos cur block block end offset if the prefs get verbose debug log error t prc blk pkt get res string ids err corruptcomprpkg reqfile get file name 666 reqfile remove block from list cur block block start offset cur block block end offset there is no chance to recover from this error else write uncompressed data to file len written reqfile write to buffer u transferred file data size unzipped n start pos n end pos cur block block this else if the prefs get verbose c string str zip error if cur block z stream cur block z stream msg str zip error format t hs cur block z stream msg if result z ok int len unzipped 0 assert 0 str zip error append format t z ok len unzipped d len unzipped debug log error t prc blk pkt get res string ids err corruptcomprpkg str zip error reqfile get file name result reqfile remove block from list cur block block start offset cur block block end offset if we had an zstream error there is no chance that we could recover from it nor that we could use the current zstream which is in error state any longer if cur block z stream inflate end cur block z stream delete cur block z stream cur block z stream null although we can t further use the current zstream there is no need to disconnect the sending client because the next zstream a series of 10k blocks which build a 180k block could be valid again just ignore all further blocks for the current zstream cur block fz stream error 1 cur block total unzipped 0 delete unzipped these checks only need to be done if any data was written if len written 0 m ntransferreddown u transferred file data size set transferred down mini if finished reserved block if n end pos cur block block end offset reqfile remove block from list cur block block start offset cur block block end offset delete cur block block not always allocated if cur block z stream inflate end cur block z stream delete cur block z stream delete cur block m pendingblocks list remove at pos last request next block if the prefs get debug clienttcp level 0 debug send more block requests this send block requests stop looping and exit method return trace s dropping packet n function cupdownclient processblockpacket bi64offsets ndbgstartpos theprefs getdebugclienttcplevel _t blocksize ndbgstartpos dbggetfileinfo _t ndbgstartpos ndbgstartpos dbggetfileinfo getdownloadstate ds_downloading getdownloadstate ds_noneededparts __function__ m_dwlastblockreceived gettickcount csafememfile readhash16 nheadersize getfilehash getresstring ids_err_wrongfileid _t processblockpacket nstartpos nendpos nblocksize bi64offsets nstartpos readuint64 nheadersize nstartpos readuint32 nheadersize nblocksize readuint32 nheadersize nendpos nstartpos nheadersize bi64offsets nendpos readuint64 nheadersize nendpos readuint32 nheadersize utransferredfiledatasize nheadersize nendpos nstartpos nendpos nstartpos nheadersize getresstring ids_err_baddatablock _t processblockpacket bfrompf theprefs add2sessiontransferdata getclientsoft getuserport utransferredfiledatasize m_ndowndataratems utransferredfiledatasize adddownloaded utransferredfiledatasize nendpos m_pendingblocks_list getheadposition poslast pending_block_struct cur_block m_pendingblocks_list getnext cur_block startoffset nstartpos cur_block endoffset nstartpos cur_block fzstreamerror theprefs getverbose adddebuglogline _t prcblkpkt utransferredfiledatasize nstartpos getfilename dbggetclientinfo removeblockfromlist cur_block startoffset cur_block endoffset m_nlastblockoffset nstartpos lenwritten lenwritten writetobuffer utransferredfiledatasize nheadersize nstartpos nendpos cur_block lenunzipped lenunzipped lenunzipped lenunzipped cur_block nheadersize utransferredfiledatasize lenunzipped lenunzipped z_ok lenunzipped lenunzipped lenunzipped nstartpos cur_block startoffset cur_block totalunzipped lenunzipped nendpos cur_block startoffset cur_block totalunzipped nstartpos cur_block endoffset nendpos cur_block endoffset theprefs getverbose debuglogerror _t prcblkpkt getresstring ids_err_corruptcomprpkg getfilename removeblockfromlist cur_block startoffset cur_block endoffset lenwritten writetobuffer utransferredfiledatasize nstartpos nendpos cur_block theprefs getverbose cstring strziperror cur_block zstream cur_block zstream strziperror _t cur_block zstream z_ok lenunzipped strziperror appendformat _t z_ok lenunzipped lenunzipped debuglogerror _t prcblkpkt getresstring ids_err_corruptcomprpkg strziperror getfilename removeblockfromlist cur_block startoffset cur_block endoffset cur_block zstream inflateend cur_block zstream cur_block zstream cur_block zstream cur_block fzstreamerror cur_block totalunzipped lenwritten m_ntransferreddown utransferredfiledatasize settransferreddownmini nendpos cur_block endoffset removeblockfromlist cur_block startoffset cur_block endoffset cur_block cur_block zstream inflateend cur_block zstream cur_block zstream cur_block m_pendingblocks_list removeat poslast theprefs getdebugclienttcplevel debugsend sendblockrequests __function__ void c up down client clear download block requests for position pos m downloadblocks list get head position pos 0 requested block struct cur block m downloadblocks list get next pos if reqfile reqfile remove block from list cur block start offset cur block end offset delete cur block m downloadblocks list remove all for position pos m pendingblocks list get head position pos 0 pending block struct pending m pendingblocks list get next pos if reqfile reqfile remove block from list pending block start offset pending block end offset delete pending block not always allocated if pending z stream inflate end pending z stream delete pending z stream delete pending m pendingblocks list remove all cupdownclient cleardownloadblockrequests m_downloadblocks_list getheadposition requested_block_struct cur_block m_downloadblocks_list getnext removeblockfromlist cur_block startoffset cur_block endoffset cur_block m_downloadblocks_list removeall m_pendingblocks_list getheadposition pending_block_struct m_pendingblocks_list getnext removeblockfromlist startoffset endoffset zstream inflateend zstream zstream m_pendingblocks_list removeall uint32 c up down client calculate download rate patch by bad wolf accurate datarate calculation transferred data newitem m ndowndataratems get tick count m avarageddr list add tail newitem m nsumforavgdowndatarate m ndowndataratems m ndowndataratems 0 while m avarageddr list get count 500 m nsumforavgdowndatarate m avarageddr list remove head datalen if m avarageddr list get count 1 dword dw duration m avarageddr list get tail timestamp m avarageddr list get head timestamp if dw duration m ndowndatarate uint 1000u ulonglong m nsumforavgdowndatarate dw duration else m ndowndatarate 0 end patch by bad wolf m cshowdr if m cshowdr 30 m cshowdr 0 update displayed info return m ndowndatarate cupdownclient calculatedownloadrate badwolf transferreddata m_ndowndataratems gettickcount m_avarageddr_list addtail m_nsumforavgdowndatarate m_ndowndataratems m_ndowndataratems m_avarageddr_list getcount m_nsumforavgdowndatarate m_avarageddr_list removehead m_avarageddr_list getcount dwduration m_avarageddr_list gettail m_avarageddr_list gethead dwduration m_ndowndatarate m_nsumforavgdowndatarate dwduration m_ndowndatarate badwolf m_cshowdr m_cshowdr m_cshowdr updatedisplayedinfo m_ndowndatarate uint16 c up down client get available part count const uint result 0 for uint i 0 i m npartcount i if is part available i result return uint16 result cupdownclient getavailablepartcount m_npartcount ispartavailable bool c up down client swap to another file lpctstr reason bool b ignore no needed bool ignore suspensions bool b remove completely c part file to file bool allow same bool is about to ask bool debug bool print debug debug the prefs get loga4af if print debug add debug log line dlp low false t ooo debug switching source s remove s b ignore no needed s allow same s reason s dbg get client info b remove completely t yes t no b ignore no needed t yes t no allow same t yes t no reason if b remove completely allow same the prefs geta4af save cpu only swap if we can t keep the old source if print debug add debug log line dlp low false t ooo debug return false since prefs setting to save cpu is enabled return false bool do agressive swapping b remove completely allow same is about to ask if print debug add debug log line dlp low false t ooo debug do agressive swapping s do agressive swapping t true t false if b remove completely ignore suspensions allow same get time until reask reqfile do agressive swapping true false 0 get download state ds noneededparts m otherrequests list is empty if print debug add debug log line dlp low false t ooo debug return false due to not reached reask time get time until reask 0 return false if b remove completely allow same m otherrequests list is empty b ignore no needed m othernoneeded list is empty no file to swap too and it s ok to keep it if print debug add debug log line dlp low false t ooo debug return false due to no file to swap too and it s ok to keep it return false if b remove completely get download state ds onqueue get download state ds noneededparts get download state ds toomanyconns get download state ds remotequeuefull get download state ds connected if print debug add debug log line dlp low false t ooo debug return false due to wrong state return false c part file swap to null c part file cur file null position finalpos null c typed ptr list c ptr list c part file used list null if allow same b remove completely swap to reqfile if print debug add debug log line dlp verylow false t ooo debug allow same file s source req s reqfile get file name is source request allowed reqfile t true t false bool swap to isnnp swap to null swap to reqfile get download state ds noneededparts c part file skipped due to source exchange null bool skipped isnnp false if m otherrequests list is empty if print debug add debug log line dlp verylow false t ooo debug m otherrequests list for position pos m otherrequests list get head position pos 0 m otherrequests list get next pos cur file m otherrequests list get at pos if print debug add debug log line dlp verylow false t ooo debug checking file s soure req s cur file get file name is source request allowed cur file t true t false if b remove completely ignore suspensions allow same is swap suspended cur file do agressive swapping false if print debug add debug log line dlp verylow false t ooo debug continue due to is swap suspended file true continue if cur file reqfile the app downloadqueue is part file cur file cur file is stopped cur file get status false ps ready cur file get status false ps empty if print debug add debug log line dlp verylow false t ooo debug it s a partfile not stopped etc if to file null if cur file to file if print debug add debug log line dlp verylow false t ooo debug found to file swap to cur file swap to isnnp false used list m otherrequests list finalpos pos break else bool was skipped due to source exchange false if swap to right file swap to cur file ignore suspensions swap to isnnp false was skipped due to source exchange do agressive swapping debug if print debug add debug log line dlp verylow false t ooo debug swapping to file s cur file get file name if swap to was skipped due to source exchange if debug the prefs get loga4af add debug log line dlp verylow false t ooo debug swapped due to source exchange possibility bool discard skipped false if swap to right file skipped due to source exchange swap to ignore suspensions skipped isnnp swap to isnnp discard skipped do agressive swapping debug skipped due to source exchange swap to skipped isnnp skipped isnnp true swap to reqfile get download state ds noneededparts if print debug add debug log line dlp verylow false t ooo debug skipped file was better than last skipped file swap to cur file swap to isnnp false used list m otherrequests list finalpos pos else if print debug add debug log line dlp verylow false t ooo debug keeping file s swap to get file name if was skipped due to source exchange if print debug add debug log line dlp verylow false t ooo debug kept the file due to source exchange possibility bool discard skipped false if swap to right file skipped due to source exchange cur file ignore suspensions skipped isnnp false discard skipped do agressive swapping debug skipped due to source exchange cur file skipped isnnp false if print debug add debug log line dlp verylow false t ooo debug skipped file was better than last skipped file if swap to swap to reqfile get download state ds noneededparts b ignore no needed if print debug add debug log line dlp verylow false t ooo debug m othernoneeded list for position pos m othernoneeded list get head position pos 0 m othernoneeded list get next pos cur file m othernoneeded list get at pos if print debug add debug log line dlp verylow false t ooo debug checking file s cur file get file name if b remove completely ignore suspensions allow same is swap suspended cur file do agressive swapping true if print debug add debug log line dlp verylow false t ooo debug continue due to is swap suspended file true continue if cur file reqfile the app downloadqueue is part file cur file cur file is stopped cur file get status false ps ready cur file get status false ps empty if print debug add debug log line dlp verylow false t ooo debug it s a partfile not stopped etc if to file null if cur file to file if print debug add debug log line dlp verylow false t ooo debug found to file swap to cur file used list m othernoneeded list finalpos pos break else bool was skipped due to source exchange false if swap to right file swap to cur file ignore suspensions swap to isnnp true was skipped due to source exchange do agressive swapping debug if print debug add debug log line dlp verylow false t ooo debug swapping to file s cur file get file name if swap to was skipped due to source exchange if print debug add debug log line dlp verylow false t ooo debug swapped due to source exchange possibility bool discard skipped false if swap to right file skipped due to source exchange swap to ignore suspensions skipped isnnp swap to isnnp discard skipped do agressive swapping debug skipped due to source exchange swap to skipped isnnp skipped isnnp true swap to reqfile get download state ds noneededparts if print debug add debug log line dlp verylow false t ooo debug skipped file was better than last skipped file swap to cur file swap to isnnp true used list m othernoneeded list finalpos pos cupdownclient swaptoanotherfile bignorenoneeded ignoresuspensions bremovecompletely cpartfile tofile allowsame isabouttoask printdebug theprefs getloga4af printdebug adddebuglogline dlp_low _t bignorenoneeded allowsame dbggetclientinfo bremovecompletely _t _t bignorenoneeded _t _t allowsame _t _t bremovecompletely allowsame theprefs geta4afsavecpu printdebug adddebuglogline dlp_low _t doagressiveswapping bremovecompletely allowsame isabouttoask printdebug adddebuglogline dlp_low _t doagressiveswapping doagressiveswapping _t _t bremovecompletely ignoresuspensions allowsame gettimeuntilreask doagressiveswapping getdownloadstate ds_noneededparts m_otherrequests_list isempty printdebug adddebuglogline dlp_low _t gettimeuntilreask bremovecompletely allowsame m_otherrequests_list isempty bignorenoneeded m_othernoneeded_list isempty printdebug adddebuglogline dlp_low _t bremovecompletely getdownloadstate ds_onqueue getdownloadstate ds_noneededparts getdownloadstate ds_toomanyconns getdownloadstate ds_remotequeuefull getdownloadstate ds_connected printdebug adddebuglogline dlp_low _t cpartfile swapto cpartfile cur_file ctypedptrlist cptrlist cpartfile usedlist allowsame bremovecompletely swapto printdebug adddebuglogline dlp_verylow _t allowsame sourcereq getfilename issourcerequestallowed _t _t swaptoisnnp swapto swapto getdownloadstate ds_noneededparts cpartfile skippedduetosourceexchange skippedisnnp m_otherrequests_list isempty printdebug adddebuglogline dlp_verylow _t m_otherrequests_list m_otherrequests_list getheadposition m_otherrequests_list getnext cur_file m_otherrequests_list getat printdebug adddebuglogline dlp_verylow _t sourereq cur_file getfilename issourcerequestallowed cur_file _t _t bremovecompletely ignoresuspensions allowsame isswapsuspended cur_file doagressiveswapping printdebug adddebuglogline dlp_verylow _t isswapsuspended cur_file theapp ispartfile cur_file cur_file isstopped cur_file getstatus ps_ready cur_file getstatus ps_empty printdebug adddebuglogline dlp_verylow _t tofile cur_file tofile printdebug adddebuglogline dlp_verylow _t tofile swapto cur_file swaptoisnnp usedlist m_otherrequests_list wasskippedduetosourceexchange swaptorightfile swapto cur_file ignoresuspensions swaptoisnnp wasskippedduetosourceexchange doagressiveswapping printdebug adddebuglogline dlp_verylow _t cur_file getfilename swapto wasskippedduetosourceexchange theprefs getloga4af adddebuglogline dlp_verylow _t discardskipped swaptorightfile skippedduetosourceexchange swapto ignoresuspensions skippedisnnp swaptoisnnp discardskipped doagressiveswapping skippedduetosourceexchange swapto skippedisnnp skippedisnnp swapto getdownloadstate ds_noneededparts printdebug adddebuglogline dlp_verylow _t swapto cur_file swaptoisnnp usedlist m_otherrequests_list printdebug adddebuglogline dlp_verylow _t swapto getfilename wasskippedduetosourceexchange printdebug adddebuglogline dlp_verylow _t discardskipped swaptorightfile skippedduetosourceexchange cur_file ignoresuspensions skippedisnnp discardskipped doagressiveswapping skippedduetosourceexchange cur_file skippedisnnp printdebug adddebuglogline dlp_verylow _t swapto swapto getdownloadstate ds_noneededparts bignorenoneeded printdebug adddebuglogline dlp_verylow _t m_othernoneeded_list m_othernoneeded_list getheadposition m_othernoneeded_list getnext cur_file m_othernoneeded_list getat printdebug adddebuglogline dlp_verylow _t cur_file getfilename bremovecompletely ignoresuspensions allowsame isswapsuspended cur_file doagressiveswapping printdebug adddebuglogline dlp_verylow _t isswapsuspended cur_file theapp ispartfile cur_file cur_file isstopped cur_file getstatus ps_ready cur_file getstatus ps_empty printdebug adddebuglogline dlp_verylow _t tofile cur_file tofile printdebug adddebuglogline dlp_verylow _t tofile swapto cur_file usedlist m_othernoneeded_list wasskippedduetosourceexchange swaptorightfile swapto cur_file ignoresuspensions swaptoisnnp wasskippedduetosourceexchange doagressiveswapping printdebug adddebuglogline dlp_verylow _t cur_file getfilename swapto wasskippedduetosourceexchange printdebug adddebuglogline dlp_verylow _t discardskipped swaptorightfile skippedduetosourceexchange swapto ignoresuspensions skippedisnnp swaptoisnnp discardskipped doagressiveswapping skippedduetosourceexchange swapto skippedisnnp skippedisnnp swapto getdownloadstate ds_noneededparts printdebug adddebuglogline dlp_verylow _t swapto cur_file swaptoisnnp usedlist m_othernoneeded_list void c up down client dont swap to const c part file file dword dw now get tick count for position pos m dontswap list get head position pos 0 m dontswap list get next pos if m dontswap list get at pos file file m dontswap list get at pos timestamp dw now return part file stamp newfs file dw now m dontswap list add head newfs cupdownclient dontswapto cpartfile dwnow gettickcount m_dontswap_list getheadposition m_dontswap_list getnext m_dontswap_list getat m_dontswap_list getat dwnow partfilestamp dwnow m_dontswap_list addhead bool c up down client is swap suspended const c part file file const bool allow short reask time const bool file isnnp if file reqfile return false don t swap if we have reasked this client too recently if get time until reask file allow short reask time true file isnnp 0 return true if m dontswap list get count 0 return false for position pos m dontswap list get head position pos 0 m dontswap list get count 0 m dontswap list get next pos if m dontswap list get at pos file file if get tick count m dontswap list get at pos timestamp purgesourceswapstop m dontswap list remove at pos return false else return true else if m dontswap list get at pos file null in which cases should this happen m dontswap list remove at pos return false cupdownclient isswapsuspended cpartfile allowshortreasktime fileisnnp gettimeuntilreask allowshortreasktime fileisnnp m_dontswap_list getcount m_dontswap_list getheadposition m_dontswap_list getcount m_dontswap_list getnext m_dontswap_list getat gettickcount m_dontswap_list getat m_dontswap_list removeat m_dontswap_list getat m_dontswap_list removeat uint32 c up down client get time until reask const return get time until reask reqfile cupdownclient gettimeuntilreask gettimeuntilreask uint32 c up down client get time until reask const c part file file const return get time until reask file false cupdownclient gettimeuntilreask cpartfile gettimeuntilreask uint32 c up down client get time until reask const c part file file const bool allow short reask time const bool use givennnp const bool givennnp const dword last asked time tick get last asked time file if last asked time tick 0 dword tick get tick count dword reask time if allow short reask time file reqfile get download state ds none reask time min requesttime else if use givennnp givennnp file reqfile get download state ds noneededparts file reqfile is in no needed list file reask time filereasktime 2 else reask time filereasktime if tick last asked time tick reask time return reask time tick last asked time tick else return 0 else return 0 cupdownclient gettimeuntilreask cpartfile allowshortreasktime usegivennnp lastaskedtimetick getlastaskedtime lastaskedtimetick gettickcount reasktime allowshortreasktime getdownloadstate ds_none reasktime min_requesttime usegivennnp getdownloadstate ds_noneededparts isinnoneededlist reasktime reasktime lastaskedtimetick reasktime reasktime lastaskedtimetick void c up down client udp reaskack uint16 n newqr m budppending false set remote queue rank n newqr true set last asked time cupdownclient udpreaskack nnewqr m_budppending setremotequeuerank nnewqr setlastaskedtime void c up down client udp reaskfnf m budppending false if get download state ds downloading avoid premature deletion of this client if the prefs get verbose add debug log line dlp low false t udp fnf answer s s dbg get client info dbg get file info reqfile reqfile get file hash null if reqfile reqfile m deadsourcelist add dead source this switch get download state case ds onqueue case ds noneededparts dont swap to reqfile if swap to another file t source says it doesn t have the file c up down client udp reaskfnf true true true null false false break fall through default the app downloadqueue remove source this if socket if disconnected t udp reaskfnf socket null delete this else if the prefs get verbose debug log warning t udp fnf answer s did not remove client because of current download state get user name cupdownclient udpreaskfnf m_budppending getdownloadstate ds_downloading theprefs getverbose adddebuglogline dlp_low _t dbggetclientinfo dbggetfileinfo getfilehash m_deadsourcelist adddeadsource getdownloadstate ds_onqueue ds_noneededparts dontswapto swaptoanotherfile _t cupdownclient udpreaskfnf theapp removesource _t udpreaskfnf theprefs getverbose debuglogwarning _t getusername void c up down client udp reask for download assert reqfile if reqfile m budppending return todo this should be changed to determine if the last 4 udp packets failed not the total one if m ntotaludppackets 3 float m nfailedudppackets m ntotaludppackets 3 return if getudp port 0 getudp version 0 the prefs getudp port 0 the app is firewalled socket socket is connected the prefs get proxy settings use proxy if has lowid don t use udp to ask for sources if is source request allowed return if swap to another file t a4af check before op reaskfileping c up down client udp reask for download true false false null true true return we swapped so need to go to tcp m budppending true c safe mem file data 128 data write hash16 reqfile get file hash if getudp version 3 if reqfile is part file c part file reqfile write part status data else data writeu int16 0 if getudp version 2 data writeu int16 reqfile m ncompletesourcescount if the prefs get debug clientudp level 0 debug send op reaskfileping this reqfile get file hash packet response new packet data op emuleprot response opcode op reaskfileping the stats add up data overhead file request response size the app downloadqueue addudp file reasks the app clientudp send packet response getip getudp port m ntotaludppackets else if has lowid get buddyip get buddy port has valid buddyid m budppending true c safe mem file data 128 data write hash16 get buddyid data write hash16 reqfile get file hash if getudp version 3 if reqfile is part file c part file reqfile write part status data else data writeu int16 0 if getudp version 2 data writeu int16 reqfile m ncompletesourcescount if the prefs get debug clientudp level 0 debug send op reaskcallbackudp this reqfile get file hash packet response new packet data op emuleprot response opcode op reaskcallbackudp the stats add up data overhead file request response size the app downloadqueue addudp file reasks the app clientudp send packet response get buddyip get buddy port m ntotaludppackets cupdownclient udpreaskfordownload m_budppending m_ntotaludppackets m_nfailedudppackets m_ntotaludppackets getudpport getudpversion theprefs getudpport theapp isfirewalled isconnected theprefs getproxysettings useproxy haslowid issourcerequestallowed swaptoanotherfile _t op__reaskfileping cupdownclient udpreaskfordownload m_budppending csafememfile writehash16 getfilehash getudpversion ispartfile cpartfile writepartstatus writeuint16 getudpversion writeuint16 m_ncompletesourcescount theprefs getdebugclientudplevel debugsend op__reaskfileping getfilehash op_emuleprot op_reaskfileping thestats addupdataoverheadfilerequest theapp addudpfilereasks theapp sendpacket getudpport m_ntotaludppackets haslowid getbuddyip getbuddyport hasvalidbuddyid m_budppending csafememfile writehash16 getbuddyid writehash16 getfilehash getudpversion ispartfile cpartfile writepartstatus writeuint16 getudpversion writeuint16 m_ncompletesourcescount theprefs getdebugclientudplevel debugsend op__reaskcallbackudp getfilehash op_emuleprot op_reaskcallbackudp thestats addupdataoverheadfilerequest theapp addudpfilereasks theapp sendpacket getbuddyip getbuddyport m_ntotaludppackets bool c up down client is source request allowed const return is source request allowed reqfile cupdownclient issourcerequestallowed issourcerequestallowed bool c up down client is source request allowed c part file partfile bool source exchange check const dword dw tick count get tick count connection latency unsigned int n time passed client dw tick count get last src answer time unsigned int n time passed file dw tick count partfile get last answered time bool b never asked before get last asked for sources 0 uint u sources partfile get source count uint u valid sources partfile get valid sources count if partfile reqfile u sources u valid sources uint u req valid sources reqfile get valid sources count return if client has the correct extended protocol ext protocol available get source exchange version 1 and if we need more sources reqfile get max source per file soft u sources and if source is not complete and file is very rare m bcompletesource b never asked before n time passed client sourceclientreasks u sources rare file 5 source exchange check partfile reqfile u valid sources u req valid sources u req valid sources 3 source is not complete and file is rare m bcompletesource b never asked before n time passed client sourceclientreasks u sources rare file source exchange check partfile reqfile u sources rare file 2 u valid sources n time passed file sourceclientreaskf source exchange check partfile reqfile u valid sources sourceclientreasks sourceclientreaskf u valid sources u req valid sources or if file is not rare b never asked before n time passed client unsigned sourceclientreasks mincommonpenalty n time passed file unsigned sourceclientreaskf mincommonpenalty source exchange check partfile reqfile u valid sources sourceclientreasks sourceclientreaskf u valid sources u req valid sources cupdownclient issourcerequestallowed cpartfile sourceexchangecheck dwtickcount gettickcount connection_latency ntimepassedclient dwtickcount getlastsrcanswertime ntimepassedfile dwtickcount getlastansweredtime bneveraskedbefore getlastaskedforsources usources getsourcecount uvalidsources getvalidsourcescount usources uvalidsources ureqvalidsources getvalidsourcescount extprotocolavailable getsourceexchangeversion getmaxsourceperfilesoft usources m_bcompletesource bneveraskedbefore ntimepassedclient usources rare_file sourceexchangecheck uvalidsources ureqvalidsources ureqvalidsources m_bcompletesource bneveraskedbefore ntimepassedclient usources rare_file sourceexchangecheck usources rare_file uvalidsources ntimepassedfile sourceexchangecheck uvalidsources uvalidsources ureqvalidsources bneveraskedbefore ntimepassedclient ntimepassedfile sourceexchangecheck uvalidsources uvalidsources ureqvalidsources bool c up down client is valid source const bool valid false switch get download state case ds downloading case ds onqueue case ds connected case ds noneededparts case ds remotequeuefull case ds reqhashset valid is ed2k client return valid cupdownclient isvalidsource getdownloadstate ds_downloading ds_onqueue ds_connected ds_noneededparts ds_remotequeuefull ds_reqhashset ised2kclient void set down start time m dwdownstarttime get tick count uint32 get down time difference boolean clear true uint32 my time m dwdownstarttime if clear m dwdownstarttime 0 return get tick count my time setdownstarttime m_dwdownstarttime gettickcount getdowntimedifference mytime m_dwdownstarttime m_dwdownstarttime gettickcount mytime int c up down client unzip pending block struct block const byte zipped uint32 len zipped byte unzipped uint32 len unzipped int i recursion define trace unzip trace trace unzip unzip zipd 6u unzd 6u rcrs d len zipped len unzipped i recursion int err z data error try save some typing z stream zs block z stream is this the first time this block has been unzipped if zs null create stream block z stream new z stream zs block z stream initialise stream values zs zalloc alloc func 0 zs zfree free func 0 zs opaque voidpf 0 set output data streams do this here to avoid overwriting on recursive calls zs next out unzipped zs avail out len unzipped initialise the z stream err inflate init zs if err z ok trace unzip error new stream failed d n err return err assert block total unzipped 0 use whatever input is provided zs next in const cast bytef zipped zs avail in len zipped only set the output if not being called recursively if i recursion 0 zs next out unzipped zs avail out len unzipped try to unzip the data trace unzip inflate ain 6u tin 6u aout 6u tout 6u zs avail in zs total in zs avail out zs total out err inflate zs z sync flush is zip finished reading all currently available input and writing all generated output if err z stream end finish up err inflate end zs if err z ok trace unzip error end stream failed d n err return err trace unzip z stream end n got a good result set the size to the amount unzipped in this call including all recursive calls len unzipped zs total out block total unzipped block total unzipped zs total out else if err z ok zs avail out 0 zs avail in 0 output array was not big enough call recursively until there is enough space trace unzip output array not big enough ain u n zs avail in what size should we try next uint32 new length len unzipped 2 if new length 0 new length len zipped 2 copy any data that was successfully unzipped to new array byte temp new byte new length assert zs total out block total unzipped new length memcpy temp unzipped zs total out block total unzipped delete unzipped unzipped temp len unzipped new length position stream output to correct place in new array zs next out unzipped zs total out block total unzipped zs avail out len unzipped zs total out block total unzipped try again err unzip block zs next in zs avail in unzipped len unzipped i recursion 1 else if err z ok zs avail in 0 trace unzip all input processed n all available input has been processed everything ok set the size to the amount unzipped in this call including all recursive calls len unzipped zs total out block total unzipped block total unzipped zs total out else should not get here unless input data is corrupt if the prefs get verbose c string str zip error if zs msg str zip error format t d hs err zs msg else if err z ok str zip error format t d hs err z error err trace unzip error s n str zip error debug log error t unexpected zip error s in file s str zip error reqfile reqfile get file name null if err z ok len unzipped 0 catch if the prefs get verbose debug log error t unknown exception in hs file s function reqfile reqfile get file name null err z data error assert 0 return err cupdownclient pending_block_struct lenzipped lenunzipped irecursion trace_unzip trace_unzip lenzipped lenunzipped irecursion z_data_error z_stream zstream zstream z_stream zstream alloc_func free_func next_out avail_out lenunzipped z_stream inflateinit z_ok trace_unzip totalunzipped next_in const_cast avail_in lenzipped irecursion next_out avail_out lenunzipped trace_unzip avail_in total_in avail_out total_out z_sync_flush z_stream_end inflateend z_ok trace_unzip trace_unzip z_stream_end lenunzipped total_out totalunzipped totalunzipped total_out z_ok avail_out avail_in trace_unzip avail_in newlength lenunzipped newlength newlength lenzipped newlength total_out totalunzipped newlength total_out totalunzipped lenunzipped newlength next_out total_out totalunzipped avail_out lenunzipped total_out totalunzipped next_in avail_in lenunzipped irecursion z_ok avail_in trace_unzip lenunzipped total_out totalunzipped totalunzipped total_out theprefs getverbose cstring strziperror strziperror _t z_ok strziperror _t zerror trace_unzip strziperror debuglogerror _t strziperror getfilename z_ok lenunzipped theprefs getverbose debuglogerror _t __function__ getfilename z_data_error void c up down client update displayed info bool force ifdef debug force true endif dword cur tick get tick count if force cur tick m lastrefresheddldisplay minwait before dldisplay windowupdate m random update wait the app emuledlg transferwnd downloadlistctrl update item this the app emuledlg transferwnd clientlistctrl refresh client this the app emuledlg transferwnd downloadclientsctrl refresh client this m lastrefresheddldisplay cur tick cupdownclient updatedisplayedinfo _debug curtick gettickcount curtick m_lastrefresheddldisplay minwait_before_dldisplay_windowupdate m_random_update_wait theapp updateitem theapp refreshclient theapp refreshclient m_lastrefresheddldisplay curtick void c up down client set request file c part file p req file if p req file reqfile reqfile null reset file status info reqfile p req file cupdownclient setrequestfile cpartfile preqfile preqfile resetfilestatusinfo preqfile void c up down client set req fileaich hash caich hash val if m preqfileaichhash null m preqfileaichhash val delete m preqfileaichhash m preqfileaichhash val cupdownclient setreqfileaichhash caichhash m_preqfileaichhash m_preqfileaichhash m_preqfileaichhash m_preqfileaichhash void c up down client sendaich request c part file p for file uint16 n part caich requested data request request m npart n part request m pclient this request m ppartfile p for file caich hash set m lirequesteddata add tail request m faichrequested true c safe mem file data data write hash16 p for file get file hash data writeu int16 n part p for file getaich hashset get master hash write data packet packet new packet data op emuleprot op aichrequest if the prefs get debug clienttcp level 0 debug send op aichrequest this uchar packet p buffer the stats add up data overhead file request packet size safe send packet packet cupdownclient sendaichrequest cpartfile pforfile npart caichrequesteddata m_npart npart m_pclient m_ppartfile pforfile caichhashset m_lirequesteddata addtail m_faichrequested csafememfile writehash16 pforfile getfilehash writeuint16 npart pforfile getaichhashset getmasterhash op_emuleprot op_aichrequest theprefs getdebugclienttcplevel debugsend op__aichrequest pbuffer thestats addupdataoverheadfilerequest safesendpacket void c up down client processaich answer const uchar packet uint size if m faichrequested false throw c string t received unrequested aich packet m faichrequested false c safe mem file data packet size if size 16 caich hash set clientaich request failed this return uchar aby hash 16 data read hash16 aby hash c part file p part file the app downloadqueue get file byid aby hash caich requested data request caich hash set getaich req details this uint16 n part data readu int16 if p part file null request m ppartfile p part file request m pclient this n part request m npart caich hash ah master hash data if p part file getaich hashset get status aich trusted p part file getaich hashset get status aich verified ah master hash p part file getaich hashset get master hash if p part file getaich hashset read recovery data uint64 request m npart partsize data finally all checks passed everythings seem to be fine add debug log line dlp default false t aich packet answer succeeded to read and validate received recoverydata caich hash set remove clientaich request this p part file aich recovery data available request m npart return else add debug log line dlp default false t aich packet answer succeeded to read and validate received recoverydata else add debug log line dlp high false t aich packet answer masterhash differs from packethash or hashset has no trusted masterhash else add debug log line dlp high false t aich packet answer requested values differ from values in packet caich hash set clientaich request failed this cupdownclient processaichanswer m_faichrequested cstring _t m_faichrequested csafememfile caichhashset clientaichrequestfailed abyhash readhash16 abyhash cpartfile ppartfile theapp getfilebyid abyhash caichrequesteddata caichhashset getaichreqdetails npart readuint16 ppartfile m_ppartfile ppartfile m_pclient npart m_npart caichhash ahmasterhash ppartfile getaichhashset getstatus aich_trusted ppartfile getaichhashset getstatus aich_verified ahmasterhash ppartfile getaichhashset getmasterhash ppartfile getaichhashset readrecoverydata m_npart adddebuglogline dlp_default _t caichhashset removeclientaichrequest ppartfile aichrecoverydataavailable m_npart adddebuglogline dlp_default _t adddebuglogline dlp_high _t adddebuglogline dlp_high _t caichhashset clientaichrequestfailed void c up down client processaich request const uchar packet uint size if size uint 16 2 caich hash get hash size throw c string t received aich request packet with wrong size c safe mem file data packet size uchar aby hash 16 data read hash16 aby hash uint16 n part data readu int16 caich hash ah master hash data c known file p known file the app sharedfiles get file byid aby hash if p known file null if p known file getaich hashset get status aich hashsetcomplete p known file getaich hashset has valid master hash p known file getaich hashset get master hash ah master hash p known file get part count n part p known file get file size uint64 emblocksize uint64 p known file get file size partsize uint64 n part emblocksize c safe mem file file response file response write hash16 p known file get file hash file response writeu int16 n part p known file getaich hashset get master hash write file response if p known file getaich hashset create part recovery data uint64 n part partsize file response add debug log line dlp high false t aich packet request sucessfully created and send recoverydata for s to s p known file get file name dbg get client info if the prefs get debug clienttcp level 0 debug send op aichanswer this p known file get file hash packet pack answer new packet file response op emuleprot op aichanswer the stats add up data overhead file request pack answer size safe send packet pack answer return else add debug log line dlp high false t aich packet request failed to create recoverydata for s to s p known file get file name dbg get client info else add debug log line dlp high false t aich packet request failed to create ecoverydata hashset not ready or requested hash differs from masterhash for s to s p known file get file name dbg get client info else add debug log line dlp high false t aich packet request failed to find requested shared file s dbg get client info if the prefs get debug clienttcp level 0 debug send op aichanswer this aby hash packet pack answer new packet op aichanswer 16 op emuleprot md4cpy pack answer p buffer aby hash the stats add up data overhead file request pack answer size safe send packet pack answer cupdownclient processaichrequest caichhash gethashsize cstring _t csafememfile abyhash readhash16 abyhash npart readuint16 caichhash ahmasterhash cknownfile pknownfile theapp getfilebyid abyhash pknownfile pknownfile getaichhashset getstatus aich_hashsetcomplete pknownfile getaichhashset hasvalidmasterhash pknownfile getaichhashset getmasterhash ahmasterhash pknownfile getpartcount npart pknownfile getfilesize pknownfile getfilesize npart csafememfile fileresponse fileresponse writehash16 pknownfile getfilehash fileresponse writeuint16 npart pknownfile getaichhashset getmasterhash fileresponse pknownfile getaichhashset createpartrecoverydata npart fileresponse adddebuglogline dlp_high _t pknownfile getfilename dbggetclientinfo theprefs getdebugclienttcplevel debugsend op__aichanswer pknownfile getfilehash packanswer fileresponse op_emuleprot op_aichanswer thestats addupdataoverheadfilerequest packanswer safesendpacket packanswer adddebuglogline dlp_high _t pknownfile getfilename dbggetclientinfo adddebuglogline dlp_high _t pknownfile getfilename dbggetclientinfo adddebuglogline dlp_high _t dbggetclientinfo theprefs getdebugclienttcplevel debugsend op__aichanswer abyhash packanswer op_aichanswer op_emuleprot packanswer pbuffer abyhash thestats addupdataoverheadfilerequest packanswer safesendpacket packanswer void c up down client processaich file hash c safe mem file data c part file file c part file p part file file if p part file null uchar aby hash 16 data read hash16 aby hash p part file the app downloadqueue get file byid aby hash caich hash ah master hash data if p part file null p part file get request file set req fileaich hash new caich hash ah master hash p part file getaich hashset untrusted hash received ah master hash get connectip else add debug log line dlp high false t processaich file hash part file not found or partfile differs from requested file s dbg get client info cupdownclient processaichfilehash csafememfile cpartfile cpartfile ppartfile ppartfile abyhash readhash16 abyhash ppartfile theapp getfilebyid abyhash caichhash ahmasterhash ppartfile ppartfile getrequestfile setreqfileaichhash caichhash ahmasterhash ppartfile getaichhashset untrustedhashreceived ahmasterhash getconnectip adddebuglogline dlp_high _t processaichfilehash partfile dbggetclientinfo const bool c up down client is in no needed list const c part file file to check const for position pos m othernoneeded list get head position pos 0 m othernoneeded list get next pos if m othernoneeded list get at pos file to check return true return false cupdownclient isinnoneededlist cpartfile filetocheck m_othernoneeded_list getheadposition m_othernoneeded_list getnext m_othernoneeded_list getat filetocheck const bool c up down client swap to right file c part file swap to c part file cur file bool ignore suspensions bool swap to isnnp file bool cur fileisnnp file bool was skipped due to source exchange bool do agressive swapping bool debug bool print debug debug the prefs get loga4af if print debug add debug log line dlp low false t oooo debug swap to right file start compare swap to s and cur file s swap to swap to get file name t null cur file get file name add debug log line dlp low false t oooo debug do agressive swapping s do agressive swapping t true t false if swap to return true if cur fileisnnp file cur file get source count cur file get max sources cur fileisnnp file cur file get source count cur file get max sources 8 if print debug add debug log line dlp verylow false t oooo debug cur file does probably not have too many sources if swap to get source count swap to get max sources swap to get source count swap to get max sources 8 swap to reqfile get download state ds lowtolowip get download state ds remotequeuefull if print debug add debug log line dlp verylow false t oooo debug swap to is about to be deleted due to too many sources on that file so we can steal it return true if ignore suspensions is swap suspended cur file do agressive swapping cur fileisnnp file if print debug add debug log line dlp verylow false t oooo debug no suspend block dword temp tick get tick count bool right file has higher prio c part file right file has higher prio swap to cur file uint32 all nnp reask time filereasktime 2 m othernoneeded list get size get download state ds noneededparts 1 0 wait two reask interval for each nnp file before reasking an nnp file if swap to isnnp file cur fileisnnp file get last asked time cur file 0 temp tick get last asked time cur file all nnp reask time right file has higher prio swap to isnnp file cur fileisnnp file get last asked time swap to 0 get last asked time cur file 0 temp tick get last asked time swap to temp tick get last asked time cur file temp tick get last asked time cur file all nnp reask time right file has higher prio temp tick get last asked time swap to all nnp reask time right file has higher prio get last asked time swap to 0 get last asked time cur file 0 swap to isnnp file cur fileisnnp file if print debug if swap to isnnp file cur fileisnnp file right file has higher prio add debug log line dlp verylow false t oooo debug higher prio else if swap to isnnp file get last asked time cur file 0 temp tick get last asked time cur file all nnp reask time right file has higher prio add debug log line dlp verylow false t oooo debug time to reask nnp and it had higher prio else if get last asked time swap to 0 get last asked time cur file 0 temp tick get last asked time swap to temp tick get last asked time cur file temp tick get last asked time cur file all nnp reask time right file has higher prio temp tick get last asked time swap to all nnp reask time add debug log line dlp verylow false t oooo debug both nnp and cur file has longer time since reasked else if swap to isnnp file cur fileisnnp file add debug log line dlp verylow false t oooo debug swap to isnnp file cur fileisnnp file else add debug log line dlp verylow false t oooo debug higher prio for unknown reason if is source request allowed cur file cur file allow swap for source exchange cur file reqfile recently swapped for source exchange is source request allowed swap to swap to allow swap for source exchange swap to reqfile recently swapped for source exchange get download state ds onqueue get remote queue rank 50 if print debug add debug log line dlp low false t oooo debug source request check ok return true else if print debug add debug log line dlp verylow false t oooo debug source request check failed was skipped due to source exchange true if is source request allowed cur file true cur file allow swap for source exchange cur file reqfile recently swapped for source exchange is source request allowed swap to true swap to allow swap for source exchange swap to reqfile recently swapped for source exchange get download state ds onqueue get download state ds onqueue get remote queue rank 50 was skipped due to source exchange true if print debug add debug log line dlp low false t oooo debug source exchange return true else if print debug add debug log line dlp verylow false t oooo debug suspend block else if print debug add debug log line dlp verylow false t oooo debug cur file probably has too many sources if print debug add debug log line dlp low false t oooo debug return false return false cupdownclient swaptorightfile cpartfile swapto cpartfile cur_file ignoresuspensions swaptoisnnpfile curfileisnnpfile wasskippedduetosourceexchange doagressiveswapping printdebug theprefs getloga4af printdebug adddebuglogline dlp_low _t swaptorightfile swapto cur_file swapto swapto getfilename _t cur_file getfilename adddebuglogline dlp_low _t doagressiveswapping doagressiveswapping _t _t swapto curfileisnnpfile cur_file getsourcecount cur_file getmaxsources curfileisnnpfile cur_file getsourcecount cur_file getmaxsources printdebug adddebuglogline dlp_verylow _t cur_file swapto getsourcecount swapto getmaxsources swapto getsourcecount swapto getmaxsources swapto getdownloadstate ds_lowtolowip getdownloadstate ds_remotequeuefull printdebug adddebuglogline dlp_verylow _t swapto ignoresuspensions isswapsuspended cur_file doagressiveswapping curfileisnnpfile printdebug adddebuglogline dlp_verylow _t temptick gettickcount rightfilehashigherprio cpartfile rightfilehashigherprio swapto cur_file allnnpreasktime m_othernoneeded_list getsize getdownloadstate ds_noneededparts swaptoisnnpfile curfileisnnpfile getlastaskedtime cur_file temptick getlastaskedtime cur_file allnnpreasktime rightfilehashigherprio swaptoisnnpfile curfileisnnpfile getlastaskedtime swapto getlastaskedtime cur_file temptick getlastaskedtime swapto temptick getlastaskedtime cur_file temptick getlastaskedtime cur_file allnnpreasktime rightfilehashigherprio temptick getlastaskedtime swapto allnnpreasktime rightfilehashigherprio getlastaskedtime swapto getlastaskedtime cur_file swaptoisnnpfile curfileisnnpfile printdebug swaptoisnnpfile curfileisnnpfile rightfilehashigherprio adddebuglogline dlp_verylow _t swaptoisnnpfile getlastaskedtime cur_file temptick getlastaskedtime cur_file allnnpreasktime rightfilehashigherprio adddebuglogline dlp_verylow _t getlastaskedtime swapto getlastaskedtime cur_file temptick getlastaskedtime swapto temptick getlastaskedtime cur_file temptick getlastaskedtime cur_file allnnpreasktime rightfilehashigherprio temptick getlastaskedtime swapto allnnpreasktime adddebuglogline dlp_verylow _t cur_file swaptoisnnpfile curfileisnnpfile adddebuglogline dlp_verylow _t swaptoisnnpfile curfileisnnpfile adddebuglogline dlp_verylow _t issourcerequestallowed cur_file cur_file allowswapforsourceexchange cur_file recentlyswappedforsourceexchange issourcerequestallowed swapto swapto allowswapforsourceexchange swapto recentlyswappedforsourceexchange getdownloadstate ds_onqueue getremotequeuerank printdebug adddebuglogline dlp_low _t printdebug adddebuglogline dlp_verylow _t wasskippedduetosourceexchange issourcerequestallowed cur_file cur_file allowswapforsourceexchange cur_file recentlyswappedforsourceexchange issourcerequestallowed swapto swapto allowswapforsourceexchange swapto recentlyswappedforsourceexchange getdownloadstate ds_onqueue getdownloadstate ds_onqueue getremotequeuerank wasskippedduetosourceexchange printdebug adddebuglogline dlp_low _t printdebug adddebuglogline dlp_verylow _t printdebug adddebuglogline dlp_verylow _t cur_file printdebug adddebuglogline dlp_low _t bool c up down client do swap c part file swap to bool b remove completely lpctstr reason if the prefs get loga4af add debug log line dlp low false t ooo swapped source s remove s s s reason s dbg get client info b remove completely t yes t no this reqfile this reqfile get file name t null swap to get file name reason 17 dez 2003 bc this reqfile srclists sourcesslot find this was the only place where the usage of the c part file srclists 100 is more effective than using one list if this function here is still again a performance problem there is a more effective way to handle the find situation hint usage of a node ptr which is stored in the c up down client position pos reqfile srclist find this if pos reqfile srclist remove at pos else add debug log line dlp high true t o o unsync between parfile srclist and client otherfiles list swapping client where client has file as reqfile but file doesn t have client in srclist s remove s s s swap reason s dbg get client info b remove completely t yes t no this reqfile this reqfile get file name t null swap to get file name reason remove this client from the a4af list of our new reqfile position pos2 swap to a4a fsrclist find this if pos2 swap to a4a fsrclist remove at pos2 else add debug log line dlp high true t o o unsync between parfile srclist and client otherfiles list swapping client where client has file in another list but file doesn t have client in a4af srclist s remove s s s swap reason s dbg get client info b remove completely t yes t no this reqfile this reqfile get file name t null swap to get file name reason the app emuledlg transferwnd downloadlistctrl remove source this swap to reqfile remove downloading source this if b remove completely reqfile a4a fsrclist add tail this if get download state ds noneededparts m othernoneeded list add tail reqfile else m otherrequests list add tail reqfile the app emuledlg transferwnd downloadlistctrl add source reqfile this true else m filereasktimes remove key reqfile set download state ds none c part file p old request file reqfile set request file swap to p old request file update parts info p old request file update available parts count swap to srclist add tail this the app emuledlg transferwnd downloadlistctrl add source swap to this false return true cupdownclient doswap cpartfile swapto bremovecompletely theprefs getloga4af adddebuglogline dlp_low _t dbggetclientinfo bremovecompletely _t _t getfilename _t swapto getfilename cpartfile cupdownclient removeat adddebuglogline dlp_high _t swapreason dbggetclientinfo bremovecompletely _t _t getfilename _t swapto getfilename swapto a4afsrclist swapto a4afsrclist removeat adddebuglogline dlp_high _t swapreason dbggetclientinfo bremovecompletely _t _t getfilename _t swapto getfilename theapp removesource swapto removedownloadingsource bremovecompletely a4afsrclist addtail getdownloadstate ds_noneededparts m_othernoneeded_list addtail m_otherrequests_list addtail theapp addsource m_filereasktimes removekey setdownloadstate ds_none cpartfile poldrequestfile setrequestfile swapto poldrequestfile updatepartsinfo poldrequestfile updateavailablepartscount swapto addtail theapp addsource swapto void c up down client process http block packet const byte puc data uint u size if reqfile null throw c string t failed to process http data block no reqfile attached if reqfile is stopped reqfile get status ps ready reqfile get status ps empty throw c string t failed to process http data block file not ready for receiving data if m nurlstartpos uint64 1 throw c string t failed to process http data block unexpected file data uint64 n start pos m nurlstartpos uint64 n end pos m nurlstartpos u size m nurlstartpos u size if the prefs get debug clienttcp level 0 debug start i64u end i64u size u s n n start pos n end pos size dbg get file info reqfile get file hash if get download state ds downloading get download state ds noneededparts throw c string t failed to process http data block invalid download state m dwlastblockreceived get tick count if n end pos n start pos u size n end pos n start pos throw c string t failed to process http data block invalid block start end offsets the prefs add2 session transfer data get client soft get client soft so url uint 2 uint 1 false false u size m ndowndataratems u size if credits credits add downloaded u size getip n end pos for position pos m pendingblocks list get head position pos null position pos last pos pending block struct cur block m pendingblocks list get next pos if cur block block start offset n start pos n start pos cur block block end offset if the prefs get debug clienttcp level 0 note left is only accurate in case we have one request block void p m ppcdownsocket void m ppcdownsocket void socket debug t 08x start i64u end i64u size u left i64u s n p n start pos n end pos u size cur block block end offset n start pos u size 1 dbg get file info reqfile get file hash m nlastblockoffset n start pos uint32 len written reqfile write to buffer u size puc data n start pos n end pos cur block block this if len written 0 m ntransferreddown u size set transferred down mini if n end pos cur block block end offset reqfile remove block from list cur block block start offset cur block block end offset delete cur block block delete cur block m pendingblocks list remove at pos last if m pendingblocks list is empty if the prefs get debug clienttcp level 0 debug send more block requests this m nurlstartpos uint64 1 send http block requests else trace hs d bytes missing n function cur block block end offset n end pos return trace s dropping packet n function cupdownclient processhttpblockpacket pucdata usize cstring _t isstopped getstatus ps_ready getstatus ps_empty cstring _t m_nurlstartpos cstring _t nstartpos m_nurlstartpos nendpos m_nurlstartpos usize m_nurlstartpos usize theprefs getdebugclienttcplevel nstartpos nendpos dbggetfileinfo getfilehash getdownloadstate ds_downloading getdownloadstate ds_noneededparts cstring _t m_dwlastblockreceived gettickcount nendpos nstartpos usize nendpos nstartpos cstring _t theprefs add2sessiontransferdata getclientsoft getclientsoft so_url usize m_ndowndataratems usize adddownloaded usize nendpos m_pendingblocks_list getheadposition poslast pending_block_struct cur_block m_pendingblocks_list getnext cur_block startoffset nstartpos nstartpos cur_block endoffset theprefs getdebugclienttcplevel m_ppcdownsocket m_ppcdownsocket _t nstartpos nendpos usize cur_block endoffset nstartpos usize dbggetfileinfo getfilehash m_nlastblockoffset nstartpos lenwritten writetobuffer usize pucdata nstartpos nendpos cur_block lenwritten m_ntransferreddown usize settransferreddownmini nendpos cur_block endoffset removeblockfromlist cur_block startoffset cur_block endoffset cur_block cur_block m_pendingblocks_list removeat poslast m_pendingblocks_list isempty theprefs getdebugclienttcplevel debugsend m_nurlstartpos sendhttpblockrequests __function__ cur_block endoffset nendpos __function__ bool c up down client process http down response const c stringa array assert 0 return false cupdownclient processhttpdownresponse cstringaarray bool c up down client process http down response body const byte puc data uint u size process http block packet puc data u size return true cupdownclient processhttpdownresponsebody pucdata usize processhttpblockpacket pucdata usize bool c up down client get friend slot const if credits the app clientcredits crypto available switch credits get current ident state getip case is idfailed case is idneeded case is idbadguy return false return m bfriendslot cupdownclient getfriendslot theapp cryptoavailable getcurrentidentstate is_idfailed is_idneeded is_idbadguy m_bfriendslot void c up down client set upload state e upload state e new state if e new state m nuploadstate if m nuploadstate us uploading reset upload data rate computation m nupdatarate 0 m nsumforavgupdatarate 0 m avarageudr list remove all if e new state us uploading m fsentoutofpartreqs 0 don t add any final cleanups for us none here m nuploadstate euploadstate e new state the app emuledlg transferwnd clientlistctrl refresh client this cupdownclient setuploadstate euploadstate enewstate enewstate m_nuploadstate m_nuploadstate us_uploading m_nupdatarate m_nsumforavgupdatarate m_avarageudr_list removeall enewstate us_uploading m_fsentoutofpartreqs us_none m_nuploadstate _euploadstate enewstate theapp refreshclient uint32 c up down client get wait start time const if credits null assert false return 0 uint32 dw result credits get secure wait start time getip if dw result m dwuploadtime is downloading this happens only if two clients with invalid securehash are in the queue if at all dw result m dwuploadtime 1 if the prefs get verbose debug only add debug log line false t warning c up down client get wait start time waittime collision s get user name return dw result cupdownclient getwaitstarttime dwresult getsecurewaitstarttime dwresult m_dwuploadtime isdownloading dwresult m_dwuploadtime theprefs getverbose debug_only adddebuglogline _t cupdownclient getwaitstarttime getusername dwresult void c up down client set wait start time if credits null return credits set sec wait start time getip cupdownclient setwaitstarttime setsecwaitstarttime void c up down client clear wait start time if credits null return credits clear wait start time cupdownclient clearwaitstarttime clearwaitstarttime uint32 c up down client get score bool sysvalue bool isdownloading bool onlybasevalue const if m pszusername return 0 if credits 0 assert is kind of runtime class c url client return 0 c known file currequpfile the app sharedfiles get file byid requpfileid if currequpfile return 0 bad clients see note in function if credits get current ident state getip is idbadguy return 0 friend slot if is friend get friend slot has lowid return 0x0fffffff if is banned m bgplevildoer return 0 if sysvalue has lowid socket socket is connected return 0 int filepriority get file prio as number calculate score based on waitingtime and other factors float f base value if onlybasevalue f base value 100 else if isdownloading f base value float get tick count get wait start time 1000 else we dont want one client to download forever the first 15 min downloadtime counts as 15 min waitingtime and you get a 15 min bonus while you are in the first 15 min to avoid 20 sec downloads after this the score won t raise anymore f base value float m dwuploadtime get wait start time assert m dwuploadtime get wait start time 0 oct 28 02 changed this from 0 to 0 f base value float get tick count m dwuploadtime 900000 900000 1800000 f base value 1000 if the prefs use credit system float modif credits get score ratio getip f base value modif if onlybasevalue f base value float filepriority 10 0f if is emule client this get client soft 10 m byemuleversion 0x19 f base value 0 5f return uint32 f base value cupdownclient getscore m_pszusername iskindof runtime_class curlclient cknownfile theapp getfilebyid getcurrentidentstate is_idbadguy isfriend getfriendslot haslowid isbanned m_bgplevildoer haslowid isconnected getfileprioasnumber fbasevalue fbasevalue fbasevalue gettickcount getwaitstarttime fbasevalue m_dwuploadtime getwaitstarttime m_dwuploadtime getwaitstarttime fbasevalue gettickcount m_dwuploadtime fbasevalue theprefs usecreditsystem getscoreratio fbasevalue fbasevalue isemuleclient getclientsoft m_byemuleversion fbasevalue fbasevalue void c up down client add req block requested block struct reqblock if get upload state us uploading if the prefs get log ul dl events add debug log line dlp low false t upload client client tried to add req block when not in upload slot prevented req blocks from being added s dbg get client info delete reqblock return if has collection upload slot c known file p downloading file the app sharedfiles get file byid reqblock fileid if p downloading file null if c collection has collection extention p downloading file get file name p downloading file get file size uint64 maxprioritycoll size add debug log line dlp high false t upload client client tried to add req block for non collection while having a collection slot prevented req blocks from being added s dbg get client info delete reqblock return else assert false for position pos m doneblocks list get head position pos 0 const requested block struct cur reqblock m doneblocks list get next pos if reqblock start offset cur reqblock start offset reqblock end offset cur reqblock end offset delete reqblock return for position pos m blockrequests queue get head position pos 0 const requested block struct cur reqblock m blockrequests queue get next pos if reqblock start offset cur reqblock start offset reqblock end offset cur reqblock end offset delete reqblock return m blockrequests queue add tail reqblock cupdownclient addreqblock requested_block_struct getuploadstate us_uploading theprefs getloguldlevents adddebuglogline dlp_low _t uploadclient dbggetclientinfo hascollectionuploadslot cknownfile pdownloadingfile theapp getfilebyid pdownloadingfile ccollection hascollectionextention pdownloadingfile getfilename pdownloadingfile getfilesize maxprioritycoll_size adddebuglogline dlp_high _t uploadclient dbggetclientinfo m_doneblocks_list getheadposition requested_block_struct cur_reqblock m_doneblocks_list getnext startoffset cur_reqblock startoffset endoffset cur_reqblock endoffset m_blockrequests_queue getheadposition requested_block_struct cur_reqblock m_blockrequests_queue getnext startoffset cur_reqblock startoffset endoffset cur_reqblock endoffset m_blockrequests_queue addtail void c up down client create next block package see if we can do an early return there may be no new blocks to load from disk and add to buffer or buffer may be large enough allready if m blockrequests queue is empty there are no new blocks requested m addedpayloadqueuesession get queue session payload up m addedpayloadqueuesession get queue session payload up 50 1024 the buffered data is large enough allready return c file file byte filedata 0 c string fullname bool b frompf true statistic to breakdown uploaded data by complete file vs partfile c sync helper lock file try buffer new data if current buffer is less than 100 k bytes while m blockrequests queue is empty m addedpayloadqueuesession get queue session payload up m addedpayloadqueuesession get queue session payload up 100 1024 requested block struct currentblock m blockrequests queue get head c known file srcfile the app sharedfiles get file byid currentblock fileid if srcfile throw get res string ids err req fnf if srcfile is part file c part file srcfile get status ps complete do not access a part file if it is currently moved into the incoming directory because the moving of part file into the incoming directory may take a noticable amount of time we can not wait for m filecompletemutex and block the main thread if c part file srcfile m filecompletemutex lock 0 just do a quick test of the mutex s state and return if it s locked return lock file m pobject c part file srcfile m filecompletemutex if it s a part file which we are uploading the file remains locked until we ve read the current block this way the file completion thread can not try to move the file into the incoming directory fullname remove file extension c part file srcfile get full name else fullname format t s s srcfile get path srcfile get file name uint64 i64u togo if currentblock start offset currentblock end offset i64u togo currentblock end offset srcfile get file size currentblock start offset else i64u togo currentblock end offset currentblock start offset if srcfile is part file c part file srcfile is complete currentblock start offset currentblock end offset 1 true throw get res string ids err incompleteblock if i64u togo emblocksize 3 throw get res string ids err largereqblock uint32 togo uint32 i64u togo if srcfile is part file b frompf false this is not a part file if file open fullname c file mode read c file os sequential scan c file share deny none throw get res string ids err open file seek currentblock start offset 0 filedata new byte togo 500 if uint32 done file read filedata togo togo file seek to begin file read filedata done togo done file close else c part file partfile c part file srcfile partfile m hpartfile seek currentblock start offset 0 filedata new byte togo 500 if uint32 done partfile m hpartfile read filedata togo togo partfile m hpartfile seek to begin partfile m hpartfile read filedata done togo done if lock file m pobject lock file m pobject unlock unlock the part file as soon as we are done with accessing it lock file m pobject null set upload fileid srcfile check extension to decide whether to compress or not c string ext srcfile get file name ext make lower int pos ext reverse find t if pos 1 ext ext mid pos bool comp flag ext t zip ext t cbz ext t rar ext t cbr ext t ace ext t ogm if ext t avi the prefs get dont compress avi comp flag false if is uploading to peer cache m bydatacompver 1 comp flag create packed packets filedata togo currentblock b frompf else create standart packets filedata togo currentblock b frompf file statistic srcfile statistic add transferred togo m addedpayloadqueuesession togo m doneblocks list add head m blockrequests queue remove head delete filedata filedata 0 catch c string error if the prefs get verbose debug log warning get res string ids err clienterrored get user name error the app uploadqueue remove from upload queue this t client error error delete filedata return catch c file exception e tchar sz error max cfexp errormsg e get error message sz error arrsize sz error if the prefs get verbose debug log warning t failed to create upload package for s s get user name sz error the app uploadqueue remove from upload queue this c string t failed to create upload package sz error delete filedata e delete return cupdownclient createnextblockpackage m_blockrequests_queue isempty m_addedpayloadqueuesession getqueuesessionpayloadup m_addedpayloadqueuesession getqueuesessionpayloadup cfile cstring bfrompf csynchelper lockfile kbytes m_blockrequests_queue isempty m_addedpayloadqueuesession getqueuesessionpayloadup m_addedpayloadqueuesession getqueuesessionpayloadup requested_block_struct m_blockrequests_queue gethead cknownfile theapp getfilebyid getresstring ids_err_req_fnf ispartfile cpartfile getstatus ps_complete m_filecompletemutex cpartfile m_filecompletemutex lockfile m_pobject cpartfile m_filecompletemutex removefileextension cpartfile getfullname _t getpath getfilename i64utogo startoffset endoffset i64utogo endoffset getfilesize startoffset i64utogo endoffset startoffset ispartfile cpartfile iscomplete startoffset endoffset getresstring ids_err_incompleteblock i64utogo getresstring ids_err_largereqblock i64utogo ispartfile bfrompf cfile moderead cfile ossequentialscan cfile sharedenynone getresstring ids_err_open startoffset seektobegin cpartfile cpartfile m_hpartfile startoffset m_hpartfile m_hpartfile seektobegin m_hpartfile lockfile m_pobject lockfile m_pobject lockfile m_pobject setuploadfileid cstring getfilename makelower reversefind _t compflag _t _t _t _t _t _t _t theprefs getdontcompressavi compflag isuploadingtopeercache m_bydatacompver compflag createpackedpackets bfrompf createstandartpackets bfrompf addtransferred m_addedpayloadqueuesession m_doneblocks_list addhead m_blockrequests_queue removehead cstring theprefs getverbose debuglogwarning getresstring ids_err_clienterrored getusername theapp removefromuploadqueue _t cfileexception szerror max_cfexp_errormsg geterrormessage szerror szerror theprefs getverbose debuglogwarning _t getusername szerror theapp removefromuploadqueue cstring _t szerror void c up down client send hashset packet const uchar forfileid c known file file the app sharedfiles get file byid forfileid if file check failed file id reqs forfileid throw get res string ids err req fnf t send hashset packet c safe mem file data 1024 data write hash16 file get file hash uint parts file get hash count data writeu int16 uint16 parts for uint i 0 i parts i data write hash16 file get part hash i if the prefs get debug clienttcp level 0 debug send op hashsetanswer this forfileid packet packet new packet data packet opcode op hashsetanswer the stats add up data overhead file request packet size socket send packet packet true true cupdownclient sendhashsetpacket cknownfile theapp getfilebyid checkfailedfileidreqs getresstring ids_err_req_fnf _t sendhashsetpacket csafememfile writehash16 getfilehash gethashcount writeuint16 writehash16 getparthash theprefs getdebugclienttcplevel debugsend op__hashsetanswer op_hashsetanswer thestats addupdataoverheadfilerequest sendpacket void c up down client set upload fileid c known file newreqfile c known file oldreqfile we use the knownfilelist because we may have unshared the file but we always check the download list first because that person may have decided to redownload that file which will replace the object in the knownfilelist if completed if oldreqfile the app downloadqueue get file byid requpfileid null oldreqfile the app knownfiles find known file byid requpfileid if newreqfile oldreqfile return clear old status delete m abyuppartstatus m abyuppartstatus null m nuppartcount 0 m nupcompletesourcescount 0 if newreqfile newreqfile add uploading client this md4cpy requpfileid newreqfile get file hash else md4clr requpfileid if oldreqfile oldreqfile remove uploading client this cupdownclient setuploadfileid cknownfile cknownfile theapp getfilebyid theapp findknownfilebyid m_abyuppartstatus m_abyuppartstatus m_nuppartcount m_nupcompletesourcescount adduploadingclient getfilehash removeuploadingclient uint32 c up down client send block data dword cur tick get tick count uint64 sent bytes complete file 0 uint64 sent bytes part file 0 uint64 sent bytes payload 0 if get file upload socket m epeercacheupstate pcus wait cache reply cem socket s get file upload socket uint u up stats port if m ppcupsocket is uploading to peer cache u up stats port uint 1 check if filedata has been sent via the normal socket since last call uint64 sent bytes complete file normal socket socket get sent bytes complete file since last call and reset uint64 sent bytes part file normal socket socket get sent bytes part file since last call and reset if the prefs get verbose sent bytes complete file normal socket sent bytes part file normal socket 0 add debug log line false t sent file data via normal socket when in pc mode bytes i64i sent bytes complete file normal socket sent bytes part file normal socket else u up stats port get user port extended statistics information based on which client software and which port we sent this data to this also updates the grand total for sent bytes etc and where this data came from sent bytes complete file s get sent bytes complete file since last call and reset sent bytes part file s get sent bytes part file since last call and reset the prefs add2 session transfer data get client soft u up stats port false true uint sent bytes complete file is friend get friend slot the prefs add2 session transfer data get client soft u up stats port true true uint sent bytes part file is friend get friend slot m ntransferredup uint m ntransferredup sent bytes complete file sent bytes part file credits add uploaded uint sent bytes complete file sent bytes part file getip sent bytes payload s get sent payload since last call and reset m ncurqueuesessionpayloadup uint m ncurqueuesessionpayloadup sent bytes payload if the app uploadqueue check for time over this the app uploadqueue remove from upload queue this t completed transfer true send out of part reqs and add to waiting queue else read blocks from file and put on socket create next block package if sent bytes complete file sent bytes part file 0 m avarageudr list get count 0 cur tick m avarageudr list get tail timestamp 1 1000 store how much data we ve transferred this round to be able to calculate average speed later keep sum of all values in list up to date transferred data newitem uint sent bytes complete file sent bytes part file cur tick m avarageudr list add tail newitem m nsumforavgupdatarate uint m nsumforavgupdatarate sent bytes complete file sent bytes part file remove to old values in list while m avarageudr list get count 0 cur tick m avarageudr list get head timestamp 10 1000 keep sum of all values in list up to date m nsumforavgupdatarate m avarageudr list remove head datalen calculate average speed for this slot if m avarageudr list get count 0 cur tick m avarageudr list get head timestamp 0 get up start time delay 2 1000 m nupdatarate uint ulonglong m nsumforavgupdatarate 1000 cur tick m avarageudr list get head timestamp else not enough values to calculate trustworthy speed use 1 to tell this m nupdatarate 0 1 check if it s time to update the display if cur tick m lastrefresheduldisplay minwait before uldisplay windowupdate uint32 rand 800 rand max update display the app emuledlg transferwnd uploadlistctrl refresh client this the app emuledlg transferwnd clientlistctrl refresh client this m lastrefresheduldisplay cur tick return uint sent bytes complete file sent bytes part file cupdownclient sendblockdata curtick gettickcount sentbytescompletefile sentbytespartfile sentbytespayload getfileuploadsocket m_epeercacheupstate pcus_wait_cache_reply cemsocket getfileuploadsocket uupstatsport m_ppcupsocket isuploadingtopeercache uupstatsport sentbytescompletefilenormalsocket getsentbytescompletefilesincelastcallandreset sentbytespartfilenormalsocket getsentbytespartfilesincelastcallandreset theprefs getverbose sentbytescompletefilenormalsocket sentbytespartfilenormalsocket adddebuglogline _t sentbytescompletefilenormalsocket sentbytespartfilenormalsocket uupstatsport getuserport sentbytescompletefile getsentbytescompletefilesincelastcallandreset sentbytespartfile getsentbytespartfilesincelastcallandreset theprefs add2sessiontransferdata getclientsoft uupstatsport sentbytescompletefile isfriend getfriendslot theprefs add2sessiontransferdata getclientsoft uupstatsport sentbytespartfile isfriend getfriendslot m_ntransferredup m_ntransferredup sentbytescompletefile sentbytespartfile adduploaded sentbytescompletefile sentbytespartfile sentbytespayload getsentpayloadsincelastcallandreset m_ncurqueuesessionpayloadup m_ncurqueuesessionpayloadup sentbytespayload theapp checkfortimeover theapp removefromuploadqueue _t sendoutofpartreqsandaddtowaitingqueue createnextblockpackage sentbytescompletefile sentbytespartfile m_avarageudr_list getcount curtick m_avarageudr_list gettail transferreddata sentbytescompletefile sentbytespartfile curtick m_avarageudr_list addtail m_nsumforavgupdatarate m_nsumforavgupdatarate sentbytescompletefile sentbytespartfile m_avarageudr_list getcount curtick m_avarageudr_list gethead m_nsumforavgupdatarate m_avarageudr_list removehead m_avarageudr_list getcount curtick m_avarageudr_list gethead getupstarttimedelay m_nupdatarate m_nsumforavgupdatarate curtick m_avarageudr_list gethead m_nupdatarate curtick m_lastrefresheduldisplay minwait_before_uldisplay_windowupdate rand_max theapp refreshclient theapp refreshclient m_lastrefresheduldisplay curtick sentbytescompletefile sentbytespartfile void c up down client clear upload block requests flush send blocks for position pos m blockrequests queue get head position pos 0 delete m blockrequests queue get next pos m blockrequests queue remove all for position pos m doneblocks list get head position pos 0 delete m doneblocks list get next pos m doneblocks list remove all cupdownclient clearuploadblockrequests flushsendblocks m_blockrequests_queue getheadposition m_blockrequests_queue getnext m_blockrequests_queue removeall m_doneblocks_list getheadposition m_doneblocks_list getnext m_doneblocks_list removeall void c up down client send ranking info if ext protocol available return uint n rank the app uploadqueue get waiting position this if n rank return packet packet new packet op queueranking 12 op emuleprot pokeu int16 packet p buffer 0 uint16 n rank memset packet p buffer 2 0 10 if the prefs get debug clienttcp level 0 debug send op queuerank this the stats add up data overhead file request packet size socket send packet packet true true cupdownclient sendrankinginfo extprotocolavailable nrank theapp getwaitingposition nrank op_queueranking op_emuleprot pokeuint16 pbuffer nrank pbuffer theprefs getdebugclienttcplevel debugsend op__queuerank thestats addupdataoverheadfilerequest sendpacket void c up down client send comment info const c known file file if m bcommentdirty file null ext protocol available m byacceptcommentver 1 return m bcommentdirty false uint rating file get file rating const c string desc file get file comment if file get file rating 0 desc is empty return c safe mem file data 256 data writeu int8 uint8 rating data write long string desc get unicode support if the prefs get debug clienttcp level 0 debug send op filedesc this file get file hash packet packet new packet data op emuleprot packet opcode op filedesc the stats add up data overhead file request packet size socket send packet packet true cupdownclient sendcommentinfo cknownfile m_bcommentdirty extprotocolavailable m_byacceptcommentver m_bcommentdirty getfilerating cstring getfilecomment getfilerating isempty csafememfile writeuint8 writelongstring getunicodesupport theprefs getdebugclienttcplevel debugsend op__filedesc getfilehash op_emuleprot op_filedesc thestats addupdataoverheadfilerequest sendpacket void c up down client add request count const uchar fileid for position pos m requestedfiles list get head position pos 0 requested file struct cur struct m requestedfiles list get next pos if md4cmp cur struct fileid fileid if get tick count cur struct lastasked min requesttime get friend slot if get download state ds downloading cur struct badrequests if cur struct badrequests badclientban ban else if cur struct badrequests cur struct badrequests cur struct lastasked get tick count return requested file struct new struct new requested file struct md4cpy new struct fileid fileid new struct lastasked get tick count new struct badrequests 0 m requestedfiles list add head new struct cupdownclient addrequestcount m_requestedfiles_list getheadposition requested_file_struct cur_struct m_requestedfiles_list getnext cur_struct gettickcount cur_struct min_requesttime getfriendslot getdownloadstate ds_downloading cur_struct cur_struct cur_struct cur_struct cur_struct gettickcount requested_file_struct new_struct requested_file_struct new_struct new_struct gettickcount new_struct m_requestedfiles_list addhead new_struct void c up down client un ban the app clientlist add track client this the app clientlist remove banned client getip set upload state us none clear wait start time the app emuledlg transferwnd show queue count the app uploadqueue get waiting user count for position pos m requestedfiles list get head position pos 0 requested file struct cur struct m requestedfiles list get next pos cur struct badrequests 0 cur struct lastasked 0 cupdownclient unban theapp addtrackclient theapp removebannedclient setuploadstate us_none clearwaitstarttime theapp showqueuecount theapp getwaitingusercount m_requestedfiles_list getheadposition requested_file_struct cur_struct m_requestedfiles_list getnext cur_struct cur_struct void c up down client ban lpctstr psz reason set chat state ms none the app clientlist add track client this if is banned if the prefs get log banned clients add debug log line false t banned s s psz reason null t aggressive behaviour psz reason dbg get client info ifdef debug else if the prefs get log banned clients add debug log line false t banned refreshed s s psz reason null t aggressive behaviour psz reason dbg get client info endif the app clientlist add banned client getip set upload state us banned the app emuledlg transferwnd show queue count the app uploadqueue get waiting user count the app emuledlg transferwnd queuelistctrl refresh client this if socket null socket is connected socket shut down sd receive let the socket timeout since we dont want to risk to delete the client right now this isnt acutally perfect could be changed later cupdownclient pszreason setchatstate ms_none theapp addtrackclient isbanned theprefs getlogbannedclients adddebuglogline _t pszreason _t pszreason dbggetclientinfo _debug theprefs getlogbannedclients adddebuglogline _t pszreason _t pszreason dbggetclientinfo theapp addbannedclient setuploadstate us_banned theapp showqueuecount theapp getwaitingusercount theapp refreshclient isconnected shutdown sd_receive void c up down client flush send blocks call this when you stop upload or the socket might be not able to send if socket socket may be null socket truncate queues cupdownclient flushsendblocks truncatequeues void c up down client set collection upload slot bool b value assert is downloading b value m bcollectionuploadslot m bcollectionuploadslot b value cupdownclient setcollectionuploadslot bvalue isdownloading bvalue m_bcollectionuploadslot m_bcollectionuploadslot bvalue bool c up down client process extended info c safe mem file data c known file tempreqfile delete m abyuppartstatus m abyuppartstatus null m nuppartcount 0 m nupcompletesourcescount 0 if get extended requests version 0 return true uint16 ned2k up part count data readu int16 if ned2k up part count m nuppartcount tempreqfile get part count m abyuppartstatus new uint8 m nuppartcount memset m abyuppartstatus 0 m nuppartcount else if tempreqfile geted2k part count ned2k up part count we already checked if we are talking about the same file so if we get here something really strange happened m nuppartcount 0 return false m nuppartcount tempreqfile get part count m abyuppartstatus new uint8 m nuppartcount uint16 done 0 while done m nuppartcount uint8 toread data readu int8 for uint i 0 i 8 i m abyuppartstatus done toread i 1 1 0 we may want to use this for another feature if m abyuppartstatus done tempreqfile is complete uint64 done partsize uint64 done 1 partsize 1 b parts needed true done if done m nuppartcount break if get extended requests version 1 uint16 n complete count last get up complete sources count uint16 n complete count new data readu int16 set up complete sources count n complete count new if n complete count last n complete count new tempreqfile update parts info the app emuledlg transferwnd queuelistctrl refresh client this return true cupdownclient processextendedinfo csafememfile cknownfile m_abyuppartstatus m_abyuppartstatus m_nuppartcount m_nupcompletesourcescount getextendedrequestsversion ned2kuppartcount readuint16 ned2kuppartcount m_nuppartcount getpartcount m_abyuppartstatus m_nuppartcount m_abyuppartstatus m_nuppartcount geted2kpartcount ned2kuppartcount m_nuppartcount m_nuppartcount getpartcount m_abyuppartstatus m_nuppartcount m_nuppartcount readuint8 m_abyuppartstatus m_abyuppartstatus iscomplete bpartsneeded m_nuppartcount getextendedrequestsversion ncompletecountlast getupcompletesourcescount ncompletecountnew readuint16 setupcompletesourcescount ncompletecountnew ncompletecountlast ncompletecountnew updatepartsinfo theapp refreshclient void c up down client draw up status bar cdc dc rect rect bool onlygreyrect bool b flat const colorref cr neither colorref cr next sending colorref cr both colorref cr sending if get slot number the app uploadqueue get active uploads count get upload state us uploading get upload state us connecting cr neither rgb 224 224 224 cr next sending rgb 255 208 0 cr both b flat rgb 0 0 0 rgb 104 104 104 cr sending rgb 0 150 0 else grayed out cr neither rgb 248 248 248 cr next sending rgb 255 244 191 cr both b flat rgb 191 191 191 rgb 191 191 191 cr sending rgb 191 229 191 wistily up status fix c known file currequpfile the app sharedfiles get file byid requpfileid em file size filesize if currequpfile filesize currequpfile get file size else filesize uint64 partsize uint64 m nuppartcount wistily up status fix if filesize uint64 0 s upstatusbar set file size filesize s upstatusbar set height rect bottom rect top s upstatusbar set width rect right rect left s upstatusbar fill cr neither if onlygreyrect m abyuppartstatus for uint i 0 i m nuppartcount i if m abyuppartstatus i s upstatusbar fill range partsize uint64 i partsize uint64 i 1 cr both const requested block struct block if m blockrequests queue is empty block m blockrequests queue get head if block uint32 start uint32 block start offset partsize s upstatusbar fill range uint64 start partsize uint64 start 1 partsize cr next sending if m doneblocks list is empty block m doneblocks list get tail if block uint32 start uint32 block start offset partsize s upstatusbar fill range uint64 start partsize uint64 start 1 partsize cr next sending if m doneblocks list is empty for position pos m doneblocks list get head position pos 0 block m doneblocks list get next pos s upstatusbar fill range block start offset block end offset 1 cr sending s upstatusbar draw dc rect left rect top b flat cupdownclient drawupstatusbar bflat crneither crnextsending crboth crsending getslotnumber theapp getactiveuploadscount getuploadstate us_uploading getuploadstate us_connecting crneither crnextsending crboth bflat crsending crneither crnextsending crboth bflat crsending upstatusfix cknownfile theapp getfilebyid emfilesize getfilesize m_nuppartcount upstatusfix s_upstatusbar setfilesize s_upstatusbar setheight s_upstatusbar setwidth s_upstatusbar crneither m_abyuppartstatus m_nuppartcount m_abyuppartstatus s_upstatusbar fillrange crboth requested_block_struct m_blockrequests_queue isempty m_blockrequests_queue gethead startoffset s_upstatusbar fillrange crnextsending m_doneblocks_list isempty m_doneblocks_list gettail startoffset s_upstatusbar fillrange crnextsending m_doneblocks_list isempty m_doneblocks_list getheadposition m_doneblocks_list getnext s_upstatusbar fillrange startoffset endoffset crsending s_upstatusbar bflat float c up down client get combined file prio and credit if credits 0 assert is kind of runtime class c url client return 0 0f return 10 0f credits get score ratio getip float get file prio as number cupdownclient getcombinedfileprioandcredit iskindof runtime_class curlclient getscoreratio getfileprioasnumber void c up down client send out of part reqs and add to waiting queue op outofpartreqs will tell the downloading client to go back to on queue the main reason for this is that if we put the client back on queue and it goes back to the upload before the socket times out we get a situation where the downloader thinks it already sent the requested blocks and the uploader thinks the downloader didn t send any request blocks then the connection times out i did some tests with e donkey also and it seems to work well with them also if the prefs get debug clienttcp level 0 debug send op outofpartreqs this packet p packet new packet op outofpartreqs 0 the stats add up data overhead file request p packet size socket send packet p packet true true m fsentoutofpartreqs 1 the app uploadqueue add client to queue this true cupdownclient sendoutofpartreqsandaddtowaitingqueue op_outofpartreqs onqueue edonkey theprefs getdebugclienttcplevel debugsend op__outofpartreqs ppacket op_outofpartreqs thestats addupdataoverheadfilerequest ppacket sendpacket ppacket m_fsentoutofpartreqs theapp addclienttoqueue cem socket c up down client get file upload socket bool b log if m ppcupsocket is uploading to peer cache m epeercacheupstate pcus wait cache reply if b log the prefs get verbose add debug log line false t s got peercache socket dbg get client info return m ppcupsocket else if b log the prefs get verbose add debug log line false t s got normal socket dbg get client info return socket cemsocket cupdownclient getfileuploadsocket blog m_ppcupsocket isuploadingtopeercache m_epeercacheupstate pcus_wait_cache_reply blog theprefs getverbose adddebuglogline _t dbggetclientinfo m_ppcupsocket blog theprefs getverbose adddebuglogline _t dbggetclientinfo void c up down client create standart packets byte data uint32 togo requested block struct currentblock bool b frompf uint32 n packet size c mem file memfile byte data togo if togo 10240 n packet size togo uint32 togo 10240 else n packet size togo while togo if togo n packet size 2 n packet size togo assert n packet size togo n packet size uint64 statpos currentblock end offset togo n packet size uint64 endpos currentblock end offset togo if is uploading to peer cache if m ppcupsocket null assert 0 c string str error str error format t failed to upload to peer cache missing socket s dbg get client info throw str error uses conversion c safe mem file data http 10240 if m ihttpsendstate 0 c known file srcfile the app sharedfiles get file byid get upload fileid c stringa str str append format http 1 0 206 r n str append format content range bytes i64u i64u i64u r n currentblock start offset currentblock end offset 1 srcfile get file size str append format content type application octet stream r n str append format content length u r n uint32 currentblock end offset currentblock start offset str append format server e mule s r n t2ca the app m strcurversionlong str append format r n data http write lpcstr str str get length the stats add up data overhead file request uint data http get length m ihttpsendstate 1 if the prefs get debug clienttcp level 0 debug send peer cache http this get upload fileid debug t hs n str data http write data n packet size data n packet size if the prefs get debug clienttcp level 1 debug send peer cache http data this get upload fileid debug t start i64u end i64u size u n statpos endpos n packet size uint u raw packet size uint data http get length lpbyte p raw packet data data http detach c raw packet packet new c raw packet char p raw packet data u raw packet size b frompf m ppcupsocket send packet packet true false n packet size free p raw packet data else packet packet if statpos 0xffffffff endpos 0xffffffff packet new packet op sendingpart i64 n packet size 32 op emuleprot b frompf md4cpy packet p buffer 0 get upload fileid pokeu int64 packet p buffer 16 statpos pokeu int64 packet p buffer 24 endpos memfile read packet p buffer 32 n packet size the stats add up data overhead file request 32 else packet new packet op sendingpart n packet size 24 op edonkeyprot b frompf md4cpy packet p buffer 0 get upload fileid pokeu int32 packet p buffer 16 uint32 statpos pokeu int32 packet p buffer 20 uint32 endpos memfile read packet p buffer 24 n packet size the stats add up data overhead file request 24 if the prefs get debug clienttcp level 0 debug send op sendingpart this get upload fileid debug t start i64u end i64u size u n statpos endpos n packet size put packet directly on socket socket send packet packet true false n packet size cupdownclient createstandartpackets requested_block_struct bfrompf npacketsize cmemfile npacketsize npacketsize npacketsize npacketsize npacketsize npacketsize endoffset npacketsize endoffset isuploadingtopeercache m_ppcupsocket cstring strerror strerror _t peercache dbggetclientinfo strerror uses_conversion csafememfile datahttp m_ihttpsendstate cknownfile theapp getfilebyid getuploadfileid cstringa appendformat appendformat startoffset endoffset getfilesize appendformat appendformat endoffset startoffset appendformat emule theapp m_strcurversionlong appendformat datahttp getlength thestats addupdataoverheadfilerequest datahttp getlength m_ihttpsendstate theprefs getdebugclienttcplevel debugsend peercache getuploadfileid _t datahttp npacketsize npacketsize theprefs getdebugclienttcplevel debugsend peercache getuploadfileid _t npacketsize urawpacketsize datahttp getlength prawpacketdata datahttp crawpacket crawpacket prawpacketdata urawpacketsize bfrompf m_ppcupsocket sendpacket npacketsize prawpacketdata op_sendingpart_i64 npacketsize op_emuleprot bfrompf pbuffer getuploadfileid pokeuint64 pbuffer pokeuint64 pbuffer pbuffer npacketsize thestats addupdataoverheadfilerequest op_sendingpart npacketsize op_edonkeyprot bfrompf pbuffer getuploadfileid pokeuint32 pbuffer pokeuint32 pbuffer pbuffer npacketsize thestats addupdataoverheadfilerequest theprefs getdebugclienttcplevel debugsend op__sendingpart getuploadfileid _t npacketsize sendpacket npacketsize void c up down client create packed packets byte data uint32 togo requested block struct currentblock bool b frompf byte output new byte togo 300 u longf newsize togo 300 uint result compress2 output newsize data togo 9 if result z ok togo newsize delete output create standart packets data togo currentblock b frompf return c mem file memfile output newsize uint32 old size togo togo newsize uint32 n packet size if togo 10240 n packet size togo uint32 togo 10240 else n packet size togo uint32 total payload size 0 while togo if togo n packet size 2 n packet size togo assert n packet size togo n packet size uint64 statpos currentblock start offset packet packet if currentblock start offset 0xffffffff currentblock end offset 0xffffffff packet new packet op compressedpart i64 n packet size 28 op emuleprot b frompf md4cpy packet p buffer 0 get upload fileid pokeu int64 packet p buffer 16 statpos pokeu int32 packet p buffer 24 newsize memfile read packet p buffer 28 n packet size else packet new packet op compressedpart n packet size 24 op emuleprot b frompf md4cpy packet p buffer 0 get upload fileid pokeu int32 packet p buffer 16 uint32 statpos pokeu int32 packet p buffer 20 newsize memfile read packet p buffer 24 n packet size if the prefs get debug clienttcp level 0 debug send op compressedpart this get upload fileid debug t start i64u block size u size u n statpos newsize n packet size approximate payload size uint32 payload size n packet size old size newsize if togo 0 total payload size payload size old size payload size old size total payload size total payload size payload size put packet directly on socket the stats add up data overhead file request 24 socket send packet packet true false payload size delete output cupdownclient createpackedpackets requested_block_struct bfrompf ulongf z_ok createstandartpackets bfrompf cmemfile oldsize npacketsize npacketsize npacketsize totalpayloadsize npacketsize npacketsize npacketsize npacketsize startoffset startoffset endoffset op_compressedpart_i64 npacketsize op_emuleprot bfrompf pbuffer getuploadfileid pokeuint64 pbuffer pokeuint32 pbuffer pbuffer npacketsize op_compressedpart npacketsize op_emuleprot bfrompf pbuffer getuploadfileid pokeuint32 pbuffer pokeuint32 pbuffer pbuffer npacketsize theprefs getdebugclienttcplevel debugsend op__compressedpart getuploadfileid _t blocksize npacketsize payloadsize npacketsize oldsize totalpayloadsize payloadsize oldsize payloadsize oldsize totalpayloadsize totalpayloadsize payloadsize thestats addupdataoverheadfilerequest sendpacket payloadsize int c up down client get file prio as number const c known file currequpfile the app sharedfiles get file byid requpfileid if currequpfile return 0 todo coded by tecxx herbert one yet unsolved problem here sometimes a client asks for 2 files and there is no way to decide which file the client finally gets so it could happen that he is queued first because of a high prio file but then asks for something completely different int filepriority 10 standard switch currequpfile get up priority case pr veryhigh filepriority 18 break case pr high filepriority 9 break case pr low filepriority 6 break case pr verylow filepriority 2 break case pr normal default filepriority 7 break return filepriority cupdownclient getfileprioasnumber cknownfile theapp getfilebyid getuppriority pr_veryhigh pr_high pr_low pr_verylow pr_normal void setip uint32 val only use this when you know the real ip or when your clearing it m dwuserip val m nconnectip val m_dwuserip m_nconnectip bool has valid hash const return const int m achuserhash 0 0 const int m achuserhash 1 0 const int m achuserhash 2 0 const int m achuserhash 3 0 hasvalidhash m_achuserhash m_achuserhash m_achuserhash m_achuserhash uint get session up const return m ntransferredup m ncursessionup void reset session up m ncursessionup m ntransferredup m addedpayloadqueuesession 0 m ncurqueuesessionpayloadup 0 getsessionup m_ntransferredup m_ncursessionup resetsessionup m_ncursessionup m_ntransferredup m_addedpayloadqueuesession m_ncurqueuesessionpayloadup uint get session down const return m ntransferreddown m ncursessiondown void reset session down m ncursessiondown m ntransferreddown getsessiondown m_ntransferreddown m_ncursessiondown resetsessiondown m_ncursessiondown m_ntransferreddown void draw up status bar cdc dc rect rect bool onlygreyrect bool b flat const bool is up part available uint i part const return i part m nuppartcount m abyuppartstatus false m abyuppartstatus i part 0 drawupstatusbar bflat isuppartavailable ipart ipart m_nuppartcount m_abyuppartstatus m_abyuppartstatus ipart void set last asked time m filereasktimes set at reqfile get tick count bool is part available uint i part const return i part m npartcount m abypartstatus false m abypartstatus i part 0 setlastaskedtime m_filereasktimes setat gettickcount ispartavailable ipart ipart m_npartcount m_abypartstatus m_abypartstatus ipart void set down start time m dwdownstarttime get tick count uint32 get down time difference boolean clear true uint32 my time m dwdownstarttime if clear m dwdownstarttime 0 return get tick count my time setdownstarttime m_dwdownstarttime gettickcount getdowntimedifference mytime m_dwdownstarttime m_dwdownstarttime gettickcount mytime void cemule app enablertl windows layout bool winapi pfn set process default layout dword dw flags farproc pfn set process default layout get proc address get module handle t user32 set process default layout if pfn set process default layout pfn set process default layout layout rtl s hrtlwindowslayoutoldcbtfilterhook set windows hook ex wh cbt rtl windows layout cbt filter hook null get current thread id cemuleapp enablertlwindowslayout pfnsetprocessdefaultlayout dwflags pfnsetprocessdefaultlayout getprocaddress getmodulehandle _t setprocessdefaultlayout pfnsetprocessdefaultlayout pfnsetprocessdefaultlayout layout_rtl s_hrtlwindowslayoutoldcbtfilterhook setwindowshookex wh_cbt rtlwindowslayoutcbtfilterhook getcurrentthreadid void cemule app disablertl windows layout if s hrtlwindowslayoutoldcbtfilterhook verify unhook windows hook ex s hrtlwindowslayoutoldcbtfilterhook s hrtlwindowslayoutoldcbtfilterhook null bool winapi pfn set process default layout dword dw flags farproc pfn set process default layout get proc address get module handle t user32 set process default layout if pfn set process default layout pfn set process default layout 0 cemuleapp disablertlwindowslayout s_hrtlwindowslayoutoldcbtfilterhook unhookwindowshookex s_hrtlwindowslayoutoldcbtfilterhook s_hrtlwindowslayoutoldcbtfilterhook pfnsetprocessdefaultlayout dwflags pfnsetprocessdefaultlayout getprocaddress getmodulehandle _t setprocessdefaultlayout pfnsetprocessdefaultlayout pfnsetprocessdefaultlayout operator hicon const return this null null m hicon m_hicon operator hicon const return this null null m hicon m_hicon returns the width of the bar int get width return m iwidth getwidth m_iwidth returns the height of the bar int get height return m iheight getheight m_iheight returns the width of the bar int get width return m iwidth getwidth m_iwidth returns the height of the bar int get height return m iheight getheight m_iheight c bar shader c bar shader uint32 height uint32 width m iwidth width m iheight height m ufilesize uint64 1 m spans set at 0 0 slugfiller speed bar shader m modifiers null m bispreview false cbarshader cbarshader m_iwidth m_iheight m_ufilesize m_spans setat speedbarshader m_modifiers m_bispreview c bar shader c bar shader void delete m modifiers cbarshader cbarshader m_modifiers void c bar shader set width int width if m iwidth width m iwidth width if m ufilesize uint64 0 m dpixelsperbyte double m iwidth uint64 m ufilesize else m dpixelsperbyte 0 0 if m iwidth m dbytesperpixel double m ufilesize m iwidth else m dbytesperpixel 0 0 cbarshader setwidth m_iwidth m_iwidth m_ufilesize m_dpixelsperbyte m_iwidth m_ufilesize m_dpixelsperbyte m_iwidth m_dbytesperpixel m_ufilesize m_iwidth m_dbytesperpixel void c bar shader set height int height if m iheight height m iheight height build modifiers cbarshader setheight m_iheight m_iheight buildmodifiers void c bar shader reset fill 0 cbarshader void c bar shader set file size em file size file size if m ufilesize file size m ufilesize file size if m ufilesize uint64 0 m dpixelsperbyte double m iwidth uint64 m ufilesize else m dpixelsperbyte 0 0 if m iwidth m dbytesperpixel double m ufilesize m iwidth else m dbytesperpixel 0 0 cbarshader setfilesize emfilesize filesize m_ufilesize filesize m_ufilesize filesize m_ufilesize m_dpixelsperbyte m_iwidth m_ufilesize m_dpixelsperbyte m_iwidth m_dbytesperpixel m_ufilesize m_iwidth m_dbytesperpixel void c bar shader fill range uint64 start uint64 end colorref color if end m ufilesize end m ufilesize if start end return slugfiller speed bar shader position endpos m spans find first key after end 1 if endpos m spans get prev endpos else endpos m spans get tail position assert endpos null colorref endcolor m spans get value at endpos endpos m spans set at end endcolor for position pos m spans find first key after start 1 pos endpos position pos1 pos m spans get next pos m spans remove at pos1 m spans get prev endpos if m spans get value at endpos color m spans set at start color slugfiller speed bar shader cbarshader fillrange m_ufilesize m_ufilesize speedbarshader m_spans findfirstkeyafter m_spans getprev m_spans gettailposition m_spans getvalueat m_spans setat m_spans findfirstkeyafter m_spans getnext m_spans removeat m_spans getprev m_spans getvalueat m_spans setat speedbarshader void c bar shader fill colorref color slugfiller speed bar shader m spans remove all m spans set at 0 color m spans set at m ufilesize 0 slugfiller speed bar shader cbarshader speedbarshader m_spans removeall m_spans setat m_spans setat m_ufilesize speedbarshader void c bar shader draw cdc dc int i left int i top bool b flat position pos m spans get head position slugfiller speed bar shader rect rect span rect span top i top rect span bottom i top m iheight rect span right i left sint64 i bytes in one pixel sint64 m dbytesperpixel 0 5f uint64 start 0 bs current start slugfiller speed bar shader colorref color m spans get value at pos m spans get next pos slugfiller speed bar shader while pos null rect span right i left m iwidth slugfiller speed bar shader uint64 u span m spans get key at pos start slugfiller speed bar shader sint64 i pixels sint64 u span m dpixelsperbyte 0 5f if i pixels 0 rect span left rect span right rect span right int i pixels fill rect dc rect span color b flat slugfiller speed bar shader start uint64 i pixels m dbytesperpixel 0 5f else float f red 0 float f green 0 float f blue 0 uint64 i end start i bytes in one pixel uint64 i last start slugfiller speed bar shader do float f weight float min m spans get key at pos i end i last m dpixelsperbyte f red getr value color f weight f green getg value color f weight f blue getb value color f weight if m spans get key at pos i end break i last m spans get key at pos color m spans get value at pos m spans get next pos while pos null slugfiller speed bar shader rect span left rect span right rect span right if g blowcolordesktop fill rect dc rect span color b flat else fill rect dc rect span f red f green f blue b flat start i bytes in one pixel slugfiller speed bar shader while pos null m spans get key at pos start color m spans get value at pos m spans get next pos slugfiller speed bar shader cbarshader ileft itop bflat m_spans getheadposition speedbarshader rectspan rectspan itop rectspan itop m_iheight rectspan ileft ibytesinonepixel m_dbytesperpixel bscurrent speedbarshader m_spans getvalueat m_spans getnext speedbarshader rectspan ileft m_iwidth speedbarshader uspan m_spans getkeyat speedbarshader ipixels uspan m_dpixelsperbyte ipixels rectspan rectspan rectspan ipixels fillrect rectspan bflat speedbarshader ipixels m_dbytesperpixel fred fgreen fblue iend ibytesinonepixel ilast speedbarshader fweight m_spans getkeyat iend ilast m_dpixelsperbyte fred getrvalue fweight fgreen getgvalue fweight fblue getbvalue fweight m_spans getkeyat iend ilast m_spans getkeyat m_spans getvalueat m_spans getnext speedbarshader rectspan rectspan rectspan g_blowcolordesktop fillrect rectspan bflat fillrect rectspan fred fgreen fblue bflat ibytesinonepixel speedbarshader m_spans getkeyat m_spans getvalueat m_spans getnext speedbarshader void c bar shader draw preview cdc dc int i left int i top uint preview level cax2 aqua bar m bispreview true m used3dlevel preview level build modifiers draw dc i left i top preview level 0 m bispreview false cbarshader drawpreview ileft itop previewlevel m_bispreview m_used3dlevel previewlevel buildmodifiers ileft itop previewlevel m_bispreview void c bar shader build modifiers delete m modifiers m modifiers null new may throw an exception if m bispreview m used3dlevel the prefs get3d depth barry new property page slider to control depth of gradient depth must be at least 2 2 gives greatest depth the higher the value the flatter the appearance m modifiers count 1 will always be 1 m modifiers 0 depends on the value of depth int depth 7 m used3dlevel int count half m iheight double pi over depth m pi depth double base pi over depth depth 2 0 1 double increment pi over depth count 1 m modifiers new float count for int i 0 i count i m modifiers i float sin base i increment cbarshader buildmodifiers m_modifiers m_modifiers m_bispreview m_used3dlevel theprefs get3ddepth m_modifiers m_modifiers m_used3dlevel m_iheight pioverdepth m_pi pioverdepth pioverdepth m_modifiers m_modifiers void c bar shader fill rect cdc dc lprect rect span float f red float f green float f blue bool b flat if b flat colorref color rgb int f red 5f int f green 5f int f blue 5f dc fill rect rect span c brush color else if m modifiers null m used3dlevel the prefs get3d depth m bispreview build modifiers rect rect rect span int i top rect top int i bot rect bottom int i max half m iheight for int i 0 i i max i c brush cb new rgb int f red m modifiers i 5f int f green m modifiers i 5f int f blue m modifiers i 5f rect top i top i rect bottom i top i 1 dc fill rect rect cb new rect top i bot i 1 rect bottom i bot i dc fill rect rect cb new cbarshader fillrect rectspan fred fgreen fblue bflat bflat fred fgreen fblue fillrect rectspan cbrush m_modifiers m_used3dlevel theprefs get3ddepth m_bispreview buildmodifiers rectspan itop ibot imax m_iheight imax cbrush cbnew fred m_modifiers fgreen m_modifiers fblue m_modifiers itop itop fillrect cbnew ibot ibot fillrect cbnew void c bar shader fill rect cdc dc lprect rect span colorref color bool b flat if color b flat dc fill rect rect span c brush color else fill rect dc rect span getr value color getg value color getb value color false cbarshader fillrect rectspan bflat bflat fillrect rectspan cbrush fillrect rectspan getrvalue getgvalue getbvalue c part file c part file uint ucat init m category ucat cpartfile cpartfile m_category c part file c part file c search file searchresult uint cat init const c typed ptr list c ptr list kademlia c entry list searchresult get notes for position pos list get head position pos null kademlia c entry entry list get next pos m kadnotes add tail entry copy update file rating comment avail md4cpy m abyfilehash searchresult get file hash for int i 0 i searchresult taglist get count i const c tag p tag searchresult taglist i switch p tag get nameid case ft filename assert p tag is str if p tag is str if get file name is empty set file name p tag get str true break case ft filesize assert p tag is int64 true if p tag is int64 true set file size p tag get int64 break default bool b tag added false if p tag get nameid 0 p tag get name null p tag is str p tag is int static const struct uint8 n name uint8 n type ametatags ft media artist 2 ft media album 2 ft media title 2 ft media length 3 ft media bitrate 3 ft media codec 2 ft filetype 2 ft fileformat 2 for int t 0 t arrsize ametatags t if p tag get type ametatags t n type p tag get nameid ametatags t n name skip string tags with empty string values if p tag is str p tag get str is empty break skip integer tags with 0 values if p tag is int p tag get int 0 break trace t c part file c part file c search file added tag s n p tag get full info dbg get file meta tag name c tag newtag new c tag p tag taglist add newtag b tag added true break if b tag added trace t c part file c part file c search file ignored tag s n p tag get full info dbg get file meta tag name create part file cat m category cat cpartfile cpartfile csearchfile ctypedptrlist cptrlist centry getnotes getheadposition centry getnext m_kadnotes addtail updatefileratingcommentavail m_abyfilehash getfilehash getcount ctag ptag ptag getnameid ft_filename ptag isstr ptag isstr getfilename isempty setfilename ptag getstr ft_filesize ptag isint64 ptag isint64 setfilesize ptag getint64 btagadded ptag getnameid ptag getname ptag isstr ptag isint nname ntype _ametatags ft_media_artist ft_media_album ft_media_title ft_media_length ft_media_bitrate ft_media_codec ft_filetype ft_fileformat _ametatags ptag gettype _ametatags ntype ptag getnameid _ametatags nname ptag isstr ptag getstr isempty ptag isint ptag getint _t cpartfile cpartfile csearchfile ptag getfullinfo dbggetfilemetatagname ctag ctag ptag btagadded btagadded _t cpartfile cpartfile csearchfile ptag getfullinfo dbggetfilemetatagname createpartfile m_category c part file c part file c string edonkeylink uint cat ced2k link p link 0 try p link ced2k link create link from url edonkeylink assert p link 0 ced2k file link p file link p link get file link if p file link 0 throw get res string ids err notafilelink initialize from link p file link cat catch c string error tchar buffer 200 stprintf buffer get res string ids err invalidlink error log error log statusbar get res string ids err linkerror buffer set status ps error delete p link cpartfile cpartfile cstring ced2klink plink plink ced2klink createlinkfromurl _assert plink ced2kfilelink pfilelink plink getfilelink pfilelink getresstring ids_err_notafilelink initializefromlink pfilelink cstring _stprintf getresstring ids_err_invalidlink logerror log_statusbar getresstring ids_err_linkerror setstatus ps_error plink c part file c part file ced2k file link file link uint cat initialize from link file link cat cpartfile cpartfile ced2kfilelink filelink initializefromlink filelink c part file c part file barry ensure all buffered data is written try if m allocatethread null handle h thread m allocatethread m hthread 2 minutes to let the thread finish if wait for single object h thread 120000 wait timeout terminate thread h thread 100 if m hpartfile m hfile invalid handle value flush buffer true catch c file exception e e delete if m hpartfile m hfile invalid handle value commit file and directory entry m hpartfile close update met file with current directory entry save part file for position pos gaplist get head position pos 0 delete gaplist get next pos pos m buffereddata list get head position while pos part file buffered data item m buffereddata list get next pos delete item data delete item cpartfile cpartfile m_allocatethread hthread m_allocatethread m_hthread waitforsingleobject hthread wait_timeout terminatethread hthread m_hpartfile m_hfile invalid_handle_value flushbuffer cfileexception m_hpartfile m_hfile invalid_handle_value m_hpartfile savepartfile getheadposition getnext m_buffereddata_list getheadposition partfilebuffereddata m_buffereddata_list getnext void c part file set file name lpctstr psz file name bool b replace invalid file system chars c known file set file name psz file name b replace invalid file system chars update displayed info true the app emuledlg transferwnd downloadlistctrl update current category view this cpartfile setfilename pszfilename breplaceinvalidfilesystemchars cknownfile setfilename pszfilename breplaceinvalidfilesystemchars updatedisplayedinfo theapp updatecurrentcategoryview c string c part file get temp path const return m fullname left m fullname reverse find t 1 cstring cpartfile gettemppath m_fullname m_fullname reversefind _t em file size c part file get real file size const return get disk file size get file path emfilesize cpartfile getrealfilesize getdiskfilesize getfilepath void c part file get size to transfer and needed space uint64 rui64 size to transfer uint64 rui64 needed space const bool b normal file is normal file for position pos gaplist get head position pos 0 const gap struct cur gap gaplist get next pos uint64 u gap size cur gap end cur gap start rui64 size to transfer u gap size if b normal file cur gap end get file size uint64 1 rui64 needed space u gap size if b normal file rui64 needed space rui64 size to transfer cpartfile getsizetotransferandneededspace rui64sizetotransfer rui64neededspace bnormalfile isnormalfile getheadposition gap_struct cur_gap getnext ugapsize cur_gap cur_gap rui64sizetotransfer ugapsize bnormalfile cur_gap getfilesize rui64neededspace ugapsize bnormalfile rui64neededspace rui64sizetotransfer uint64 c part file get needed space const if m hpartfile get length get file size return 0 shouldn t happen but just in case return get file size m hpartfile get length cpartfile getneededspace m_hpartfile getlength getfilesize getfilesize m_hpartfile getlength void c part file initialize from link ced2k file link file link uint cat init try set file name file link get name true set file size file link get size md4cpy m abyfilehash file link get hash key if the app downloadqueue is file existing m abyfilehash if file link m hashset file link m hashset get length 0 try if load hashset from file file link m hashset true assert hashlist get count 0 add debug log line false t ed2k link s specified with invalid hashset file link get name else hashsetneeded false catch c file exception e tchar sz error max cfexp errormsg e get error message sz error arrsize sz error add debug log line false t error failed to process hashset for ed2k link s s file link get name sz error e delete create part file cat m category cat else set status ps error catch c string error tchar buffer 200 stprintf buffer get res string ids err invalidlink error log error log statusbar get res string ids err linkerror buffer set status ps error cpartfile initializefromlink ced2kfilelink filelink setfilename filelink getname setfilesize filelink getsize m_abyfilehash filelink gethashkey theapp isfileexisting m_abyfilehash filelink m_hashset filelink m_hashset getlength loadhashsetfromfile filelink m_hashset getcount adddebuglogline _t filelink getname cfileexception szerror max_cfexp_errormsg geterrormessage szerror szerror adddebuglogline _t filelink getname szerror createpartfile m_category setstatus ps_error cstring _stprintf getresstring ids_err_invalidlink logerror log_statusbar getresstring ids_err_linkerror setstatus ps_error uint32 c part file process uint32 reducedownload uint icounter in percent if the prefs m idbgheap 2 assert valid this uint n old trans source count get src statistics value ds downloading dword dw cur tick get tick count if buffer size exceeds limit or if not written within time limit flush data if m ntotalbufferdata the prefs get file buffer size dw cur tick m nlastbufferflushtime buffer time limit avoid flushing while copying preview file if m bpreviewing flush buffer datarate 0 calculate datarate set limit etc if icounter 10 uint32 cur datarate for position pos m downloadingsourcelist get head position pos 0 c up down client cur src m downloadingsourcelist get next pos if the prefs m idbgheap 2 assert valid cur src if cur src cur src get download state ds downloading assert cur src socket if cur src socket cur src check download timeout cur datarate cur src calculate download rate datarate cur datarate if reducedownload uint32 limit reducedownload cur datarate 1000 if limit 1000 reducedownload 200 limit 1000 else if limit 200 cur datarate 0 reducedownload 100 limit 200 else if limit 60 cur datarate 600 reducedownload 97 limit 60 else if limit 20 cur datarate 200 reducedownload 93 limit 20 else if limit 1 limit 1 cur src socket set download limit limit if cur src is downloading from peer cache cur src m ppcdownsocket cur src m ppcdownsocket is connected cur src m ppcdownsocket set download limit limit else bool downloadingbefore m anstates ds downloading 0 khaos moved this here otherwise we were setting our permanent variables to 0 every tenth of a second memset m anstates 0 sizeof m anstates memset src stats 0 sizeof src stats memset net stats 0 sizeof net stats uint n count for state for position pos srclist get head position pos null c up down client cur src srclist get next pos if the prefs m idbgheap 2 assert valid cur src begin rewritten refreshing statistics no need for temp vars since it is not multithreaded n count for state cur src get download state special case which is not yet set as downloadstate if n count for state ds onqueue if cur src is remote queue full n count for state ds remotequeuefull this is a performance killer avoid calling is banned for gathering stats if cur src is banned n count for state ds banned if cur src get upload state us banned not as accurate as is banned but way faster and good enough for stats n count for state ds banned if cur src get source from sf server cur src get source from sf passive src stats cur src get source from if cur src get serverip cur src get server port net stats 0 if cur src get kad port net stats 2 if cur src get kad port net stats 1 assert n count for state sizeof m anstates sizeof m anstates 0 m anstates n count for state switch cur src get download state case ds downloading assert cur src socket if cur src socket cur src check download timeout uint32 cur datarate cur src calculate download rate datarate cur datarate if reducedownload cur src get download state ds downloading uint32 limit reducedownload cur datarate 1000 uint32 float reducedownload 100 cur datarate 10 if limit 1000 reducedownload 200 limit 1000 else if limit 200 cur datarate 0 reducedownload 100 limit 200 else if limit 60 cur datarate 600 reducedownload 97 limit 60 else if limit 20 cur datarate 200 reducedownload 93 limit 20 else if limit 1 limit 1 cur src socket set download limit limit if cur src is downloading from peer cache cur src m ppcdownsocket cur src m ppcdownsocket is connected cur src m ppcdownsocket set download limit limit else cur src socket disable download limit if cur src is downloading from peer cache cur src m ppcdownsocket cur src m ppcdownsocket is connected cur src m ppcdownsocket disable download limit break do nothing with this client case ds banned break check if something has changed with our or their id state case ds lowtolowip to mods please stop instantly removing these sources this causes sources to pop in and out creating extra overhead make sure this source is still a lowid client if cur src has lowid make sure we still cannot callback to this client if the app do callback cur src if we are almost maxed on sources slowly remove these client to see if we can find a better source if dw cur tick lastpurgetime sec2ms 30 this get source count get max sources 8 the app downloadqueue remove source cur src lastpurgetime dw cur tick break this should no longer be a lowtolowip cur src set download state ds onqueue break case ds noneededparts to mods please stop instantly removing these sources this causes sources to pop in and out creating extra overhead if dw cur tick lastpurgetime sec2ms 40 lastpurgetime dw cur tick we only delete them if reaching the limit if get source count get max sources 8 the app downloadqueue remove source cur src break doubled reasktime for no needed parts save connections and traffic if cur src get time until reask 0 break cur src swap to another file t a4af for nnp file c part file process true false false null true true zz download manager recheck this client to see if still nnp set to ds none so that we force a tcp reask next time cur src set download state ds none break case ds onqueue to mods please stop instantly removing these sources this causes sources to pop in and out creating extra overhead if cur src is remote queue full if dw cur tick lastpurgetime min2ms 1 get source count get max sources 8 the app downloadqueue remove source cur src lastpurgetime dw cur tick break give up to 1 min for udp to respond if we are within one min of tcp reask do not try if the app is connected cur src get time until reask min2ms 2 cur src get time until reask sec2ms 1 get tick count cur src get last tried to connect time 20 60 1000 zz download manager one resk timestamp for each file cur src udp reask for download case ds connecting case ds toomanyconns case ds toomanyconnskad case ds none case ds waitcallback case ds waitcallbackkad if the app is connected cur src get time until reask 0 get tick count cur src get last tried to connect time 20 60 1000 zz download manager one resk timestamp for each file if cur src ask for download note this may delete the client break i left this break here just as a reminder just in case re rearange things break if downloadingbefore m anstates ds downloading 0 notify status change if get max source per fileudp get source count if the app downloadqueue do kademlia file request kademlia c kademlia get total file kademliatotalfile dw cur tick m lastsearchtimekad kademlia c kademlia is connected the app is connected stopped once we can handle lowid users in kad we remove the second is connected kademlia the app downloadqueue set last kademlia file request if get kad file searchid kademlia c search p search kademlia c search manager prepare lookup kademlia c search file true kademlia cu int128 get file hash if p search if m totalsearcheskad 7 m totalsearcheskad m lastsearchtimekad dw cur tick kademliareasktime m totalsearcheskad set kad file searchid p search get searchid else set kad file searchid 0 else if get kad file searchid kademlia c search manager stop search get kad file searchid true check if we want new sources from server if m blocalsrcreqqueued m lastsearchtime dw cur tick m lastsearchtime serverreasktime the app serverconnect is connected get max source per file soft get source count stopped is large file the app serverconnect get current server null the app serverconnect get current server supports large filestcp m blocalsrcreqqueued true the app downloadqueue send local src request this count if count 3 count 0 update auto down priority update displayed info update completed infos if get src statistics value ds downloading n old trans source count if the app emuledlg transferwnd downloadlistctrl cur tab 0 the app emuledlg transferwnd downloadlistctrl change category 0 else update displayed info true if the pre cpartfile theprefs m_idbgheap assert_valid noldtranssourcecount getsrcstatisticsvalue ds_downloading dwcurtick gettickcount m_ntotalbufferdata theprefs getfilebuffersize dwcurtick m_nlastbufferflushtime buffer_time_limit m_bpreviewing flushbuffer cur_datarate m_downloadingsourcelist getheadposition cupdownclient cur_src m_downloadingsourcelist getnext theprefs m_idbgheap assert_valid cur_src cur_src cur_src getdownloadstate ds_downloading cur_src cur_src cur_src checkdownloadtimeout cur_datarate cur_src calculatedownloadrate cur_datarate cur_datarate cur_datarate cur_datarate cur_datarate cur_src setdownloadlimit cur_src isdownloadingfrompeercache cur_src m_ppcdownsocket cur_src m_ppcdownsocket isconnected cur_src m_ppcdownsocket setdownloadlimit m_anstates ds_downloading m_anstates m_anstates src_stats src_stats net_stats net_stats ncountforstate getheadposition cupdownclient cur_src getnext theprefs m_idbgheap assert_valid cur_src ncountforstate cur_src getdownloadstate ncountforstate ds_onqueue cur_src isremotequeuefull ncountforstate ds_remotequeuefull isbanned cur_src isbanned ncountforstate ds_banned cur_src getuploadstate us_banned isbanned ncountforstate ds_banned cur_src getsourcefrom sf_server cur_src getsourcefrom sf_passive src_stats cur_src getsourcefrom cur_src getserverip cur_src getserverport net_stats cur_src getkadport net_stats cur_src getkadport net_stats ncountforstate m_anstates m_anstates m_anstates ncountforstate cur_src getdownloadstate ds_downloading cur_src cur_src cur_src checkdownloadtimeout cur_datarate cur_src calculatedownloadrate cur_datarate cur_src getdownloadstate ds_downloading cur_datarate cur_datarate cur_datarate cur_datarate cur_datarate cur_src setdownloadlimit cur_src isdownloadingfrompeercache cur_src m_ppcdownsocket cur_src m_ppcdownsocket isconnected cur_src m_ppcdownsocket setdownloadlimit cur_src disabledownloadlimit cur_src isdownloadingfrompeercache cur_src m_ppcdownsocket cur_src m_ppcdownsocket isconnected cur_src m_ppcdownsocket disabledownloadlimit ds_banned ds_lowtolowip cur_src haslowid theapp docallback cur_src dwcurtick getsourcecount getmaxsources theapp removesource cur_src dwcurtick cur_src setdownloadstate ds_onqueue ds_noneededparts dwcurtick dwcurtick getsourcecount getmaxsources theapp removesource cur_src cur_src gettimeuntilreask cur_src swaptoanotherfile _t cpartfile downloadmanager ds_none cur_src setdownloadstate ds_none ds_onqueue cur_src isremotequeuefull dwcurtick getsourcecount getmaxsources theapp removesource cur_src dwcurtick theapp isconnected cur_src gettimeuntilreask cur_src gettimeuntilreask gettickcount cur_src getlasttriedtoconnecttime downloadmanager cur_src udpreaskfordownload ds_connecting ds_toomanyconns ds_toomanyconnskad ds_none ds_waitcallback ds_waitcallbackkad theapp isconnected cur_src gettimeuntilreask gettickcount cur_src getlasttriedtoconnecttime downloadmanager cur_src askfordownload m_anstates ds_downloading notifystatuschange getmaxsourceperfileudp getsourcecount theapp dokademliafilerequest ckademlia gettotalfile dwcurtick m_lastsearchtimekad ckademlia isconnected theapp isconnected isconnected theapp setlastkademliafilerequest getkadfilesearchid csearch psearch csearchmanager preparelookup csearch cuint128 getfilehash psearch m_totalsearcheskad m_totalsearcheskad m_lastsearchtimekad dwcurtick m_totalsearcheskad setkadfilesearchid psearch getsearchid setkadfilesearchid getkadfilesearchid csearchmanager stopsearch getkadfilesearchid m_blocalsrcreqqueued m_lastsearchtime dwcurtick m_lastsearchtime theapp isconnected getmaxsourceperfilesoft getsourcecount islargefile theapp getcurrentserver theapp getcurrentserver supportslargefilestcp m_blocalsrcreqqueued theapp sendlocalsrcrequest updateautodownpriority updatedisplayedinfo updatecompletedinfos getsrcstatisticsvalue ds_downloading noldtranssourcecount theapp curtab theapp changecategory updatedisplayedinfo thepre uint8 c part file load part file lpctstr in directory lpctstr in filename bool getsizeonly bool isnewstyle uint8 version e part file format partmettype pmt unknown c map uint uint gap struct gap struct gap map slugfiller m utransferred 0 m partmetfilename in filename set path in directory m fullname format t s s get path m partmetfilename readfile data form part met file c safe buffered file met file c file exception fexp met if met file open m fullname c file mode read c file os sequential scan c file type binary c file share deny write fexp met c string str error str error format get res string ids err openmet m partmetfilename t tchar sz error max cfexp errormsg if fexp met get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false setvbuf met file m pstream null iofbf 16384 try version met file readu int8 if version partfile version version partfile splittedversion version partfile version largefile met file close if version 83 return import shareaza tempfile in directory in filename getsizeonly log error log statusbar get res string ids err badmetversion m partmetfilename get file name return false isnewstyle version partfile splittedversion partmettype isnewstyle pmt splitted pmt defaultold if isnewstyle uint8 test 4 met file seek 24 c file begin met file read test 0 1 met file read test 1 1 met file read test 2 1 met file read test 3 1 met file seek 1 c file begin if test 0 0 test 1 0 test 2 2 test 3 1 isnewstyle true edonkeys so called old part style partmettype pmt newold if isnewstyle uint32 temp met file read temp 4 if temp 0 0 48 partmets different again load hashset from file met file false else uchar gethash 16 met file seek 2 c file begin load date from file met file met file read gethash 16 md4cpy m abyfilehash gethash else load date from file met file load hashset from file met file false uint tagcount met file readu int32 for uint j 0 j tagcount j c tag newtag new c tag met file false if getsizeonly getsizeonly newtag get nameid ft filesize newtag get nameid ft filename switch newtag get nameid case ft filename if newtag is str log error log statusbar get res string ids err metcorrupt m partmetfilename get file name delete newtag return false if get file name is empty set file name newtag get str delete newtag break case ft lastseencomplete assert newtag is int if newtag is int lastseencomplete newtag get int delete newtag break case ft filesize assert newtag is int64 true if newtag is int64 true set file size newtag get int64 delete newtag break case ft transferred assert newtag is int64 true if newtag is int64 true m utransferred newtag get int64 delete newtag break case ft compression assert newtag is int64 true if newtag is int64 true m ucompressiongain newtag get int64 delete newtag break case ft corrupted assert newtag is int64 if newtag is int64 m ucorruptionloss newtag get int64 delete newtag break case ft filetype assert newtag is str if newtag is str set file type newtag get str delete newtag break case ft category assert newtag is int if newtag is int m category newtag get int delete newtag break case ft maxsources assert newtag is int if newtag is int m umaxsources newtag get int delete newtag break case ft dlpriority assert newtag is int if newtag is int if isnewstyle m idownpriority uint8 newtag get int if m idownpriority pr auto m idownpriority pr high set auto down priority true else if m idownpriority pr low m idownpriority pr normal m idownpriority pr high m idownpriority pr normal set auto down priority false delete newtag break case ft status assert newtag is int if newtag is int paused newtag get int 0 stopped paused delete newtag break case ft ulpriority assert newtag is int if newtag is int if isnewstyle int i up priority newtag get int if i up priority pr auto set up priority pr high false set auto up priority true else if i up priority pr verylow i up priority pr low i up priority pr normal i up priority pr high i up priority pr veryhigh i up priority pr normal set up priority uint8 i up priority false set auto up priority false delete newtag break case ft kadlastpublishsrc assert newtag is int if newtag is int set last publish time kad src newtag get int 0 if get last publish time kad src uint32 time null kademliarepublishtimes there may be a posibility of an older client that saved a random number here this will check for that set last publish time kad src 0 0 delete newtag break case ft kadlastpublishnotes assert newtag is int if newtag is int set last publish time kad notes newtag get int delete newtag break case ft dl preview assert newtag is int if newtag get int 1 set preview prio true else set preview prio false delete newtag break statistics case ft attransferred assert newtag is int if newtag is int statistic alltimetransferred newtag get int delete newtag break case ft attransferredhi assert newtag is int if newtag is int uint32 hi low low uint statistic alltimetransferred hi newtag get int uint64 hi2 hi2 hi hi2 hi2 32 statistic alltimetransferred low hi2 delete newtag break case ft atrequested assert newtag is int if newtag is int statistic alltimerequested newtag get int delete newtag break case ft ataccepted assert newtag is int if newtag is int statistic alltimeaccepted newtag get int delete newtag break old tags as long as they are not needed take the chance to purge them case ft permissions assert newtag is int delete newtag break case ft kadlastpublishkey assert newtag is int delete newtag break case ft dl active time assert newtag is int if newtag is int m ndlactivetime newtag get int delete newtag break case ft corruptedparts assert newtag is str if newtag is str assert corrupted list get head position null c string str corrupted parts newtag get str int i pos 0 c string str part str corrupted parts tokenize t i pos while str part is empty uint u part if stscanf str part t u u part 1 if u part get part count is corrupted part u part corrupted list add tail uint16 u part str part str corrupted parts tokenize t i pos delete newtag break case ft aich hash assert newtag is str caich hash hash if decode base32 newtag get str hash uint caich hash get hash size m paichhashset set master hash hash aich verified else assert false delete newtag break default if newtag get nameid 0 newtag get name 0 ft gapstart newtag get name 0 ft gapend assert newtag is int64 true if newtag is int64 true gap struct gap uint gapkey atoi newtag get name 1 if gap map lookup gapkey gap gap new gap struct gap map set at gapkey gap gap start uint64 1 gap end uint64 1 if newtag get name 0 ft gapstart gap start newtag get int64 if newtag get name 0 ft gapend gap end newtag get int64 1 delete newtag else taglist add newtag cpartfile loadpartfile in_directory in_filename epartfileformat pmt_unknown cmap gap_struct gap_struct gap_map m_utransferred m_partmetfilename in_filename setpath in_directory m_fullname _t getpath m_partmetfilename csafebufferedfile metfile cfileexception fexpmet metfile m_fullname cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite fexpmet cstring strerror strerror getresstring ids_err_openmet m_partmetfilename _t szerror max_cfexp_errormsg fexpmet geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror metfile m_pstream _iofbf metfile readuint8 partfile_version partfile_splittedversion partfile_version_largefile metfile importshareazatempfile in_directory in_filename logerror log_statusbar getresstring ids_err_badmetversion m_partmetfilename getfilename partfile_splittedversion pmt_splitted pmt_defaultold metfile cfile metfile metfile metfile metfile metfile cfile pmt_newold metfile loadhashsetfromfile metfile metfile cfile loaddatefromfile metfile metfile m_abyfilehash loaddatefromfile metfile loadhashsetfromfile metfile metfile readuint32 ctag ctag metfile getnameid ft_filesize getnameid ft_filename getnameid ft_filename isstr logerror log_statusbar getresstring ids_err_metcorrupt m_partmetfilename getfilename getfilename isempty setfilename getstr ft_lastseencomplete isint isint getint ft_filesize isint64 isint64 setfilesize getint64 ft_transferred isint64 isint64 m_utransferred getint64 ft_compression isint64 isint64 m_ucompressiongain getint64 ft_corrupted isint64 isint64 m_ucorruptionloss getint64 ft_filetype isstr isstr setfiletype getstr ft_category isint isint m_category getint ft_maxsources isint isint m_umaxsources getint ft_dlpriority isint isint m_idownpriority getint m_idownpriority pr_auto m_idownpriority pr_high setautodownpriority m_idownpriority pr_low m_idownpriority pr_normal m_idownpriority pr_high m_idownpriority pr_normal setautodownpriority ft_status isint isint getint ft_ulpriority isint isint iuppriority getint iuppriority pr_auto setuppriority pr_high setautouppriority iuppriority pr_verylow iuppriority pr_low iuppriority pr_normal iuppriority pr_high iuppriority pr_veryhigh iuppriority pr_normal setuppriority iuppriority setautouppriority ft_kadlastpublishsrc isint isint setlastpublishtimekadsrc getint getlastpublishtimekadsrc setlastpublishtimekadsrc ft_kadlastpublishnotes isint isint setlastpublishtimekadnotes getint ft_dl_preview isint getint setpreviewprio setpreviewprio ft_attransferred isint isint getint ft_attransferredhi isint isint getint ft_atrequested isint isint getint ft_ataccepted isint isint getint ft_permissions isint ft_kadlastpublishkey isint ft_dl_active_time isint isint m_ndlactivetime getint ft_corruptedparts isstr isstr corrupted_list getheadposition cstring strcorruptedparts getstr ipos cstring strpart strcorruptedparts _t ipos strpart isempty upart _stscanf strpart _t upart upart getpartcount iscorruptedpart upart corrupted_list addtail upart strpart strcorruptedparts _t ipos ft_aich_hash isstr caichhash decodebase32 getstr caichhash gethashsize m_paichhashset setmasterhash aich_verified getnameid getname ft_gapstart getname ft_gapend isint64 isint64 gap_struct getname gap_map gap_struct gap_map setat getname ft_gapstart getint64 getname ft_gapend getint64 uint8 c part file import shareaza tempfile lpctstr in directory lpctstr in filename bool getsizeonly c string fullname fullname format t s s in directory in filename open the file c file sd file c file exception fexp met if sd file open fullname c file mode read c file os sequential scan c file type binary c file share deny write fexp met c string str error str error format get res string ids err openmet in filename t tchar sz error max cfexp errormsg if fexp met get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false setvbuf sd file m pstream null iofbf 16384 try c archive ar sd file c archive load is it a valid shareaza temp file char szid 3 ar read szid 3 if strncmp szid sdl 3 ar close sd file close return pmt unknown get the version int n version ar n version get the file name c string s remote name ar s remote name set file name s remote name get the file size unsigned int64 l size em file size n size if n version 29 ar l size n size l size else ar n size ar l size n size l size set file size n size get the ed2k hash bool bsha1 b tiger bmd5 bed2k trusted bmd5 false bed2k false byte psha1 20 byte p tiger 24 byte pmd5 16 byte ped2k 16 ar bsha1 if bsha1 ar read psha1 sizeof psha1 if n version 31 ar trusted ar b tiger if b tiger ar read p tiger sizeof p tiger if n version 31 ar trusted if n version 22 ar bmd5 if bmd5 ar read pmd5 sizeof pmd5 if n version 31 ar trusted if n version 13 ar bed2k if bed2k ar read ped2k sizeof ped2k if n version 31 ar trusted ar close if bed2k md4cpy m abyfilehash ped2k else log log error get res string ids x shareaza import no hash in filename sd file close return false if getsizeonly sd file close return pmt shareaza now the tricky part longlong base pos sd file get position try to to get the gap list if gotostring sd file n version 29 uchar l size uchar n size n version 29 8 4 search the gap list sd file seek sd file get position n version 29 8 4 c file begin file size c archive ar sd file c archive load bool bad gap list false if n version 29 int64 n total n remaining dword n fragments ar n total n remaining n fragments if n total n remaining int64 begin length for n fragments ar begin length if begin length n total bad gap list true break add gap uint32 begin uint32 begin length 1 else bad gap list true else dword n total n remaining dword n fragments ar n total n remaining n fragments if n total n remaining dword begin length for n fragments ar begin length if begin length n total bad gap list true break add gap begin begin length 1 else bad gap list true if bad gap list while gaplist get count 0 delete gaplist get at gaplist get head position gaplist remove at gaplist get head position log log warning get res string ids x shareaza import gap list corrupt in filename ar close else log log warning get res string ids x shareaza import no gap list in filename sd file seek base pos c file begin not found reset start position try to get the complete hashset if gotostring sd file m abyfilehash 16 search the hashset sd file seek sd file get position 16 4 c file begin list size hash length c archive ar sd file c archive load dword n count ar n count byte pmd4 16 ar read pmd4 sizeof pmd4 read the hash again read the hashset for dword i 0 i n count i uchar curhash new uchar 16 ar read curhash 16 hashlist add curhash uchar checkhash new uchar 16 if hashlist is empty uchar buffer new uchar hashlist get count 16 for int i 0 i hashlist get count i md4cpy buffer i 16 hashlist i create hash buffer hashlist get count 16 checkhash delete buffer if md4cmp pmd4 checkhash for int i 0 i hashlist get size i delete hashlist i hashlist remove all log log warning get res string ids x shareaza import hash set corrupt in filename delete checkhash ar close else log log warning get res string ids x shareaza import no hash set in filename sd file seek base pos c file begin not found reset start position close the file sd file close catch c archive exception error tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err fileerror in filename get file name buffer error delete return false catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err metcorrupt in filename get file name else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err fileerror in filename get file name buffer error delete return false catch log error log statusbar get res string ids err metcorrupt in filename get file name assert 0 return false the part below would be a copy of the c part file load part file so it is smarter to save and reload the file insta dof dougling the whole stuff if save part file return false for int i 0 i hashlist get size i delete hashlist i hashlist remove all while gaplist get count 0 delete gaplist get at gaplist get head position gaplist remove at gaplist get head position return load part file in directory in filename cpartfile importshareazatempfile in_directory in_filename cstring _t in_directory in_filename cfile sdfile cfileexception fexpmet sdfile cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite fexpmet cstring strerror strerror getresstring ids_err_openmet in_filename _t szerror max_cfexp_errormsg fexpmet geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror sdfile m_pstream _iofbf carchive sdfile carchive sdfile pmt_unknown nversion nversion cstring sremotename sremotename setfilename sremotename __int64 lsize emfilesize nsize nversion lsize nsize lsize nsize lsize nsize lsize setfilesize nsize btiger ptiger nversion btiger btiger ptiger ptiger nversion nversion nversion nversion nversion m_abyfilehash log_error getresstring ids_x_shareaza_import_no_hash in_filename sdfile sdfile pmt_shareaza basepos sdfile getposition sdfile nversion lsize nsize nversion sdfile sdfile getposition nversion cfile carchive sdfile carchive badgaplist nversion __int64 ntotal nremaining nfragments ntotal nremaining nfragments ntotal nremaining __int64 nfragments ntotal badgaplist addgap badgaplist ntotal nremaining nfragments ntotal nremaining nfragments ntotal nremaining nfragments ntotal badgaplist addgap badgaplist badgaplist getcount getat getheadposition removeat getheadposition log_warning getresstring ids_x_shareaza_import_gap_list_corrupt in_filename log_warning getresstring ids_x_shareaza_import_no_gap_list in_filename sdfile basepos cfile sdfile m_abyfilehash sdfile sdfile getposition cfile carchive sdfile carchive ncount ncount ncount isempty getcount getcount createhash getcount getsize removeall log_warning getresstring ids_x_shareaza_import_hash_set_corrupt in_filename log_warning getresstring ids_x_shareaza_import_no_hash_set in_filename sdfile basepos cfile sdfile carchiveexception max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_fileerror in_filename getfilename cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_metcorrupt in_filename getfilename max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_fileerror in_filename getfilename logerror log_statusbar getresstring ids_err_metcorrupt in_filename getfilename cpartfile loadpartfile savepartfile getsize removeall getcount getat getheadposition removeat getheadposition loadpartfile in_directory in_filename bool c part file save part file switch status case ps waitingforhash case ps hashing return false search part file c file find ff c string searchpath remove file extension m fullname bool end ff find file searchpath 0 if end ff find next file if end ff is directory log error get res string ids err savemet t s m partmetfilename get file name get res string ids err part fnf return false get filedate c time lwtime try ff get last write time lwtime catch c exception ex ex delete m tlastmodified uint lwtime get time if m tlastmodified 0 m tlastmodified uint 1 m tutclastmodified m tlastmodified if m tutclastmodified 1 if the prefs get verbose add debug log line false t failed to get file date of s s m partmetfilename get file name else adjustntfs daylight file time m tutclastmodified ff get file path ff close c string str tmp file m fullname str tmp file partmet tmp ext save file data to part met file c safe buffered file file c file exception fexp if file open str tmp file c file mode write c file mode create c file type binary c file share deny write fexp c string str error str error format get res string ids err savemet m partmetfilename get file name tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error t s str error return false setvbuf file m pstream null iofbf 16384 try version only use 64 bit tags when partfile version largefile is set file writeu int8 is large file partfile version largefile partfile version date file writeu int32 m tutclastmodified hash file write hash16 m abyfilehash uint parts hashlist get count file writeu int16 uint16 parts for uint x 0 x parts x file write hash16 hashlist x uint u tag count 0 ulong u tag count file pos ulong file get position file writeu int32 u tag count if write opted2kutf8 tag file get file name ft filename u tag count c tag nametag ft filename get file name nametag write tag to file file u tag count c tag sizetag ft filesize m nfilesize is large file sizetag write tag to file file u tag count if m utransferred c tag transtag ft transferred m utransferred is large file transtag write tag to file file u tag count if m ucompressiongain c tag transtag ft compression m ucompressiongain is large file transtag write tag to file file u tag count if m ucorruptionloss c tag transtag ft corrupted m ucorruptionloss is large file transtag write tag to file file u tag count if paused c tag statustag ft status 1 statustag write tag to file file u tag count c tag prioritytag ft dlpriority is auto down priority pr auto m idownpriority prioritytag write tag to file file u tag count c tag ulprioritytag ft ulpriority is auto up priority pr auto get up priority ulprioritytag write tag to file file u tag count if lastseencomplete get time c tag lsctag ft lastseencomplete uint lastseencomplete get time lsctag write tag to file file u tag count if m category c tag categorytag ft category m category categorytag write tag to file file u tag count if get last publish time kad src c tag kad last pub src ft kadlastpublishsrc get last publish time kad src kad last pub src write tag to file file u tag count if get last publish time kad notes c tag kad last pub notes ft kadlastpublishnotes get last publish time kad notes kad last pub notes write tag to file file u tag count if get dl active time c tag tag dl active time ft dl active time get dl active time tag dl active time write tag to file file u tag count if get preview prio c tag tag dl preview ft dl preview get preview prio 1 0 tag dl preview write tag to file file u tag count statistics if statistic get all time transferred c tag attag1 ft attransferred uint32 statistic get all time transferred attag1 write tag to file file u tag count c tag attag4 ft attransferredhi uint32 statistic get all time transferred 32 attag4 write tag to file file u tag count if statistic get all time requests c tag attag2 ft atrequested statistic get all time requests attag2 write tag to file file u tag count if statistic get all time accepts c tag attag3 ft ataccepted statistic get all time accepts attag3 write tag to file file u tag count if m umaxsources c tag attag3 ft maxsources m umaxsources attag3 write tag to file file u tag count currupt part infos position pos corrupted part corrupted list get head position if pos corrupted part c string str corrupted parts while pos corrupted part uint u corrupted part corrupted list get next pos corrupted part if str corrupted parts is empty str corrupted parts t str corrupted parts append format t u uint u corrupted part assert str corrupted parts is empty c tag tag corrupted parts ft corruptedparts str corrupted parts tag corrupted parts write tag to file file u tag count aich filehash if m paichhashset has valid master hash m paichhashset get status aich verified c tag aichtag ft aich hash m paichhashset get master hash get string aichtag write tag to file file u tag count for int j 0 j taglist get count j if taglist j is str taglist j is int taglist j write tag to file file u tag count gaps char namebuffer 10 char number namebuffer 1 uint i pos 0 for position pos gaplist get head position pos 0 gap struct gap gaplist get next pos itoa i pos number 10 namebuffer 0 ft gapstart c tag gapstarttag namebuffer gap start is large file gapstarttag write tag to file file u tag count gap start first missing byte but gap ends first non missing byte in edonkey but i think its easier to user the real limits namebuffer 0 ft gapend c tag gapendtag namebuffer gap end 1 is large file gapendtag write tag to file file u tag count i pos file seek u tag count file pos c file begin file writeu int32 u tag count file seek to end if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush flush file stream buffers to disk buffers if commit fileno file m pstream 0 commit disk buffers to disk afx throw file exception c file exception hardio get last error file get file name file close catch c file exception error c string str error str error format get res string ids err savemet m partmetfilename get file name tchar sz error max cfexp errormsg if error get error message sz error arrsize sz error str error t str error sz error log error t s str error error delete remove the partially written or otherwise damaged temporary file file abort need to close the file before removing it call abort instead of close just to avoid an assert void tremove str tmp file return false after successfully writing the temporary part met file if tremove m fullname 0 errno enoent if the prefs get verbose debug log error t failed to remove s s m fullname strerror errno if trename str tmp file m fullname 0 int i errno errno if the prefs get verbose debug log error t failed to move temporary part met file s to s s str tmp file m fullname strerror i errno c string str error str error format get res string ids err savemet m partmetfilename get file name str error t str error strerror i errno log error t s str error return false create a backup of the successfully written part met file c string bak name m fullname bak name append partmet bak ext if copy file m fullname bak name false if the prefs get verbose debug log error t failed to create backup of s s s m fullname get file name get error message get last error return true cpartfile savepartfile ps_waitingforhash ps_hashing cfilefind cstring removefileextension m_fullname findfile findnextfile isdirectory logerror getresstring ids_err_savemet _t m_partmetfilename getfilename getresstring ids_err_part_fnf ctime getlastwritetime cexception m_tlastmodified gettime m_tlastmodified m_tlastmodified m_tutclastmodified m_tlastmodified m_tutclastmodified theprefs getverbose adddebuglogline _t m_partmetfilename getfilename adjustntfsdaylightfiletime m_tutclastmodified getfilepath cstring strtmpfile m_fullname strtmpfile partmet_tmp_ext csafebufferedfile cfileexception strtmpfile cfile modewrite cfile modecreate cfile typebinary cfile sharedenywrite cstring strerror strerror getresstring ids_err_savemet m_partmetfilename getfilename szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror _t strerror m_pstream _iofbf partfile_version_largefile writeuint8 islargefile partfile_version_largefile partfile_version writeuint32 m_tutclastmodified writehash16 m_abyfilehash getcount writeuint16 writehash16 utagcount utagcountfilepos getposition writeuint32 utagcount writeopted2kutf8tag getfilename ft_filename utagcount ctag ft_filename getfilename writetagtofile utagcount ctag ft_filesize m_nfilesize islargefile writetagtofile utagcount m_utransferred ctag ft_transferred m_utransferred islargefile writetagtofile utagcount m_ucompressiongain ctag ft_compression m_ucompressiongain islargefile writetagtofile utagcount m_ucorruptionloss ctag ft_corrupted m_ucorruptionloss islargefile writetagtofile utagcount ctag ft_status writetagtofile utagcount ctag ft_dlpriority isautodownpriority pr_auto m_idownpriority writetagtofile utagcount ctag ft_ulpriority isautouppriority pr_auto getuppriority writetagtofile utagcount gettime ctag ft_lastseencomplete gettime writetagtofile utagcount m_category ctag ft_category m_category writetagtofile utagcount getlastpublishtimekadsrc ctag kadlastpubsrc ft_kadlastpublishsrc getlastpublishtimekadsrc kadlastpubsrc writetagtofile utagcount getlastpublishtimekadnotes ctag kadlastpubnotes ft_kadlastpublishnotes getlastpublishtimekadnotes kadlastpubnotes writetagtofile utagcount getdlactivetime ctag tagdlactivetime ft_dl_active_time getdlactivetime tagdlactivetime writetagtofile utagcount getpreviewprio ctag tagdlpreview ft_dl_preview getpreviewprio tagdlpreview writetagtofile utagcount getalltimetransferred ctag ft_attransferred getalltimetransferred writetagtofile utagcount ctag ft_attransferredhi getalltimetransferred writetagtofile utagcount getalltimerequests ctag ft_atrequested getalltimerequests writetagtofile utagcount getalltimeaccepts ctag ft_ataccepted getalltimeaccepts writetagtofile utagcount m_umaxsources ctag ft_maxsources m_umaxsources writetagtofile utagcount poscorruptedpart corrupted_list getheadposition poscorruptedpart cstring strcorruptedparts poscorruptedpart ucorruptedpart corrupted_list getnext poscorruptedpart strcorruptedparts isempty strcorruptedparts _t strcorruptedparts appendformat _t ucorruptedpart strcorruptedparts isempty ctag tagcorruptedparts ft_corruptedparts strcorruptedparts tagcorruptedparts writetagtofile utagcount m_paichhashset hasvalidmasterhash m_paichhashset getstatus aich_verified ctag ft_aich_hash m_paichhashset getmasterhash getstring writetagtofile utagcount getcount isstr isint writetagtofile utagcount i_pos getheadposition gap_struct getnext i_pos ft_gapstart ctag islargefile writetagtofile utagcount ft_gapend ctag islargefile writetagtofile utagcount i_pos utagcountfilepos cfile writeuint32 utagcount seektoend theprefs getcommitfiles theprefs getcommitfiles theapp isrunning _commit _fileno m_pstream afxthrowfileexception cfileexception getlasterror getfilename cfileexception cstring strerror strerror getresstring ids_err_savemet m_partmetfilename getfilename szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror _t strerror _tremove strtmpfile _tremove m_fullname theprefs getverbose debuglogerror _t m_fullname _trename strtmpfile m_fullname ierrno theprefs getverbose debuglogerror _t strtmpfile m_fullname ierrno cstring strerror strerror getresstring ids_err_savemet m_partmetfilename getfilename strerror _t strerror ierrno logerror _t strerror cstring bakname m_fullname bakname partmet_bak_ext copyfile m_fullname bakname theprefs getverbose debuglogerror _t m_fullname getfilename geterrormessage getlasterror void c part file part file hash finished c known file result newdate true bool errorfound false if geted2k part hash count 0 get hash count 0 assert is complete 0 m nfilesize uint64 1 true is complete 0 m nfilesize uint64 1 false if is complete 0 m nfilesize uint64 1 false if md4cmp result get file hash get file hash log warning get res string ids err foundcorruption 1 get file name add gap 0 m nfilesize uint64 1 errorfound true else if geted2k part hash count get hash count assert result geted2k part hash count geted2k part hash count if set hashset result get hashset hashsetneeded false else for uint i 0 i uint hashlist get size i assert is complete uint64 i partsize uint64 i 1 partsize 1 true is complete uint64 i partsize uint64 i 1 partsize 1 false if i get part count is complete uint64 i partsize uint64 i 1 partsize 1 false if result get part hash i md4cmp result get part hash i get part hash i log warning get res string ids err foundcorruption i 1 get file name add gap uint64 i partsize uint64 uint64 i 1 partsize 1 m nfilesize uint64 m nfilesize 1 uint64 i 1 partsize 1 errorfound true if errorfound result getaich hashset get status aich hashsetcomplete status ps completing delete m paichhashset m paichhashset result getaich hashset result setaich hashset null m paichhashset set owner this else if status ps completing add debug log line false t failed to store new aich hashset for completed file s get file name delete result if errorfound if status ps completing if the prefs get verbose add debug log line true t completed file hashing for s get file name if the app sharedfiles get file byid get file hash null the app sharedfiles safe addk file this complete file true return else add log line false get res string ids hashingdone get file name else set status ps ready if the prefs get verbose debug log error log statusbar t file hashing failed for s get file name save part file return if the prefs get verbose add debug log line true t completed file hashing for s get file name set status ps ready save part file the app sharedfiles safe addk file this cpartfile partfilehashfinished cknownfile geted2kparthashcount gethashcount iscomplete m_nfilesize iscomplete m_nfilesize iscomplete m_nfilesize getfilehash getfilehash logwarning getresstring ids_err_foundcorruption getfilename addgap m_nfilesize geted2kparthashcount gethashcount geted2kparthashcount geted2kparthashcount sethashset gethashset getsize iscomplete iscomplete getpartcount iscomplete getparthash getparthash getparthash logwarning getresstring ids_err_foundcorruption getfilename addgap m_nfilesize m_nfilesize getaichhashset getstatus aich_hashsetcomplete ps_completing m_paichhashset m_paichhashset getaichhashset setaichhashset m_paichhashset setowner ps_completing adddebuglogline _t getfilename ps_completing theprefs getverbose adddebuglogline _t getfilename theapp getfilebyid getfilehash theapp safeaddkfile completefile addlogline getresstring ids_hashingdone getfilename setstatus ps_ready theprefs getverbose debuglogerror log_statusbar _t getfilename savepartfile theprefs getverbose adddebuglogline _t getfilename setstatus ps_ready savepartfile theapp safeaddkfile else uchar hashresult 16 m hpartfile seek longlong partsize uint64 partnumber 0 uint32 length partsize if ulonglong partsize uint64 partnumber 1 m hpartfile get length length uint m hpartfile get length ulonglong partsize uint64 partnumber assert length partsize create hash m hpartfile length hashresult null if get part count 1 get file size uint64 partsize if md4cmp hashresult get part hash partnumber return false else return true else if md4cmp hashresult m abyfilehash return false else return true m_hpartfile m_hpartfile getlength m_hpartfile getlength createhash m_hpartfile getpartcount getfilesize getparthash m_abyfilehash void c part file add gap uint64 start uint64 end assert start end position pos1 pos2 for pos1 gaplist get head position pos2 pos1 null gap struct cur gap gaplist get next pos1 if cur gap start start cur gap end end this gap is inside the new gap delete gaplist remove at pos2 delete cur gap else if cur gap start start cur gap start end a part of this gap is in the new gap extend limit and delete end cur gap end gaplist remove at pos2 delete cur gap else if cur gap end end cur gap end start a part of this gap is in the new gap extend limit and delete start cur gap start gaplist remove at pos2 delete cur gap else if start cur gap start end cur gap end new gap is already inside this gap return return gap struct new gap new gap struct new gap start start new gap end end gaplist add tail new gap update displayed info newdate true cpartfile addgap getheadposition gap_struct cur_gap getnext cur_gap cur_gap removeat cur_gap cur_gap cur_gap cur_gap removeat cur_gap cur_gap cur_gap cur_gap removeat cur_gap cur_gap cur_gap gap_struct new_gap gap_struct new_gap new_gap addtail new_gap updatedisplayedinfo void c part file fill gap uint64 start uint64 end assert start end position pos1 pos2 for pos1 gaplist get head position pos2 pos1 null gap struct cur gap gaplist get next pos1 if cur gap start start cur gap end end our part fills this gap completly gaplist remove at pos2 delete cur gap else if cur gap start start cur gap start end a part of this gap is in the part set limit cur gap start end 1 else if cur gap end end cur gap end start a part of this gap is in the part set limit cur gap end start 1 else if start cur gap start end cur gap end uint64 buffer cur gap end cur gap end start 1 cur gap new gap struct cur gap start end 1 cur gap end buffer gaplist insert after pos1 cur gap break lord ki ron update completed infos update displayed info newdate true cpartfile fillgap getheadposition gap_struct cur_gap getnext cur_gap cur_gap removeat cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap gap_struct cur_gap cur_gap insertafter cur_gap kiron updatecompletedinfos updatedisplayedinfo void c part file draw status bar cdc dc lpcrect rect bool b flat const colorref cr progress colorref cr progress bk colorref cr have colorref cr pending colorref cr missing e part file status e virtual state get status bool notgray e virtual state ps empty e virtual state ps ready if g blowcolordesktop b flat true use straight windows colors cr progress rgb 0 255 0 cr progress bk rgb 192 192 192 if notgray cr missing rgb 255 0 0 cr have rgb 0 0 0 cr pending rgb 255 255 0 else cr missing rgb 128 0 0 cr have rgb 128 128 128 cr pending rgb 128 128 0 else if b flat cr progress rgb 0 150 0 else cr progress rgb 0 224 0 cr progress bk rgb 224 224 224 if notgray cr missing rgb 255 0 0 if b flat cr have rgb 0 0 0 cr pending rgb 255 208 0 else cr have rgb 104 104 104 cr pending rgb 255 208 0 else cr missing rgb 191 64 64 if b flat cr have rgb 64 64 64 cr pending rgb 191 168 64 else cr have rgb 116 116 116 cr pending rgb 191 168 64 s chunkbar set height rect bottom rect top s chunkbar set width rect right rect left s chunkbar set file size m nfilesize s chunkbar fill cr have if status ps complete status ps completing s chunkbar fill range 0 m nfilesize cr progress s chunkbar draw dc rect left rect top b flat percentcompleted 100 0f completedsize m nfilesize else if the app m brushbackwarddiagonal m hobject e virtual state ps insufficient status ps error int i old bk color dc set bk color rgb 255 255 0 dc fill rect rect the app m brushbackwarddiagonal dc set bk color i old bk color update completed infos else red gaps uint64 allgaps 0 for position pos gaplist get head position pos 0 const gap struct cur gap gaplist get next pos allgaps cur gap end cur gap start 1 bool gapdone false uint64 gapstart cur gap start uint64 gapend cur gap end for uint i 0 i get part count i if gapstart uint64 i partsize gapstart uint64 i 1 partsize 1 is in this part if gapend uint64 i 1 partsize 1 gapdone true else gapend uint64 i 1 partsize 1 and next part paint colorref color if m srcpartfrequency get count int ptr i m srcpartfrequency uint16 i if g blowcolordesktop if notgray if m srcpartfrequency uint16 i 5 color rgb 0 255 255 else color rgb 0 0 255 else color rgb 0 128 128 else if notgray color rgb 0 210 22 m srcpartfrequency uint16 i 1 0 0 210 22 m srcpartfrequency uint16 i 1 255 else color rgb 64 169 11 m srcpartfrequency uint16 i 1 64 64 169 11 m srcpartfrequency uint16 i 1 191 else color cr missing s chunkbar fill range gapstart gapend 1 color if gapdone finished break else gapstart gapend 1 gapend cur gap end yellow pending parts for position pos requestedblocks list get head position pos 0 const requested block struct block requestedblocks list get next pos s chunkbar fill range block start offset block transferred block end offset 1 cr pending s chunkbar draw dc rect left rect top b flat green progress float blockpixel float rect right rect left float m nfilesize rect gaprect gaprect top rect top gaprect bottom gaprect top progress height gaprect left rect left if b flat s loadbar set width int uint64 m nfilesize allgaps blockpixel 0 5f s loadbar fill cr progress s loadbar draw dc gaprect left gaprect top false else gaprect right rect left uint32 uint64 m nfilesize allgaps blockpixel 0 5f dc fill rect gaprect c brush cr progress draw gray progress only if flat gaprect left gaprect right gaprect right rect right dc fill rect gaprect c brush cr progress bk update completed infos allgaps additionally show any file op progress needed for ps completing and ps waitingforhash if get file op pfop none float blockpixel float rect right rect left 100 0f c rect rc file op progress rc file op progress top rect top rc file op progress bottom rc file op progress top progress height rc file op progress left rect left if b flat s loadbar set width int get file op progress blockpixel 0 5f s loadbar fill rgb 255 208 0 s loadbar draw dc rc file op progress left rc file op progress top false else rc file op progress right rc file op progress left uint get file op progress blockpixel 0 5f dc fill rect rc file op progress c brush rgb 255 208 0 rc file op progress left rc file op progress right rc file op progress right rect right dc fill rect rc file op progress c brush cr progress bk cpartfile drawstatusbar bflat crprogress crprogressbk crhave crpending crmissing epartfilestatus evirtualstate getstatus evirtualstate ps_empty evirtualstate ps_ready g_blowcolordesktop bflat crprogress crprogressbk crmissing crhave crpending crmissing crhave crpending bflat crprogress crprogress crprogressbk crmissing bflat crhave crpending crhave crpending crmissing bflat crhave crpending crhave crpending s_chunkbar setheight s_chunkbar setwidth s_chunkbar setfilesize m_nfilesize s_chunkbar crhave ps_complete ps_completing s_chunkbar fillrange m_nfilesize crprogress s_chunkbar bflat m_nfilesize theapp m_brushbackwarddiagonal m_hobject evirtualstate ps_insufficient ps_error ioldbkcolor setbkcolor fillrect theapp m_brushbackwarddiagonal setbkcolor ioldbkcolor updatecompletedinfos getheadposition gap_struct cur_gap getnext cur_gap cur_gap cur_gap cur_gap getpartcount m_srcpartfrequency getcount int_ptr m_srcpartfrequency g_blowcolordesktop m_srcpartfrequency m_srcpartfrequency m_srcpartfrequency m_srcpartfrequency m_srcpartfrequency crmissing s_chunkbar fillrange cur_gap requestedblocks_list getheadposition requested_block_struct requestedblocks_list getnext s_chunkbar fillrange startoffset endoffset crpending s_chunkbar bflat m_nfilesize progress_height bflat s_loadbar setwidth m_nfilesize s_loadbar crprogress s_loadbar m_nfilesize fillrect cbrush crprogress fillrect cbrush crprogressbk updatecompletedinfos ps_completing ps_waitingforhash getfileop pfop_none crect rcfileopprogress rcfileopprogress rcfileopprogress rcfileopprogress progress_height rcfileopprogress bflat s_loadbar setwidth getfileopprogress s_loadbar s_loadbar rcfileopprogress rcfileopprogress rcfileopprogress rcfileopprogress getfileopprogress fillrect rcfileopprogress cbrush rcfileopprogress rcfileopprogress rcfileopprogress fillrect rcfileopprogress cbrush crprogressbk void c part file draw share status bar cdc dc lpcrect rect bool onlygreyrect bool b flat const if is part file c known file draw share status bar dc rect onlygreyrect b flat return const colorref cr not shared rgb 224 224 224 s chunkbar set file size get file size s chunkbar set height rect bottom rect top s chunkbar set width rect right rect left s chunkbar fill cr not shared if onlygreyrect const colorref cr missing rgb 255 0 0 colorref cr progress colorref cr have colorref cr pending colorref cr noone asked if b flat cr progress rgb 0 150 0 cr have rgb 0 0 0 cr pending rgb 255 208 0 cr noone asked rgb 0 0 0 else cr progress rgb 0 224 0 cr have rgb 104 104 104 cr pending rgb 255 208 0 cr noone asked rgb 104 104 104 for uint i 0 i get part count i if is complete uint64 i partsize uint64 i 1 partsize 1 true if get status ps paused m clientuploadlist get size 0 m ncompletesourcescounthi 0 uint32 frequency if get status ps paused m srcpartfrequency is empty frequency m srcpartfrequency i else if m availpartfrequency is empty frequency max m availpartfrequency i m ncompletesourcescountlo else frequency m ncompletesourcescountlo if frequency 0 colorref color rgb 0 22 frequency 1 210 0 210 22 frequency 1 255 s chunkbar fill range partsize uint64 i partsize uint64 i 1 color else s chunkbar fill range partsize uint64 i partsize uint64 i 1 cr missing else s chunkbar fill range partsize uint64 i partsize uint64 i 1 cr noone asked s chunkbar draw dc rect left rect top b flat cpartfile drawsharestatusbar bflat ispartfile cknownfile drawsharestatusbar bflat crnotshared s_chunkbar setfilesize getfilesize s_chunkbar setheight s_chunkbar setwidth s_chunkbar crnotshared crmissing crprogress crhave crpending crnooneasked bflat crprogress crhave crpending crnooneasked crprogress crhave crpending crnooneasked getpartcount iscomplete getstatus ps_paused m_clientuploadlist getsize m_ncompletesourcescounthi getstatus ps_paused m_srcpartfrequency isempty m_srcpartfrequency m_availpartfrequency isempty m_availpartfrequency m_ncompletesourcescountlo m_ncompletesourcescountlo s_chunkbar fillrange s_chunkbar fillrange crmissing s_chunkbar fillrange crnooneasked s_chunkbar bflat bool c part file is complete uint64 start uint64 end bool b ignore buffered data const assert start end if end m nfilesize end m nfilesize uint64 1 for position pos gaplist get head position pos 0 const gap struct cur gap gaplist get next pos if cur gap start start cur gap end end cur gap start start cur gap start end cur gap end end cur gap end start start cur gap start end cur gap end return false if b ignore buffered data for position pos m buffereddata list get head position pos 0 const part file buffered data cur gap m buffereddata list get next pos if cur gap start start cur gap end end cur gap start start cur gap start end cur gap end end cur gap end start start cur gap start end cur gap end return false return true cpartfile iscomplete bignorebuffereddata m_nfilesize m_nfilesize getheadposition gap_struct cur_gap getnext cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap bignorebuffereddata m_buffereddata_list getheadposition partfilebuffereddata cur_gap m_buffereddata_list getnext cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap cur_gap bool c part file is pure gap uint64 start uint64 end const assert start end if end m nfilesize end m nfilesize uint64 1 for position pos gaplist get head position pos 0 const gap struct cur gap gaplist get next pos if start cur gap start end cur gap end return true return false cpartfile ispuregap m_nfilesize m_nfilesize getheadposition gap_struct cur_gap getnext cur_gap cur_gap bool c part file is already requested uint64 start uint64 end const assert start end for position pos requestedblocks list get head position pos 0 const requested block struct cur block requestedblocks list get next pos if start cur block end offset end cur block start offset return true return false cpartfile isalreadyrequested requestedblocks_list getheadposition requested_block_struct cur_block requestedblocks_list getnext cur_block endoffset cur_block startoffset bool c part file shrink to avoid already requested uint64 start uint64 end const assert start end ifdef debug uint64 start orig start uint64 end orig end endif for position pos requestedblocks list get head position pos 0 const requested block struct cur block requestedblocks list get next pos if start cur block end offset end cur block start offset if start cur block start offset end cur block start offset 1 if start end return false else if end cur block end offset start cur block end offset 1 if start end return false else return false assert start start orig start end orig assert end start orig end end orig return true cpartfile shrinktoavoidalreadyrequested _debug startorig endorig requestedblocks_list getheadposition requested_block_struct cur_block requestedblocks_list getnext cur_block endoffset cur_block startoffset cur_block startoffset cur_block startoffset cur_block endoffset cur_block endoffset startorig endorig startorig endorig bool c part file is corrupted part uint partnumber const return corrupted list find uint16 partnumber null cpartfile iscorruptedpart corrupted_list uint64 c part file get total gap size in range uint64 u range start uint64 u range end const assert u range start u range end uint64 u total gap size 0 if u range end m nfilesize u range end m nfilesize uint64 1 position pos gaplist get head position while pos const gap struct p gap gaplist get next pos if p gap start u range start p gap end u range end u total gap size u range end u range start 1 break if p gap start u range start p gap start u range end uint64 u end p gap end u range end u range end p gap end u total gap size u end p gap start 1 else if p gap end u range start p gap end u range end u total gap size p gap end u range start 1 assert u total gap size u range end u range start 1 return u total gap size cpartfile gettotalgapsizeinrange urangestart urangeend urangestart urangeend utotalgapsize urangeend m_nfilesize urangeend m_nfilesize getheadposition gap_struct pgap getnext pgap urangestart pgap urangeend utotalgapsize urangeend urangestart pgap urangestart pgap urangeend uend pgap urangeend urangeend pgap utotalgapsize uend pgap pgap urangestart pgap urangeend utotalgapsize pgap urangestart utotalgapsize urangeend urangestart utotalgapsize uint64 c part file get total gap size in part uint u part const uint64 u range start uint64 u part partsize uint64 u range end u range start partsize 1 if u range end m nfilesize u range end m nfilesize return get total gap size in range u range start u range end cpartfile gettotalgapsizeinpart upart urangestart upart urangeend urangestart urangeend m_nfilesize urangeend m_nfilesize gettotalgapsizeinrange urangestart urangeend void c part file update completed infos uint64 allgaps 0 for position pos gaplist get head position pos 0 const gap struct cur gap gaplist get next pos allgaps cur gap end cur gap start 1 update completed infos allgaps cpartfile updatecompletedinfos getheadposition gap_struct cur_gap getnext cur_gap cur_gap updatecompletedinfos void c part file update completed infos uint64 u total gaps if u total gaps m nfilesize assert 0 u total gaps m nfilesize if gaplist get count requestedblocks list get count percentcompleted is only used in gui round down to avoid showing 100 in case we actually have only 99 9 percentcompleted float floor 1 0 double u total gaps uint64 m nfilesize 1000 0 10 0 completedsize m nfilesize u total gaps else percentcompleted 100 0f completedsize m nfilesize cpartfile updatecompletedinfos utotalgaps utotalgaps m_nfilesize utotalgaps m_nfilesize getcount requestedblocks_list getcount utotalgaps m_nfilesize m_nfilesize utotalgaps m_nfilesize void c part file update parts info if is part file c known file update parts info return cache part count uint partcount get part count bool flag time null m ncompletesourcestime 0 reset part counters if uint m srcpartfrequency get size partcount m srcpartfrequency set size partcount for uint i 0 i partcount i m srcpartfrequency i 0 c array uint16 uint16 count if flag count set size 0 srclist get size for position pos srclist get head position pos 0 c up down client cur src srclist get next pos if cur src get part status for uint i 0 i partcount i if cur src is part available i m srcpartfrequency i 1 if flag count add cur src get up complete sources count if flag m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi 0 for uint i 0 i partcount i if i m ncompletesourcescount m srcpartfrequency i else if m ncompletesourcescount m srcpartfrequency i m ncompletesourcescount m srcpartfrequency i count add m ncompletesourcescount int n count get size if n 0 slugfiller heapsort completesrc int r for r n 2 r heap sort count r n 1 for r n r uint16 t count r count r count 0 count 0 t heap sort count 0 r 1 slugfiller heapsort completesrc calculate range int i n 1 n 2 int j n 3 2 n 3 4 int k n 7 3 n 7 8 when still a part file adjust your guesses by 20 to what you see not many sources so just use what you see if n 5 m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescount m ncompletesourcescounthi m ncompletesourcescount for low guess and normal guess count if we see more sources then the guessed low and normal use what we see if we see less sources then the guessed low adjust network accounts for 80 we account for 20 with what we see and make sure we are still above the normal for high guess adjust 80 network and 20 what we see else if n 20 if count get at i m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescount else m ncompletesourcescountlo uint16 float count get at i 8 float m ncompletesourcescount 2 m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi uint16 float count get at j 8 float m ncompletesourcescount 2 if m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcescounthi m ncompletesourcescount else many sources for low guess use what we see for normal guess adjust network accounts for 80 we account for 20 with what we see and make sure we are still above the low for high guess adjust network accounts for 80 we account for 20 with what we see and make sure we are still above the normal m ncompletesourcescountlo m ncompletesourcescount m ncompletesourcescount uint16 float count get at j 8 float m ncompletesourcescount 2 if m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi uint16 float count get at k 8 float m ncompletesourcescount 2 if m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcestime time null 60 update displayed info cpartfile updatepartsinfo ispartfile cknownfile updatepartsinfo getpartcount m_ncompletesourcestime m_srcpartfrequency getsize m_srcpartfrequency setsize m_srcpartfrequency carray setsize getsize getheadposition cupdownclient cur_src getnext cur_src getpartstatus cur_src ispartavailable m_srcpartfrequency cur_src getupcompletesourcescount m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi m_ncompletesourcescount m_srcpartfrequency m_ncompletesourcescount m_srcpartfrequency m_ncompletesourcescount m_srcpartfrequency m_ncompletesourcescount getsize heapsortcompletesrc heapsort heapsort heapsortcompletesrc m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount getat m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescountlo getat m_ncompletesourcescount m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi getat m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescount getat m_ncompletesourcescount m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi getat m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcestime updatedisplayedinfo uint16 count const the purpose of this function is to return a list of blocks 180kb to download to avoid a prematurely stop of the downloading all blocks that are requested from the same source must be located within the same chunk part 9mb the selection of the chunk to download is one of the critical parts of the edonkey network the selection algorithm must insure the best spreading of files the selection is based on 4 criteria 1 frequency of the chunk availability very rare chunks must be downloaded as quickly as possible to become a new available source 2 parts used for preview first last chunk preview or check a file e g movie mp3 3 request state downloading in process try to ask each source for another chunk spread the requests between all sources 4 completion shortest to complete partially retrieved chunks should be completed before starting to download other one the frequency criterion defines three zones very rare 10 rare 50 and common 30 inside each zone the criteria have a specific weight used to calculate the priority of chunks the chunk s with the highest priority highest 0 lowest 0xffff is are selected first very rare preview rare common 0 0 pt 10 10000 pt 50 20000 pt 100 1 frequency 25 frequency pt 2 preview 1 pt preview set to 10000 pt 3 request download in progress 20000 pt 4a completion 0 100 25 75 100 0 pt req completion 4b req completion unrolled the priority scale is 0 xxxx unrequested and requested very rare chunks 10000 1xxxx unrequested rare chunks unrequested preview chunks 20000 2xxxx unrequested common chunks priority to the most complete 30000 3xxxx requested rare chunks requested preview chunks 40000 4xxxx requested common chunks priority to the least complete this algorithm usually selects first the rarest chunk s however partially complete chunk s that is are close to completion may overtake the priority priority inversion for the common chuncks the algorithm tries to spread the dowload between the sources check input parameters if count 0 return false if sender get part status null return false define and create the list of the chunks to download const uint16 part count get part count c list chunk chunks list part count main loop uint16 new block count 0 while new block count count create a request block stucture if a chunk has been previously selected if sender m lastpartasked uint16 1 requested block struct p block new requested block struct if get next empty block in part sender m lastpartasked p block true keep a track of all pending requested blocks requestedblocks list add tail p block update list of blocks to return newblocks new block count p block skip end of loop cpu load continue else all blocks for this chunk have been already requested delete p block try to select another chunk sender m lastpartasked uint16 1 check if a new chunk must be selected e g download starting previous chunk complete if sender m lastpartasked uint16 1 quantify all chunks create list of chunks to download this is done only one time and only if it is necessary cpu load if chunks list is empty true indentify the locally missing part s that this source has for uint16 i 0 i part count i if sender is part available i true get next empty block in part i null true create a new entry for this chunk and add it to the list chunk new entry new entry part i new entry frequency m srcpartfrequency i chunks list add tail new entry check if any block s could be downloaded if chunks list is empty true break exit main loop while define the bounds of the three zones very rare rare more depending on available sources uint8 modif 10 if get source count 800 modif 2 else if get source count 200 modif 5 uint16 limit uint16 modif get source count 100 if limit 0 limit 1 const uint16 very rare bound limit const uint16 rare bound 2 limit cache preview state criterion 2 const bool is preview enable the prefs get preview prio the prefs is ext controls enabled get preview prio is previewable file type collect and calculate criteria for all chunks for position pos chunks list get head position pos null chunk cur chunk chunks list get next pos offsets of chunk const uint64 u start uint64 cur chunk part partsize const uint64 u end get file size uint64 1 u start partsize 1 get file size uint64 1 u start partsize 1 assert u start u end criterion 2 parts used for preview remark we need to download the first part and the last part s when the last part is very small it s necessary to download the two last parts bool crit preview false if is preview enable true if cur chunk part 0 crit preview true first chunk else if cur chunk part part count 1 crit preview true last chunk else if cur chunk part part count 2 last chunk 1 only if last chunk is too small if get file size u end uint64 partsize 3 crit preview true last chunk 1 criterion 3 request state downloading in process from other source s const bool crit requested cur chunk frequency very rare bound cpu load is already requested u start u end criterion 4 completion uint64 part size partsize for position pos gaplist get head position pos null const gap struct cur gap gaplist get next pos check if gap is into the limit if cur gap start u start if cur gap end u start cur gap end u end part size cur gap end u start 1 else if cur gap end u end part size 0 break exit loop for else if cur gap start u end if cur gap end u end part size cur gap end cur gap start 1 else part size u end cur gap start 1 const uint16 crit completion uint16 part size partsize 100 in calculate priority with all criteria if cur chunk frequency very rare bound 0 xxxx unrequested requested very rare chunks cur chunk rank 25 cur chunk frequency criterion 1 crit preview true 0 1 criterion 2 100 crit completion criterion 4 else if crit preview true 10000 10100 unrequested preview chunks 30000 30100 requested preview chunks cur chunk rank crit requested false 10000 30000 criterion 3 100 crit completion criterion 4 else if cur chunk frequency rare bound 10101 1xxxx unrequested rare chunks 30101 3xxxx requested rare chunks cur chunk rank 25 cur chunk frequency criterion 1 crit requested false 10101 30101 criterion 3 100 crit completion criterion 4 else common chunk if crit requested false criterion 3 20000 2xxxx unrequested common chunks cur chunk rank 20000 criterion 3 100 crit completion criterion 4 else 40000 4xxxx requested common chunks remark the weight of the completion criterion is inversed to spead the requests over the completing chunks without this the chunk closest to completion will received every new sources cur chunk rank 40000 criterion 3 crit completion criterion 4 select the next chunk to download if chunks list is empty false find and count the chunck s with the highest priority uint16 count 0 number of found chunks with same priority uint16 rank 0xffff highest priority found for position pos chunks list get head position pos null const chunk cur chunk chunks list get next pos if cur chunk rank rank count 1 rank cur chunk rank else if cur chunk rank rank count use a random access to avoid that everybody tries to download the same chunks at the same time spread the selected chunk among clients uint16 randomness 1 uint16 uint32 rand count 1 rand max 2 rand max for position pos chunks list get head position position cur pos pos const chunk cur chunk chunks list get next pos if cur chunk rank rank randomness if randomness 0 selection process is over sender m lastpartasked cu getpartstatus partcount getpartcount clist chunkslist partcount newblockcount newblockcount m_lastpartasked requested_block_struct pblock requested_block_struct getnextemptyblockinpart m_lastpartasked pblock requestedblocks_list addtail pblock newblockcount pblock pblock m_lastpartasked m_lastpartasked chunkslist isempty partcount ispartavailable getnextemptyblockinpart newentry newentry newentry m_srcpartfrequency chunkslist addtail newentry chunkslist isempty getsourcecount getsourcecount getsourcecount veryrarebound rarebound ispreviewenable theprefs getpreviewprio theprefs isextcontrolsenabled getpreviewprio ispreviewablefiletype chunkslist getheadposition cur_chunk chunkslist getnext ustart cur_chunk uend getfilesize ustart getfilesize ustart ustart uend critpreview ispreviewenable cur_chunk critpreview cur_chunk partcount critpreview cur_chunk partcount getfilesize uend critpreview critrequested cur_chunk veryrarebound isalreadyrequested ustart uend partsize getheadposition gap_struct cur_gap getnext cur_gap ustart cur_gap ustart cur_gap uend partsize cur_gap ustart cur_gap uend partsize cur_gap uend cur_gap uend partsize cur_gap cur_gap partsize uend cur_gap critcompletion partsize cur_chunk veryrarebound cur_chunk cur_chunk critpreview critcompletion critpreview cur_chunk critrequested critcompletion cur_chunk rarebound cur_chunk cur_chunk critrequested critcompletion critrequested cur_chunk critcompletion cur_chunk critcompletion chunkslist isempty chunkslist getheadposition cur_chunk chunkslist getnext cur_chunk cur_chunk cur_chunk rand_max rand_max chunkslist getheadposition cur_pos cur_chunk chunkslist getnext cur_chunk m_lastpartasked void c part file write part status c safe mem file file const uint ued2k part count geted2k part count file writeu int16 uint16 ued2k part count uint u part 0 while u part ued2k part count uint8 towrite 0 for uint i 0 i 8 i if u part get part count is complete uint64 u part partsize uint64 u part 1 partsize 1 true towrite 1 i u part if u part ued2k part count break file writeu int8 towrite cpartfile writepartstatus csafememfile ued2kpartcount geted2kpartcount writeuint16 ued2kpartcount upart upart ued2kpartcount upart getpartcount iscomplete upart upart upart upart ued2kpartcount writeuint8 void c part file write complete sources count c safe mem file file const file writeu int16 m ncompletesourcescount cpartfile writecompletesourcescount csafememfile writeuint16 m_ncompletesourcescount void c part file add sources c safe mem file sources uint32 serverip uint16 serverport uint count sources readu int8 if stopped since we may received multiple search source udp results we have to consume all data of that packet sources seek count 4 2 seek cur return uint debug lowiddropped 0 uint debug possiblesources 0 for uint i 0 i count i uint32 userid sources readu int32 uint16 port sources readu int16 check the highid ip filter lan i ps and i pfilter the received sources ip addresses if is lowid userid if is goodip userid check for 0 ip localhost and optionally for lan addresses if the prefs get log filteredi ps add debug log line false t ignored source ip s received from server bad ip ipstr userid continue if the app ipfilter is filtered userid if the prefs get log filteredi ps add debug log line false t ignored source ip s received from server ip filter s ipstr userid the app ipfilter get last hit continue if the app clientlist is banned client userid ifdef debug if the prefs get log banned clients c up down client p client the app clientlist find client byip userid add debug log line false t ignored source ip s received from server banned client s ipstr userid p client dbg get client info endif continue additionally check for lowid and own ip if can add source userid port serverip serverport debug lowiddropped if the prefs get log filteredi ps add debug log line false t ignored source ip s received from server ipstr userid continue if get max sources this get source count debug possiblesources c up down client newsource new c up down client this port userid serverip serverport true the app downloadqueue check and add source this newsource else since we may received multiple search source udp results we have to consume all data of that packet sources seek count 1 i 4 2 seek cur if get kad file searchid kademlia c search manager stop search get kad file searchid false break if the prefs get debug source exchange add debug log line false t sx recv server source response count u dropped u possible sources u file s count debug lowiddropped debug possiblesources get file name cpartfile addsources csafememfile readuint8 seek_cur debug_lowiddropped debug_possiblesources readuint32 readuint16 ips ipfilter islowid isgoodip theprefs getlogfilteredips adddebuglogline _t theapp isfiltered theprefs getlogfilteredips adddebuglogline _t theapp getlasthit theapp isbannedclient _debug theprefs getlogbannedclients cupdownclient pclient theapp findclientbyip adddebuglogline _t pclient dbggetclientinfo canaddsource debug_lowiddropped theprefs getlogfilteredips adddebuglogline _t getmaxsources getsourcecount debug_possiblesources cupdownclient cupdownclient theapp checkandaddsource seek_cur getkadfilesearchid csearchmanager stopsearch getkadfilesearchid theprefs getdebugsourceexchange adddebuglogline _t sxrecv possiblesources debug_lowiddropped debug_possiblesources getfilename void c part file add source lpctstr pszurl uint32 nip if stopped return if is goodip nip check for 0 ip localhost and optionally for lan addresses if the prefs get log filteredi ps add debug log line false t ignored url source ip s s bad ip ipstr nip pszurl return if the app ipfilter is filtered nip if the prefs get log filteredi ps add debug log line false t ignored url source ip s s ip filter s ipstr nip pszurl the app ipfilter get last hit return c url client client new c url client if client set url pszurl nip log error log statusbar t failed to process url source s pszurl delete client return client set request file this client set source from sf link if the app downloadqueue check and add source this client update parts info cpartfile addsource isgoodip theprefs getlogfilteredips adddebuglogline _t theapp isfiltered theprefs getlogfilteredips adddebuglogline _t theapp getlasthit curlclient curlclient seturl logerror log_statusbar _t setrequestfile setsourcefrom sf_link theapp checkandaddsource updatepartsinfo bool c part file can add source uint32 userid uint16 port uint32 serverip uint16 serverport uint pdebug lowiddropped bool ed2kid the incoming id could have the userid in the hybrid format uint32 hybridid 0 if ed2kid if is lowid userid hybridid userid else hybridid ntohl userid else hybridid userid if is lowid userid userid ntohl userid mod note do not change this part merkur if the app serverconnect is connected if the app serverconnect is lowid if the app serverconnect get clientid userid the app serverconnect get current server getip serverip the app serverconnect get current server get port serverport return false if the app serverconnect get localip userid return false else if the app serverconnect get clientid userid the prefs get port port return false if kademlia c kademlia is connected if kademlia c kademlia is firewalled if kademlia c kademlia getip address hybridid the prefs get port port return false this allows 0 clients to not be removed if ed2kid false if is lowid hybridid the app is firewalled if pdebug lowiddropped pdebug lowiddropped return false mod note end return true cpartfile canaddsource pdebug_lowiddropped islowid islowid theapp isconnected theapp islowid theapp getclientid theapp getcurrentserver theapp getcurrentserver getport theapp getlocalip theapp getclientid theprefs getport ckademlia isconnected ckademlia isfirewalled ckademlia getipaddress theprefs getport islowid theapp isfirewalled pdebug_lowiddropped pdebug_lowiddropped e part file status c part file get status bool ignorepause const if paused insufficient status ps error status ps completing status ps complete ignorepause return status else if paused return ps paused else return ps insufficient epartfilestatus cpartfile getstatus ps_error ps_completing ps_complete ps_paused ps_insufficient void c part file set status e part file status e status setstatus e status if the app emuledlg is running notify status change update displayed info true if the prefs show cat tab infos the app emuledlg transferwnd update cat tab titles cpartfile setstatus epartfilestatus estatus _setstatus estatus theapp isrunning notifystatuschange updatedisplayedinfo theprefs showcattabinfos theapp updatecattabtitles void c part file setstatus e part file status e status note this function is meant to be used from different threads do not call any gui functions from within here assert e status ps paused e status ps insufficient status e status cpartfile _setstatus epartfilestatus estatus estatus ps_paused estatus ps_insufficient estatus void c part file notify status change if the app emuledlg is running the app emuledlg transferwnd downloadlistctrl update current category view this cpartfile notifystatuschange theapp isrunning theapp updatecurrentcategoryview c string c part file get partfile status const switch get status case ps hashing case ps waitingforhash return get res string ids hashing case ps completing c string str state get res string ids completing if get file op pfop hashing str state t get res string ids hashing t else if get file op pfop copying str state t copying else if get file op pfop uncompressing str state t uncompressing return str state case ps complete return get res string ids complete case ps paused if stopped return get res string ids stopped return get res string ids paused case ps insufficient return get res string ids insufficient case ps error if m bcompletionerror return get res string ids insufficient return get res string ids errorlike if get src statistics value ds downloading 0 return get res string ids downloading else return get res string ids waiting cstring cpartfile getpartfilestatus getstatus ps_hashing ps_waitingforhash getresstring ids_hashing ps_completing cstring strstate getresstring ids_completing getfileop pfop_hashing strstate _t getresstring ids_hashing _t getfileop pfop_copying strstate _t getfileop pfop_uncompressing strstate _t strstate ps_complete getresstring ids_complete ps_paused getresstring ids_stopped getresstring ids_paused ps_insufficient getresstring ids_insufficient ps_error m_bcompletionerror getresstring ids_insufficient getresstring ids_errorlike getsrcstatisticsvalue ds_downloading getresstring ids_downloading getresstring ids_waiting int c part file get partfile status rang const switch get status case ps hashing case ps waitingforhash return 7 case ps completing return 1 case ps complete return 0 case ps paused if is stopped return 6 else return 5 case ps insufficient return 4 case ps error return 8 if get src statistics value ds downloading 0 return 3 waiting return 2 downloading cpartfile getpartfilestatusrang getstatus ps_hashing ps_waitingforhash ps_completing ps_complete ps_paused isstopped ps_insufficient ps_error getsrcstatisticsvalue ds_downloading void c part file set active bool b active time t t now time null if b active if the app is connected if m tactivated 0 m tactivated t now else if m tactivated 0 m ndlactivetime t now m tactivated m tactivated 0 cpartfile setactive bactive time_t tnow bactive theapp isconnected m_tactivated m_tactivated tnow m_tactivated m_ndlactivetime tnow m_tactivated m_tactivated void c part file set down priority uint8 np bool resort changed the default resort to true as it is was we almost never sorted the download list when a priority changed if we don t keep the download list sorted priority means nothing in downloadqueue cpp process also if we call this method with the same priotiry don t do anything to help use less cpu cycles if m idownpriority np we have a new priotiry if np pr low np pr normal np pr high this should never happen default to normal assert 0 np pr normal m idownpriority np some methods will change a batch of priorites then call these methods if resort sort the downloadqueue so contacting sources work correctly the app downloadqueue sort by priority the app downloadqueue check diskspace timed update our display to show the new info based on our new priority update displayed info true save the partfile we do this so that if we restart e mule before this files does any transfers it will remember the new priority save part file cpartfile setdownpriority m_idownpriority pr_low pr_normal pr_high pr_normal m_idownpriority theapp sortbypriority theapp checkdiskspacetimed updatedisplayedinfo emule savepartfile void c part file update auto down priority if is auto down priority return if get source count 100 set down priority pr low return if get source count 20 set down priority pr normal return set down priority pr high cpartfile updateautodownpriority isautodownpriority getsourcecount setdownpriority pr_low getsourcecount setdownpriority pr_normal setdownpriority pr_high uint c part file get src statistics value e download state ndl state const assert ndl state arrsize m anstates return m anstates ndl state cpartfile getsrcstatisticsvalue edownloadstate ndlstate ndlstate m_anstates m_anstates ndlstate uint c part file get transferring src count const return get src statistics value ds downloading cpartfile gettransferringsrccount getsrcstatisticsvalue ds_downloading uint c part file get not current sources count const uint counter 0 for position pos srclist get head position pos null e download state ndl state srclist get next pos get download state if ndl state ds onqueue ndl state ds downloading counter return counter cpartfile getnotcurrentsourcescount getheadposition edownloadstate ndlstate getnext getdownloadstate ndlstate ds_onqueue ndlstate ds_downloading int c part file get valid sources count const int counter 0 for position pos srclist get head position pos null e download state ndl state srclist get next pos get download state if ndl state ds onqueue ndl state ds downloading ndl state ds connected ndl state ds remotequeuefull counter return counter cpartfile getvalidsourcescount getheadposition edownloadstate ndlstate getnext getdownloadstate ndlstate ds_onqueue ndlstate ds_downloading ndlstate ds_connected ndlstate ds_remotequeuefull bool c part file is archive bool only previewable const if only previewable c string extension get file name right 4 return extension compare no case t zip 0 extension compare no case t cbz 0 extension compare no case t rar 0 extension compare no case t cbr 0 return ed2kft archive geted2k file typeid get file name cpartfile isarchive onlypreviewable onlypreviewable cstring getfilename comparenocase _t comparenocase _t comparenocase _t comparenocase _t ed2kft_archive geted2kfiletypeid getfilename bool c part file is previewable file type const return is archive is movie cpartfile ispreviewablefiletype isarchive ismovie time t c part file get time remaining const em file size completesize get completed size time t simple 1 time t estimate 1 if get datarate 0 simple time t uint64 get file size completesize uint64 get datarate if get dl active time completesize uint64 512000 estimate time t uint64 get file size completesize double completesize double get dl active time if simple 1 we are not transferring at the moment if estimate 1 we also don t have enough data to guess return 1 else if estimate hr2s 24 15 the estimate is too high return 1 else return estimate else if estimate 1 we are transferring but estimate doesn t have enough data to guess return simple if simple estimate return simple if estimate hr2s 24 15 the estimate is too high return 1 return estimate time_t cpartfile gettimeremaining emfilesize getcompletedsize time_t time_t getdatarate time_t getfilesize getdatarate getdlactivetime time_t getfilesize getdlactivetime time t c part file get time remaining simple const if get datarate 0 return 1 return time t uint64 get file size get completed size uint64 get datarate time_t cpartfile gettimeremainingsimple getdatarate time_t getfilesize getcompletedsize getdatarate uint32 c part file get dl active time const uint32 n dl active time m ndlactivetime if m tactivated 0 n dl active time time null m tactivated return n dl active time cpartfile getdlactivetime ndlactivetime m_ndlactivetime m_tactivated ndlactivetime m_tactivated ndlactivetime const c up down client client assert transize 0 assert start end increment transferred bytes counter for this file m utransferred transize this is needed a few times uint32 len data uint32 end start 1 assert len data 0 uint64 end start 1 len data if len data transize m ucompressiongain len data transize the prefs add2 saved from compression len data transize occasionally packets are duplicated no point writing it twice if is complete start end false if the prefs get verbose add debug log line false t prc blk pkt already written block s file s s dbg get block info start end get file name client dbg get client info return 0 log transferinformation in our blackbox m corruptionblackbox transferred data start end client create copy of data as new buffer byte buffer new byte len data memcpy buffer data len data create a new buffered queue entry part file buffered data item new part file buffered data item data buffer item start start item end end item block block add to the queue in the correct position most likely the end part file buffered data queue item bool added false position pos m buffereddata list get tail position while pos null position pos last pos queue item m buffereddata list get prev pos if item end queue item end added true m buffereddata list insert after pos last item break if added m buffereddata list add head item increment buffer size marker m ntotalbufferdata len data mark this small section of the file as filled fill gap item start item end update the flushed mark on the requested block the loop here is unfortunate but necessary to detect deleted blocks pos requestedblocks list get head position while pos null if requestedblocks list get next pos item block item block transferred len data if gaplist is empty flush buffer true return the length of data written to the buffer return len data cupdownclient m_utransferred lendata lendata lendata lendata m_ucompressiongain lendata theprefs add2savedfromcompression lendata iscomplete theprefs getverbose adddebuglogline _t prcblkpkt dbggetblockinfo getfilename dbggetclientinfo m_corruptionblackbox transferreddata lendata lendata partfilebuffereddata partfilebuffereddata partfilebuffereddata queueitem m_buffereddata_list gettailposition poslast queueitem m_buffereddata_list getprev queueitem m_buffereddata_list insertafter poslast m_buffereddata_list addhead m_ntotalbufferdata lendata fillgap requestedblocks_list getheadposition requestedblocks_list getnext lendata isempty flushbuffer lendata void c part file flush buffer bool forcewait bool b forceich bool b noaich bool b increased file false m nlastbufferflushtime get tick count if m buffereddata list is empty return if m allocatethread null diskspace is being allocated right now so dont write and keep the data in the buffer for later return else if m iallocinfo 0 b increased file true m iallocinfo 0 if the prefs get verbose add debug log line false t flushing file s buffer size ld bytes ld queued items transferred ld time ld n get file name m ntotalbufferdata m buffereddata list get count m utransferred m nlastbufferflushtime uint part count get part count bool changed part new bool part count remember which parts need to be checked at the end of the flush for uint part number 0 part number part count part number changed part part number false try bool b check diskspace the prefs is check diskspace enabled the prefs get min free disk space 0 ulonglong u free disk space b check diskspace get free disk spacex get temp path 0 check free diskspace for compressed sparse files before possibly increasing the file size if b check diskspace is normal file compressed sparse files regardless whether the file is increased in size check the amount of data which will be written would need to use disk cluster sizes for more accuracy if m ntotalbufferdata the prefs get min free disk space u free disk space afx throw file exception c file exception disk full 0 m hpartfile get file name ensure file is big enough to write data to the last item will be the furthest from the start part file buffered data item m buffereddata list get tail if m hpartfile get length item end uint64 newsize the prefs get alloc complete mode get file size item end 1 ulonglong u increase newsize m hpartfile get length check free diskspace for normal files before increasing the file size if b check diskspace is normal file normal files check if increasing the file would reduce the amount of min free space beyond the limit would need to use disk cluster sizes for more accuracy if u increase the prefs get min free disk space u free disk space afx throw file exception c file exception disk full 0 m hpartfile get file name if is normal file u increase 2097152 forcewait true 2mb alloc it at once allocate filesize if forcewait m allocatethread afx begin thread allocate space thread this thread priority lowest 0 create suspended if m allocatethread null trace t failed to create alloc thread allocate blocking n forcewait true else m iallocinfo newsize m allocatethread resume thread delete changed part return if forcewait b increased file true if this is a ntfs compressed file and the current block is the 1st one to be written and there is not enough free disk space to hold the entire uncompressed file windows throws a disk full if is normal file m hpartfile set length newsize allocate disk space may throw disk full loop through queue for int i m buffereddata list get count i 0 i get top item item m buffereddata list get head this is needed a few times uint32 len data uint32 item end item start 1 slugfiller safe hash could be more than one part for uint32 curpart uint32 item start partsize curpart item end partsize curpart changed part curpart true slugfiller safe hash go to the correct position in file and write block of data m hpartfile seek item start c file begin m hpartfile write item data len data remove item from queue m buffereddata list remove head decrease buffer size m ntotalbufferdata len data release memory used by this item delete item data delete item partfile should never be too large if m hpartfile get length m nfilesize it s last chance correction the real bugfix has to be applied somewhere else trace t partfile s is too large truncating i64u bytes n get file name m hpartfile get length m nfilesize m hpartfile set length m nfilesize flush to disk m hpartfile flush check each part of the file uint32 part range uint m hpartfile get length partsize 0 m hpartfile get length partsize 1 partsize 1 for int part number part count 1 part number 0 part number if changed part part number false any parts other than last must be full size part range partsize 1 continue is this 9mb part complete if is complete partsize uint64 part number partsize uint64 part number 1 1 false is part corrupt if hash single part part number log warning log statusbar get res string ids err partcorrupt part number get file name add gap partsize uint64 part number partsize uint64 part number part range add part to corrupted list if not already there if is corrupted part part number corrupted list add tail uint16 part number request aich recovery data if b noaich requestaich recovery uint16 part number update stats m ucorruptionloss part range 1 the prefs add2 lost from corruption part range 1 else if hashsetneeded if the prefs get verbose add debug log line dlp verylow false t finished part u of s part number get file name tell the blackbox about the verified data m corruptionblackbox verified data partsize uint64 part number partsize uint64 part number part range if this part was successfully completed although ich is active remove from corrupted list position pos corrupted corrupted list find uint16 part number if pos corrupted corrupted list remove at pos corrupted if status ps empty if the app emuledlg is running may be called during shutdown if get hash count geted2k part hash count hashsetneeded successfully completed part make it available for sharing set status ps ready the app sharedfiles safe addk file this else if is corrupted part part number the prefs isich enabled b forceich try to recover with minimal loss if hash single part part number m upartssaveddueich the prefs add2 session parts saved byich 1 uint32 u recovered uint32 get total gap size in part part number fill gap partsize uint64 part number partsize uint64 part number part range remove block from list partsize uint64 part number partsize uint64 part number part range tell the blackbox about the verified data m corruptionblackbox verified data partsize uint64 part number partsize uint64 part number part range remove from corrupted list position pos corrupted corrupted list find uint16 part number if pos corrupted corrupted list remove at pos corrupted add log line true get res string ids ichworked part number get file name cast itox bytes u recovered false false correct file stats if m ucorruptionloss u recovered check in case the tag was not present in part met m ucorruptionloss u recovered here we can t know if we have to subtract the amount of recovered data from the session stats or the cumulative stats so we subtract from where we can which leads eventuall to correct total stats if the prefs ses lost from corruption u recovered the prefs ses lost from corruption u recovered else if the prefs cum lost from corruption u recovered the prefs cum lost from corruption u recovered if status ps empty if the app emuledlg is running may be called during shutdown if get hash count geted2k part hash count hashsetneeded successfully recovered part make it available for sharing set status ps ready the app sharedfiles safe addk file this any parts other than last must be full size part range partsize 1 update met file save part file if the app emuledlg is running may be called during shutdown is this file finished if gaplist is empty complete file false check free diskspace checking the free disk space again after the file was written could most likely be avoided but because we do not use real physical disk allocation units for the free disk computations it should be more safe and accurate to check the free disk space again after file was written and buffers were flushed to disk if useing a normal file we could avoid the check disk space if the file was not increased if useing a compressed or sparse file we always have to check the space regardless whether the file was increased in size or not if b check diskspace is normal file b increased file is normal file switch get status case ps paused case ps error case ps completing case ps complete break default if get free disk spacex get temp path the prefs get min free disk space if is normal file normal files pause the file only if it would still grow if get needed space 0 pause file true b insufficient else cpartfile flushbuffer bforceich bnoaich bincreasedfile m_nlastbufferflushtime gettickcount m_buffereddata_list isempty m_allocatethread m_iallocinfo bincreasedfile m_iallocinfo theprefs getverbose adddebuglogline _t getfilename m_ntotalbufferdata m_buffereddata_list getcount m_utransferred m_nlastbufferflushtime partcount getpartcount changedpart partcount partnumber partnumber partcount partnumber changedpart partnumber bcheckdiskspace theprefs ischeckdiskspaceenabled theprefs getminfreediskspace ufreediskspace bcheckdiskspace getfreediskspacex gettemppath bcheckdiskspace isnormalfile m_ntotalbufferdata theprefs getminfreediskspace ufreediskspace afxthrowfileexception cfileexception diskfull m_hpartfile getfilename partfilebuffereddata m_buffereddata_list gettail m_hpartfile getlength theprefs getalloccompletemode getfilesize uincrease m_hpartfile getlength bcheckdiskspace isnormalfile uincrease theprefs getminfreediskspace ufreediskspace afxthrowfileexception cfileexception diskfull m_hpartfile getfilename isnormalfile uincrease m_allocatethread afxbeginthread allocatespacethread thread_priority_lowest create_suspended m_allocatethread _t m_iallocinfo m_allocatethread resumethread changedpart bincreasedfile diskfull isnormalfile m_hpartfile setlength diskfull m_buffereddata_list getcount m_buffereddata_list gethead lendata safehash changedpart safehash m_hpartfile cfile m_hpartfile lendata m_buffereddata_list removehead m_ntotalbufferdata lendata m_hpartfile getlength m_nfilesize _t getfilename m_hpartfile getlength m_nfilesize m_hpartfile setlength m_nfilesize m_hpartfile partrange m_hpartfile getlength m_hpartfile getlength partnumber partcount partnumber partnumber changedpart partnumber partrange iscomplete partnumber partnumber hashsinglepart partnumber logwarning log_statusbar getresstring ids_err_partcorrupt partnumber getfilename addgap partnumber partnumber partrange iscorruptedpart partnumber corrupted_list addtail partnumber bnoaich requestaichrecovery partnumber m_ucorruptionloss partrange theprefs add2lostfromcorruption partrange theprefs getverbose adddebuglogline dlp_verylow _t partnumber getfilename m_corruptionblackbox verifieddata partnumber partnumber partrange poscorrupted corrupted_list partnumber poscorrupted corrupted_list removeat poscorrupted ps_empty theapp isrunning gethashcount geted2kparthashcount setstatus ps_ready theapp safeaddkfile iscorruptedpart partnumber theprefs isichenabled bforceich hashsinglepart partnumber m_upartssaveddueich theprefs add2sessionpartssavedbyich urecovered gettotalgapsizeinpart partnumber fillgap partnumber partnumber partrange removeblockfromlist partnumber partnumber partrange m_corruptionblackbox verifieddata partnumber partnumber partrange poscorrupted corrupted_list partnumber poscorrupted corrupted_list removeat poscorrupted addlogline getresstring ids_ichworked partnumber getfilename castitoxbytes urecovered m_ucorruptionloss urecovered m_ucorruptionloss urecovered theprefs seslostfromcorruption urecovered theprefs seslostfromcorruption urecovered theprefs cumlostfromcorruption urecovered theprefs cumlostfromcorruption urecovered ps_empty theapp isrunning gethashcount geted2kparthashcount setstatus ps_ready theapp safeaddkfile partrange savepartfile theapp isrunning isempty completefile bcheckdiskspace isnormalfile bincreasedfile isnormalfile getstatus ps_paused ps_error ps_completing ps_complete getfreediskspacex gettemppath theprefs getminfreediskspace isnormalfile getneededspace pausefile binsufficient void c part file get filled list c typed ptr list c ptr list gap struct filled const if gaplist get head position null return gap struct gap gap struct best null position pos uint64 start 0 uint64 best end 0 loop until done bool finished false while finished finished true find first gap after current start pos best end m nfilesize pos gaplist get head position while pos null gap gaplist get next pos if gap start start gap end best end best gap best end best end finished false todo here we have a problem it occured that e mule crashed because of best null while recovering an archive which was currently in completing state if best null assert 0 return if finished invert this gap gap new gap struct gap start start gap end best start 1 start best end 1 filled add tail gap else if best end m nfilesize gap new gap struct gap start best end 1 gap end m nfilesize filled add tail gap cpartfile getfilledlist ctypedptrlist cptrlist gap_struct getheadposition gap_struct gap_struct bestend bestend m_nfilesize getheadposition getnext bestend bestend emule gap_struct addtail m_nfilesize gap_struct m_nfilesize addtail void c part file remove all requested blocks void requestedblocks list remove all cpartfile removeallrequestedblocks requestedblocks_list removeall bool c part file remove block from list uint64 start uint64 end assert start end bool b result false for position pos requestedblocks list get head position pos null position pos last pos requested block struct block requestedblocks list get next pos if block start offset start block end offset end requestedblocks list remove at pos last b result true return b result cpartfile removeblockfromlist bresult requestedblocks_list getheadposition poslast requested_block_struct requestedblocks_list getnext startoffset endoffset requestedblocks_list removeat poslast bresult bresult bool c part file is in requested block list const requested block struct block const return requestedblocks list find const cast requested block struct block null cpartfile isinrequestedblocklist requested_block_struct requestedblocks_list const_cast requested_block_struct void c part file remove all sources bool b try to swap position pos1 pos2 for pos1 srclist get head position pos2 pos1 null srclist get next pos1 if b try to swap if srclist get at pos2 swap to another file t removing source c part file remove all sources true true true null false false zz download manager the app downloadqueue remove source srclist get at pos2 false else the app downloadqueue remove source srclist get at pos2 false update parts info update available parts count enkeydev ottavio84 a4af remove all links a4af in sources to this file if a4a fsrclist is empty position pos1 pos2 for pos1 a4a fsrclist get head position pos2 pos1 null a4a fsrclist get next pos1 position pos3 a4a fsrclist get at pos2 m otherrequests list find this if pos3 a4a fsrclist get at pos2 m otherrequests list remove at pos3 the app emuledlg transferwnd downloadlistctrl remove source this a4a fsrclist get at pos2 this else pos3 a4a fsrclist get at pos2 m othernoneeded list find this if pos3 a4a fsrclist get at pos2 m othernoneeded list remove at pos3 the app emuledlg transferwnd downloadlistctrl remove source a4a fsrclist get at pos2 this a4a fsrclist remove all update file rating comment avail cpartfile removeallsources btrytoswap getheadposition getnext btrytoswap getat swaptoanotherfile _t cpartfile removeallsources downloadmanager theapp removesource getat theapp removesource getat updatepartsinfo updateavailablepartscount a4afsrclist isempty a4afsrclist getheadposition a4afsrclist getnext a4afsrclist getat m_otherrequests_list a4afsrclist getat m_otherrequests_list removeat theapp removesource a4afsrclist getat a4afsrclist getat m_othernoneeded_list a4afsrclist getat m_othernoneeded_list removeat theapp removesource a4afsrclist getat a4afsrclist removeall updatefileratingcommentavail bool c part file can open file const return get status ps complete cpartfile canopenfile getstatus ps_complete bool c part file is ready for preview const c preview apps e can preview res e preview apps res the preview apps can preview this if e preview apps res c preview apps not handled return e preview apps res c preview apps yes barry allow preview of archives of any length 1k if is archive true if get status ps complete get status ps completing get file size 1024 get completed size 1024 m brecoveringarchive get free disk spacex the prefs get temp dir 100000000 2 get file size return true check part file state e part file status u state get status if u state ps complete u state ps completing return false check part file size s if get file size uint64 1024 get completed size uint64 1024 return false check if we already trying to recover an archive file from this part file if m brecoveringarchive return false check free disk space uint64 u min free disk space the prefs is check diskspace enabled the prefs get min free disk space 0 the prefs get min free disk space 20 1024 1024 if the prefs get preview copied archives u min free disk space uint64 get file size uint64 2 else u min free disk space uint64 get completed size uint64 16 1024 if get free disk spacex get temp path u min free disk space return false return true if the prefs is movie preview backup return get status ps ready get status ps paused m bpreviewing get part count 5 is movie get free disk spacex get temp path 100000000 get file size is complete 0 partsize 1 false is complete partsize uint64 get part count 1 get file size uint64 1 false else tchar sz video player file name max fname tsplitpath the prefs get video player null null sz video player file name null enable the preview command if the according option is specified preview small blocks or if videolan client is specified if the prefs get preview small blocks tcsicmp sz video player file name t vlc if m bpreviewing return false e part file status u state get status if u state ps ready u state ps empty u state ps paused u state ps insufficient return false default check the ed2k file format to be of type audio video or cd image but because this could disable the preview command for some file types which e mule does not know this test can be avoided by specifying preview small blocks 2 if the prefs get preview small blocks 1 check the file extension eed2k file type e file type geted2k file typeid get file name if e file type ed2kft video e file type ed2kft audio e file type ed2kft cdimage check the ed2k file type const c string rstred2k file type get str tag value ft filetype if rstred2k file type is empty tcscmp rstred2k file type t ed2kftstr audio tcscmp rstred2k file type t ed2kftstr video return false if it s an mpeg file vlc is even capable of showing parts of the file if the beginning of the file is missing bool bmpeg false lpctstr psz ext tcsrchr get file name t if psz ext null c string str ext psz ext str ext make lower bmpeg str ext t mpg str ext t mpeg str ext t mpe str ext t mp3 str ext t mp2 str ext t mpa if bmpeg todo search a block which is at least 16k audio or 256k video if get completed size uint64 16 1024 return false else for avi files it depends on the used codec if the prefs get preview small blocks 2 if get completed size uint64 256 1024 return false else if is complete 0 256 1024 false return false return true else return get status ps ready get status ps paused m bpreviewing get part count 2 is movie is complete 0 partsize 1 false cpartfile isreadyforpreview cpreviewapps ecanpreviewres epreviewappsres thepreviewapps canpreview epreviewappsres cpreviewapps nothandled epreviewappsres cpreviewapps isarchive getstatus ps_complete getstatus ps_completing getfilesize getcompletedsize m_brecoveringarchive getfreediskspacex theprefs gettempdir getfilesize epartfilestatus ustate getstatus ustate ps_complete ustate ps_completing getfilesize getcompletedsize m_brecoveringarchive uminfreediskspace theprefs ischeckdiskspaceenabled theprefs getminfreediskspace theprefs getminfreediskspace theprefs getpreviewcopiedarchives uminfreediskspace getfilesize uminfreediskspace getcompletedsize getfreediskspacex gettemppath uminfreediskspace theprefs ismoviepreviewbackup getstatus ps_ready getstatus ps_paused m_bpreviewing getpartcount ismovie getfreediskspacex gettemppath getfilesize iscomplete iscomplete getpartcount getfilesize szvideoplayerfilename _max_fname _tsplitpath theprefs getvideoplayer szvideoplayerfilename previewsmallblocks theprefs getpreviewsmallblocks _tcsicmp szvideoplayerfilename _t m_bpreviewing epartfilestatus ustate getstatus ustate ps_ready ustate ps_empty ustate ps_paused ustate ps_insufficient emule previewsmallblocks theprefs getpreviewsmallblocks eed2kfiletype efiletype geted2kfiletypeid getfilename efiletype ed2kft_video efiletype ed2kft_audio efiletype ed2kft_cdimage cstring rstred2kfiletype getstrtagvalue ft_filetype rstred2kfiletype isempty _tcscmp rstred2kfiletype _t ed2kftstr_audio _tcscmp rstred2kfiletype _t ed2kftstr_video pszext _tcsrchr getfilename _t pszext cstring strext pszext strext makelower strext _t strext _t strext _t strext _t strext _t strext _t getcompletedsize theprefs getpreviewsmallblocks getcompletedsize iscomplete getstatus ps_ready getstatus ps_paused m_bpreviewing getpartcount ismovie iscomplete bool c part file can stop file const bool b file done get status ps complete get status ps completing return is stopped get status ps error b file done cpartfile canstopfile bfiledone getstatus ps_complete getstatus ps_completing isstopped getstatus ps_error bfiledone bool c part file can pause file const bool b file done get status ps complete get status ps completing return get status ps paused get status ps error b file done cpartfile canpausefile bfiledone getstatus ps_complete getstatus ps_completing getstatus ps_paused getstatus ps_error bfiledone bool c part file can resume file const return get status ps paused get status ps insufficient get status ps error get completion error cpartfile canresumefile getstatus ps_paused getstatus ps_insufficient getstatus ps_error getcompletionerror void c part file open file const if m pcollection c collection view dialog dialog dialog set collection m pcollection dialog do modal else shell open file get full name null cpartfile openfile m_pcollection ccollectionviewdialog setcollection m_pcollection domodal shellopenfile getfullname void c part file preview file if the preview apps preview this return if is archive true if m brecoveringarchive m bpreviewing c archive recovery recover this true the prefs get preview copied archives return if is ready for preview assert false return if the prefs is movie preview backup m bpreviewing true c preview thread p thread c preview thread afx begin thread runtime class c preview thread thread priority normal 0 create suspended p thread set values this the prefs get video player p thread resume thread else c string str line get full name strip available met extension to get the part file name if str line get length 4 str line right 4 t met str line delete str line get length 4 4 if the path contains spaces quote the entire path if str line find t 1 str line t str line t if the prefs get video player is empty get directory of video player application c string path the prefs get video player int pos path reverse find t if pos 1 path empty else path path left pos 1 if the prefs get preview small blocks flush buffer true shell execute null t open the prefs get video player str line path sw shownormal else shell execute null t open str line null null sw shownormal cpartfile previewfile thepreviewapps isarchive m_brecoveringarchive m_bpreviewing carchiverecovery theprefs getpreviewcopiedarchives isreadyforpreview theprefs ismoviepreviewbackup m_bpreviewing cpreviewthread pthread cpreviewthread afxbeginthread runtime_class cpreviewthread thread_priority_normal create_suspended pthread setvalues theprefs getvideoplayer pthread resumethread cstring strline getfullname strline getlength strline _t strline strline getlength strline _t strline _t strline _t theprefs getvideoplayer isempty cstring theprefs getvideoplayer reversefind _t theprefs getpreviewsmallblocks flushbuffer shellexecute _t theprefs getvideoplayer strline sw_shownormal shellexecute _t strline sw_shownormal void c part file delete file assert m bpreviewing barry need to tell any connected clients to stop sending the file stop file true feel free to implement a runtime handling mechanism if m allocatethread null log warning log statusbar get res string ids deleteafteralloc get file name m bdeleteafteralloc true return the app sharedfiles remove file this the app downloadqueue remove file this the app emuledlg transferwnd downloadlistctrl remove file this the app knownfiles add cancelled fileid get file hash if m hpartfile m hfile invalid handle value m hpartfile close if tremove m fullname log error log statusbar get res string ids err delete t c string strerror errno m fullname c string partfilename remove file extension m fullname if tremove partfilename log error log statusbar get res string ids err delete t c string strerror errno partfilename c string bak name m fullname bak name append partmet bak ext if taccess bak name 0 0 delete file bak name log error log statusbar get res string ids err delete t get error message get last error bak name bak name m fullname bak name append partmet tmp ext if taccess bak name 0 0 delete file bak name log error log statusbar get res string ids err delete t get error message get last error bak name delete this cpartfile deletefile m_bpreviewing stopfile m_allocatethread logwarning log_statusbar getresstring ids_deleteafteralloc getfilename m_bdeleteafteralloc theapp removefile theapp removefile theapp removefile theapp addcancelledfileid getfilehash m_hpartfile m_hfile invalid_handle_value m_hpartfile _tremove m_fullname logerror log_statusbar getresstring ids_err_delete _t cstring m_fullname cstring removefileextension m_fullname _tremove logerror log_statusbar getresstring ids_err_delete _t cstring cstring bakname m_fullname bakname partmet_bak_ext _taccess bakname deletefile bakname logerror log_statusbar getresstring ids_err_delete _t geterrormessage getlasterror bakname bakname m_fullname bakname partmet_tmp_ext _taccess bakname deletefile bakname logerror log_statusbar getresstring ids_err_delete _t geterrormessage getlasterror bakname void c part file stop file bool b cancel bool resort barry need to tell any connected clients to stop sending the file pause file false resort m lastsearchtimekad 0 m totalsearcheskad 0 remove all sources true paused true stopped true insufficient false datarate 0 memset m anstates 0 sizeof m anstates memset src stats 0 sizeof src stats xman bugfix memset net stats 0 sizeof net stats xman bugfix if b cancel flush buffer true if resort the app downloadqueue sort by priority the app downloadqueue check diskspace update displayed info true cpartfile stopfile bcancel pausefile m_lastsearchtimekad m_totalsearcheskad removeallsources m_anstates m_anstates src_stats src_stats net_stats net_stats bcancel flushbuffer theapp sortbypriority theapp checkdiskspace updatedisplayedinfo void c part file pause file bool b insufficient bool resort if file is already in insufficient state don t set it again to insufficient this may happen if a disk full condition is thrown before the automatically and periodically check free diskspace was done if b insufficient insufficient return if file is already in paused or insufficient state do not refresh the purge time if paused insufficient m ilastpausepurge time null the app downloadqueue remove local server request this if get kad file searchid kademlia c search manager stop search get kad file searchid true m lastsearchtimekad 0 if we were in the middle of searching reset timer so they can resume searching set active false if status ps complete status ps completing return packet packet new packet op canceltransfer 0 for position pos srclist get head position pos null c up down client cur src srclist get next pos if cur src get download state ds downloading cur src send cancel transfer packet cur src set download state ds onqueue t you cancelled the download sending op canceltransfer delete packet if b insufficient log error log statusbar t insufficient diskspace pausing download of s get file name insufficient true else paused true insufficient false notify status change datarate 0 m anstates ds downloading 0 khaos renamed var if b insufficient if resort the app downloadqueue sort by priority the app downloadqueue check diskspace save part file update displayed info true cpartfile pausefile binsufficient binsufficient m_ilastpausepurge theapp removelocalserverrequest getkadfilesearchid csearchmanager stopsearch getkadfilesearchid m_lastsearchtimekad setactive ps_complete ps_completing op_canceltransfer getheadposition cupdownclient cur_src getnext cur_src getdownloadstate ds_downloading cur_src sendcanceltransfer cur_src setdownloadstate ds_onqueue _t op_canceltransfer binsufficient logerror log_statusbar _t getfilename notifystatuschange m_anstates ds_downloading binsufficient theapp sortbypriority theapp checkdiskspace savepartfile updatedisplayedinfo void c part file stop paused file once an hour remove any sources for files which are no longer active downloads e part file status u state get status if u state ps paused u state ps insufficient u state ps error stopped time null m ilastpausepurge 60 60 stop file else if m bdeleteafteralloc m allocatethread null delete file return cpartfile stoppausedfile epartfilestatus ustate getstatus ustate ps_paused ustate ps_insufficient ustate ps_error m_ilastpausepurge stopfile m_bdeleteafteralloc m_allocatethread deletefile void c part file resume file bool resort if status ps complete status ps completing return if status ps error m bcompletionerror assert gaplist is empty if gaplist is empty rehashing the file could probably be avoided but better be in the safe side m bcompletionerror false complete file false return paused false stopped false set active the app is connected m lastsearchtime 0 if resort the app downloadqueue sort by priority the app downloadqueue check diskspace save part file notify status change update displayed info true cpartfile resumefile ps_complete ps_completing ps_error m_bcompletionerror isempty isempty m_bcompletionerror completefile setactive theapp isconnected m_lastsearchtime theapp sortbypriority theapp checkdiskspace savepartfile notifystatuschange updatedisplayedinfo void c part file resume file insufficient if status ps complete status ps completing return if insufficient return add log line false t resuming download of s get file name insufficient false set active the app is connected m lastsearchtime 0 update displayed info true cpartfile resumefileinsufficient ps_complete ps_completing addlogline _t getfilename setactive theapp isconnected m_lastsearchtime updatedisplayedinfo packet c part file create src info packet const c up down client for client const we need to find where the dangling pointers are before uncommenting this if is part file return c known file create src info packet for client if for client get request file this return null if get status ps ready get status ps empty return null if srclist is empty return null c safe mem file data 1024 uint n count 0 data write hash16 m abyfilehash data writeu int16 uint16 n count bool b needed for position pos srclist get head position pos 0 b needed false const c up down client cur src srclist get next pos if cur src has lowid cur src is valid source continue const uint8 srcstatus cur src get part status if srcstatus if cur src get part count get part count const uint8 reqstatus for client get part status if reqstatus assert for client get part count get part count only send sources which have needed parts for this client for uint x 0 x get part count x if srcstatus x reqstatus x b needed true break else we know this client is valid but don t know the part count status so currently we just send them for uint x 0 x get part count x if srcstatus x b needed true break else should never happen if the prefs get verbose debug only debug log error t hs found source s with wrong partcount u attached to partfile s partcount u function cur src dbg get client info cur src get part count get file name get part count if b needed n count uint32 dwid if for client get source exchange version 2 dwid cur src get userid hybrid else dwid ntohl cur src get userid hybrid data writeu int32 dwid data writeu int16 cur src get user port data writeu int32 cur src get serverip data writeu int16 cur src get server port if for client get source exchange version 1 data write hash16 cur src get user hash if n count 500 break if n count return 0 data seek 16 seek set data writeu int16 uint16 n count packet result new packet data op emuleprot result opcode op answersources 16 2 501 4 2 4 2 16 14046 bytes max if result size 354 result pack packet if the prefs get debug source exchange add debug log line false t sx send client source response count u s file s n count for client dbg get client info get file name return result cpartfile createsrcinfopacket cupdownclient forclient ispartfile cknownfile createsrcinfopacket forclient forclient getrequestfile getstatus ps_ready getstatus ps_empty isempty csafememfile ncount writehash16 m_abyfilehash writeuint16 ncount bneeded getheadposition bneeded cupdownclient cur_src getnext cur_src haslowid cur_src isvalidsource cur_src getpartstatus cur_src getpartcount getpartcount forclient getpartstatus forclient getpartcount getpartcount getpartcount bneeded getpartcount bneeded theprefs getverbose debug_only debuglogerror _t __function__ cur_src dbggetclientinfo cur_src getpartcount getfilename getpartcount bneeded ncount forclient getsourceexchangeversion cur_src getuseridhybrid cur_src getuseridhybrid writeuint32 writeuint16 cur_src getuserport writeuint32 cur_src getserverip writeuint16 cur_src getserverport forclient getsourceexchangeversion writehash16 cur_src getuserhash ncount ncount seek_set writeuint16 ncount op_emuleprot op_answersources packpacket theprefs getdebugsourceexchange adddebuglogline _t sxsend ncount forclient dbggetclientinfo getfilename void c part file add client sources c safe mem file sources uint8 sourceexchangeversion const c up down client p client if stopped return uint n count sources readu int16 if the prefs get debug source exchange c string str src if p client str src format t s p client dbg get client info add debug log line false t sx recv client source response count u s file s n count str src get file name check if the data size matches the n count for v1 or v2 and eventually correct the source exchange version while reading the packet data otherwise we could experience a higher chance in dealing with wrong source data userhashs and finally duplicate sources uint u data size uint sources get length sources get position checks if version 1 packet is correct size if n count 4 2 4 2 u data size if sourceexchangeversion 1 return checks if version 2 3 packet is correct size else if n count 4 2 4 2 16 u data size if sourceexchangeversion 1 return else if v4 inserts additional data like v2 the above code will correctly filter those packets if v4 appends additional data after count sources count we are in trouble with the above code though a client which does not understand v4 should never receive such a packet if the prefs get verbose debug log warning t received invalid source exchange packet v u of data size u for s sourceexchangeversion u data size get file name return for uint i 0 i n count i uint32 dwid sources readu int32 uint16 n port sources readu int16 uint32 dw serverip sources readu int32 uint16 n server port sources readu int16 uchar ach user hash 16 if sourceexchangeversion 1 sources read hash16 ach user hash clients send id s the the hyrbid format so highid clients with 0 won t be falsely switched to a lowid if sourceexchangeversion 3 uint32 dwided2k ntohl dwid check the highid ip filter lan i ps and i pfilter the received sources ip addresses if is lowid dwid if is goodip dwided2k check for 0 ip localhost and optionally for lan addresses if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange bad ip ipstr dwided2k continue if the app ipfilter is filtered dwided2k if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange ip filter s ipstr dwided2k the app ipfilter get last hit continue if the app clientlist is banned client dwided2k ifdef debug if the prefs get log banned clients c up down client p client the app clientlist find client byip dwided2k add debug log line false t ignored source ip s received via source exchange banned client s ipstr dwided2k p client dbg get client info endif continue additionally check for lowid and own ip if can add source dwid n port dw serverip n server port null false if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange ipstr dwided2k continue else check the highid ip filter lan i ps and i pfilter the received sources ip addresses if is lowid dwid if is goodip dwid check for 0 ip localhost and optionally for lan addresses if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange bad ip ipstr dwid continue if the app ipfilter is filtered dwid if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange ip filter s ipstr dwid the app ipfilter get last hit continue if the app clientlist is banned client dwid ifdef debug if the prefs get log banned clients c up down client p client the app clientlist find client byip dwid add debug log line false t ignored source ip s received via source exchange banned client s ipstr dwid p client dbg get client info endif continue additionally check for lowid and own ip if can add source dwid n port dw serverip n server port if the prefs get log filteredi ps add debug log line false t ignored source ip s received via source exchange ipstr dwid continue if get max sources get source count c up down client newsource if sourceexchangeversion 3 newsource new c up down client this n port dwid dw serverip n server port false else newsource new c up down client this n port dwid dw serverip n server port true if sourceexchangeversion 1 newsource set user hash ach user hash newsource set source from sf source exchange the app downloadqueue check and add source this newsource else break cpartfile addclientsources csafememfile cupdownclient pclient ncount readuint16 theprefs getdebugsourceexchange cstring strsrc pclient strsrc _t pclient dbggetclientinfo adddebuglogline _t sxrecv sfile ncount strsrc getfilename ncount udatasize getlength getposition ncount udatasize ncount udatasize theprefs getverbose debuglogwarning _t udatasize getfilename ncount readuint32 nport readuint16 dwserverip readuint32 nserverport readuint16 achuserhash readhash16 achuserhash ips ipfilter islowid isgoodip theprefs getlogfilteredips adddebuglogline _t theapp isfiltered theprefs getlogfilteredips adddebuglogline _t theapp getlasthit theapp isbannedclient _debug theprefs getlogbannedclients cupdownclient pclient theapp findclientbyip adddebuglogline _t pclient dbggetclientinfo canaddsource nport dwserverip nserverport theprefs getlogfilteredips adddebuglogline _t ips ipfilter islowid isgoodip theprefs getlogfilteredips adddebuglogline _t theapp isfiltered theprefs getlogfilteredips adddebuglogline _t theapp getlasthit theapp isbannedclient _debug theprefs getlogbannedclients cupdownclient pclient theapp findclientbyip adddebuglogline _t pclient dbggetclientinfo canaddsource nport dwserverip nserverport theprefs getlogfilteredips adddebuglogline _t getmaxsources getsourcecount cupdownclient cupdownclient nport dwserverip nserverport cupdownclient nport dwserverip nserverport setuserhash achuserhash setsourcefrom sf_source_exchange theapp checkandaddsource void c part file update available parts count uint availablecounter 0 uint i part count get part count for uint ix part 0 ix part i part count ix part for position pos srclist get head position pos if srclist get next pos is part available ix part availablecounter break if i part count availablecounter available parts count i part count lastseencomplete c time get current time available parts count availablecounter cpartfile updateavailablepartscount ipartcount getpartcount ixpart ixpart ipartcount ixpart getheadposition getnext ispartavailable ixpart ipartcount availablepartscount ipartcount ctime getcurrenttime availablepartscount void c part file set last answered time timeout m clientsrcanswered 2 connection latency get tick count sourceclientreasks cpartfile setlastansweredtimetimeout m_clientsrcanswered connection_latency gettickcount void c part file update file rating comment avail bool b old has comment m bhascomment uint u old user ratings m uuserrating m bhascomment false uint u ratings 0 uint u user ratings 0 for position pos srclist get head position pos null const c up down client cur src srclist get next pos if m bhascomment cur src has file comment m bhascomment true if cur src has file rating u ratings u user ratings cur src get file rating for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos if m bhascomment entry get str tag value tag description is empty m bhascomment true uint rating uint entry get int tag value tag filerating if rating 0 u ratings u user ratings rating if u ratings m uuserrating u user ratings u ratings else m uuserrating 0 if b old has comment m bhascomment u old user ratings m uuserrating update displayed info true cpartfile updatefileratingcommentavail boldhascomment m_bhascomment uolduserratings m_uuserrating m_bhascomment uratings uuserratings getheadposition cupdownclient cur_src getnext m_bhascomment cur_src hasfilecomment m_bhascomment cur_src hasfilerating uratings uuserratings cur_src getfilerating m_kadnotes getheadposition centry m_kadnotes getnext m_bhascomment getstrtagvalue tag_description isempty m_bhascomment getinttagvalue tag_filerating uratings uuserratings uratings m_uuserrating uuserratings uratings m_uuserrating boldhascomment m_bhascomment uolduserratings m_uuserrating updatedisplayedinfo void c part file add downloading source c up down client client position pos m downloadingsourcelist find client to be sure if pos null m downloadingsourcelist add tail client the app emuledlg transferwnd downloadclientsctrl add client client cpartfile adddownloadingsource cupdownclient m_downloadingsourcelist m_downloadingsourcelist addtail theapp addclient void c part file remove downloading source c up down client client position pos m downloadingsourcelist find client to be sure if pos null m downloadingsourcelist remove at pos the app emuledlg transferwnd downloadclientsctrl remove client client cpartfile removedownloadingsource cupdownclient m_downloadingsourcelist m_downloadingsourcelist removeat theapp removeclient c string c part file get progress string uint16 size const char cr progress 0 green char cr have 1 black char cr pending 2 yellow char cr missing 3 red char cr waiting 6 cr waiting 0 4 blue few source cr waiting 1 5 cr waiting 2 6 cr waiting 3 7 cr waiting 4 8 cr waiting 5 9 full sources c string my chunkbar for uint16 i 0 i size 1 i my chunkbar append char cr have one more for safety float unit float size float m nfilesize if get status ps complete get status ps completing char fill range my chunkbar 0 uint32 uint64 m nfilesize unit cr progress else red gaps for position pos gaplist get head position pos 0 gap struct cur gap gaplist get next pos bool gapdone false uint64 gapstart cur gap start uint64 gapend cur gap end for uint i 0 i get part count i if gapstart uint64 i partsize gapstart uint64 i 1 partsize is in this part if gapend uint64 i 1 partsize gapdone true else gapend uint64 i 1 partsize and next part paint uint8 color if m srcpartfrequency get count int ptr i m srcpartfrequency uint16 i frequency color cr waiting color m srcpartfrequency uint16 i 10 cr waiting m srcpartfrequency uint16 i 2 cr waiting 5 else color cr missing char fill range my chunkbar uint32 gapstart unit uint32 gapend unit 1 color if gapdone finished break else gapstart gapend gapend cur gap end yellow pending parts for position pos requestedblocks list get head position pos 0 requested block struct block requestedblocks list get next pos char fill range my chunkbar uint32 block start offset block transferred unit uint32 block end offset unit cr pending return my chunkbar cstring cpartfile getprogressstring crprogress crhave crpending crmissing crwaiting crwaiting crwaiting crwaiting crwaiting crwaiting crwaiting cstring my_chunkbar my_chunkbar appendchar crhave m_nfilesize getstatus ps_complete getstatus ps_completing charfillrange my_chunkbar m_nfilesize crprogress getheadposition gap_struct cur_gap getnext cur_gap cur_gap getpartcount m_srcpartfrequency getcount int_ptr m_srcpartfrequency crwaiting m_srcpartfrequency crwaiting m_srcpartfrequency crwaiting crmissing charfillrange my_chunkbar cur_gap requestedblocks_list getheadposition requested_block_struct requestedblocks_list getnext charfillrange my_chunkbar startoffset endoffset crpending my_chunkbar c string c part file get info summary const c string sbuffer lsc compl buffer lastdwl if is part file lsc format t s cast itox bytes get completed size false false compl format t s cast itox bytes get file size false false buffer format t s s lsc compl compl format t s s 1f n get res string ids dl transfcompl buffer get percent completed else compl t n if lastseencomplete null lsc format t s get res string ids never else lsc format t s lastseencomplete format the prefs get date time format float availability 0 0f if get part count 0 availability float get available part count 100 0 get part count c string avail if is part file avail format get res string ids avail get part count get available part count availability if getc file date null lastdwl format t s getc file date format the prefs get date time format else lastdwl get res string ids never c string sourcesinfo if is part file sourcesinfo format get res string ids dl sources t get res string ids sourcesinfo t n get source count get valid sources count get src statistics value ds noneededparts get srca4af count always show space on disk c string sod t get res string ids ondisk cast itox bytes get real file size false false t c string status if get transferring src count 0 status format get res string ids partinfos2 t n get transferring src count else status format t s n get partfile status todo don t show the part met filename for completed files c string info info format get res string ids dl filename t s n get res string ids fd hash t s n get res string ids fd size t s s n get res string ids fd met t s n n get res string ids status t status t s sourcesinfo t s get res string ids lastseencompl t lsc t n get res string ids fd lastchange t lastdwl get file name md4str get file hash cast itox bytes get file size false false sod get part met file name compl avail return info cstring cpartfile getinfosummary cstring ispartfile _t castitoxbytes getcompletedsize _t castitoxbytes getfilesize _t _t getresstring ids_dl_transfcompl getpercentcompleted _t _t getresstring ids_never _t theprefs getdatetimeformat getpartcount getavailablepartcount getpartcount cstring ispartfile getresstring ids_avail getpartcount getavailablepartcount getcfiledate _t getcfiledate theprefs getdatetimeformat getresstring ids_never cstring ispartfile getresstring ids_dl_sources _t getresstring ids_sourcesinfo _t getsourcecount getvalidsourcescount getsrcstatisticsvalue ds_noneededparts getsrca4afcount cstring _t getresstring ids_ondisk castitoxbytes getrealfilesize _t cstring gettransferringsrccount getresstring ids_partinfos2 _t gettransferringsrccount _t getpartfilestatus cstring getresstring ids_dl_filename _t getresstring ids_fd_hash _t getresstring ids_fd_size _t getresstring ids_fd_met _t getresstring ids_status _t _t _t getresstring ids_lastseencompl _t _t getresstring ids_fd_lastchange _t getfilename getfilehash castitoxbytes getfilesize getpartmetfilename void c part file update displayed info bool force if the app emuledlg is running dword cur tick get tick count if force cur tick m lastrefresheddldisplay minwait before dldisplay windowupdate m random update wait the app emuledlg transferwnd downloadlistctrl update item this m lastrefresheddldisplay cur tick cpartfile updatedisplayedinfo theapp isrunning curtick gettickcount curtick m_lastrefresheddldisplay minwait_before_dldisplay_windowupdate m_random_update_wait theapp updateitem m_lastrefresheddldisplay curtick uint c part file get category const if m category uint the prefs get cat count 1 m category 0 return m category cpartfile getcategory m_category theprefs getcatcount m_category m_category void c part file set category uint cat m category cat zz download manager set new prio if is part file save part file zz download manager cpartfile setcategory m_category downloadmanager ispartfile savepartfile downloadmanager bool c part file check show item in given cat int in category const int myfilter the prefs get cat filter in category common cases if uint in category get category myfilter 0 return true if in category 0 get category uint in category the prefs get category in category care4all return false bool ret true if myfilter 0 if myfilter 4 myfilter 8 is part file ret false else switch myfilter case 1 ret get category 0 break case 2 ret is part file break case 3 ret is part file break case 4 ret get status ps ready get status ps empty get transferring src count 0 break case 5 ret get status ps ready get status ps empty get transferring src count 0 break case 6 ret get status ps error break case 7 ret get status ps paused is stopped break case 8 ret lastseencomplete null break case 10 ret is movie break case 11 ret ed2kft audio geted2k file typeid get file name break case 12 ret is archive break case 13 ret ed2kft cdimage geted2k file typeid get file name break case 14 ret ed2kft document geted2k file typeid get file name break case 15 ret ed2kft image geted2k file typeid get file name break case 16 ret ed2kft program geted2k file typeid get file name break case 18 ret regular expression match the prefs get category in category regexp get file name break case 20 ret ed2kft emulecollection geted2k file typeid get file name break return the prefs get cat filter neg in category ret ret cpartfile checkshowitemingivencat incategory theprefs getcatfilter incategory incategory getcategory incategory getcategory incategory theprefs getcategory incategory ispartfile getcategory ispartfile ispartfile getstatus ps_ready getstatus ps_empty gettransferringsrccount getstatus ps_ready getstatus ps_empty gettransferringsrccount getstatus ps_error getstatus ps_paused isstopped ismovie ed2kft_audio geted2kfiletypeid getfilename isarchive ed2kft_cdimage geted2kfiletypeid getfilename ed2kft_document geted2kfiletypeid getfilename ed2kft_image geted2kfiletypeid getfilename ed2kft_program geted2kfiletypeid getfilename regularexpressionmatch theprefs getcategory incategory getfilename ed2kft_emulecollection geted2kfiletypeid getfilename theprefs getcatfilterneg incategory uint8 c part file mm create part status create partstatus info in mobilemule protocol specs result needs to be deleted slow but not timecritical uint8 result new uint8 get part count 1 for uint i 0 i get part count i result i 0 if is complete uint64 i partsize uint64 i 1 partsize 1 false result i 1 continue else if is complete uint64 i partsize 0 partsize 3 uint64 i partsize 1 partsize 3 1 false result i 2 if is complete uint64 i partsize 1 partsize 3 uint64 i partsize 2 partsize 3 1 false result i 4 if is complete uint64 i partsize 2 partsize 3 uint64 i partsize 3 partsize 3 1 false result i 8 uint8 freq if m srcpartfrequency get count signed i freq uint8 m srcpartfrequency i else freq 0 if freq 44 freq 44 freq uint8 ceilf float freq 3 freq uint8 freq 4 result i uint8 result i freq return result cpartfile mmcreatepartstatus getpartcount getpartcount iscomplete iscomplete iscomplete iscomplete m_srcpartfrequency getcount m_srcpartfrequency bool c part file grab image uint8 n frames to grab double d start time bool b reduce color uint16 n max width void p sender if is part file return c known file grab image get path c string t get file name n frames to grab d start time b reduce color n max width p sender else if get status ps ready get status ps paused m bpreviewing get part count 2 is complete 0 partsize 1 true return false c string str file name remove file extension get full name if m filecompletemutex lock 100 m bpreviewing true try if m hpartfile m hfile invalid handle value m hpartfile close catch c file exception exception exception delete m filecompletemutex unlock m bpreviewing false return false else return false return c known file grab image str file name n frames to grab d start time b reduce color n max width p sender cpartfile grabimage nframestograb dstarttime breducecolor nmaxwidth psender ispartfile cknownfile grabimage getpath cstring _t getfilename nframestograb dstarttime breducecolor nmaxwidth psender getstatus ps_ready getstatus ps_paused m_bpreviewing getpartcount iscomplete cstring strfilename removefileextension getfullname m_filecompletemutex m_bpreviewing m_hpartfile m_hfile invalid_handle_value m_hpartfile cfileexception m_filecompletemutex m_bpreviewing cknownfile grabimage strfilename nframestograb dstarttime breducecolor nmaxwidth psender void c part file grabbing finished cx image img results uint8 n frames grabbed void p sender unlock and reopen the file if is part file c string str file name remove file extension get full name if m hpartfile open str file name c file mode read write c file share deny write c file os sequential scan uhuh that s really bad log error log statusbar get res string ids failedreopen remove file extension get part met file name get file name set status ps error stop file m bpreviewing false m filecompletemutex unlock continue processing c known file grabbing finished img results n frames grabbed p sender cpartfile grabbingfinished cximage imgresults nframesgrabbed psender ispartfile cstring strfilename removefileextension getfullname m_hpartfile strfilename cfile modereadwrite cfile sharedenywrite cfile ossequentialscan logerror log_statusbar getresstring ids_failedreopen removefileextension getpartmetfilename getfilename setstatus ps_error stopfile m_bpreviewing m_filecompletemutex cknownfile grabbingfinished imgresults nframesgrabbed psender void c part file flush buffers exception handler c file exception error if the prefs is check diskspace enabled error m cause c file exception disk full log error log statusbar get res string ids err outofspace get file name if the app emuledlg is running the prefs get notifier on important error c string msg msg format get res string ids err outofspace get file name the app emuledlg show notifier msg tbn importantevent c file exception disk full is also used for not enough min free space if the app emuledlg is running if the prefs is check diskspace enabled the prefs get min free disk space 0 the app downloadqueue check diskspace true else pause file true b insufficient else if the prefs is error beep enabled beep 800 200 if error m cause c file exception disk full log error log statusbar get res string ids err outofspace get file name may be called during shutdown if the app emuledlg is running the prefs get notifier on important error c string msg msg format get res string ids err outofspace get file name the app emuledlg show notifier msg tbn importantevent else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err writeerror get file name buffer set status ps error paused true m ilastpausepurge time null the app downloadqueue remove local server request this datarate 0 m anstates ds downloading 0 if the app emuledlg is running may be called during shutdown update displayed info error delete cpartfile flushbuffersexceptionhandler cfileexception theprefs ischeckdiskspaceenabled m_cause cfileexception diskfull logerror log_statusbar getresstring ids_err_outofspace getfilename theapp isrunning theprefs getnotifieronimportanterror cstring getresstring ids_err_outofspace getfilename theapp shownotifier tbn_importantevent cfileexception diskfull theapp isrunning theprefs ischeckdiskspaceenabled theprefs getminfreediskspace theapp checkdiskspace pausefile binsufficient theprefs iserrorbeepenabled m_cause cfileexception diskfull logerror log_statusbar getresstring ids_err_outofspace getfilename theapp isrunning theprefs getnotifieronimportanterror cstring getresstring ids_err_outofspace getfilename theapp shownotifier tbn_importantevent max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_writeerror getfilename setstatus ps_error m_ilastpausepurge theapp removelocalserverrequest m_anstates ds_downloading theapp isrunning updatedisplayedinfo void c part file flush buffers exception handler assert 0 log error log statusbar get res string ids err writeerror get file name get res string ids unknown set status ps error paused true m ilastpausepurge time null the app downloadqueue remove local server request this datarate 0 m anstates ds downloading 0 if the app emuledlg is running may be called during shutdown update displayed info cpartfile flushbuffersexceptionhandler logerror log_statusbar getresstring ids_err_writeerror getfilename getresstring ids_unknown setstatus ps_error m_ilastpausepurge theapp removelocalserverrequest m_anstates ds_downloading theapp isrunning updatedisplayedinfo void c part file perform file complete end dword dw result if dw result file completion thread success set status ps complete set status and update status modification related gui elements the app knownfiles safe addk file this the app downloadqueue remove file this the app mmserver add finished file this if the prefs get remove finished downloads the app emuledlg transferwnd downloadlistctrl remove file this else update displayed info true the app emuledlg transferwnd downloadlistctrl show files count the prefs add2 down completed files the prefs add2 down session completed files the prefs save completed downloads stat 05 j n 2004 bc ed2k and kad are already full of totally wrong and or not properly attached meta data take the chance to clean any available meta data tags and provide only tags which were determined by us update meta data tags republish that file to the ed2k server to update the ft complete sources counter on the server the app sharedfiles republish file this give visual response log log success log statusbar get res string ids downloaddone get file name the app emuledlg show notifier get res string ids tbn downloaddone t n get file name tbn downloadfinished get file path if dw result file completion thread renamed c string str file path get full name path strip path str file path get buffer str file path release buffer log log statusbar get res string ids downloadrenamed str file path if m pcollection c collection has collection extention get file name m pcollection new c collection if m pcollection init collection from file get file path get file name delete m pcollection m pcollection null the app downloadqueue start next file if prefs get category cpartfile performfilecompleteend dwresult dwresult file_completion_thread_success setstatus ps_complete theapp safeaddkfile theapp removefile theapp addfinishedfile theprefs getremovefinisheddownloads theapp removefile updatedisplayedinfo theapp showfilescount theprefs add2downcompletedfiles theprefs add2downsessioncompletedfiles theprefs savecompleteddownloadsstat updatemetadatatags ft_complete_sources theapp republishfile log_success log_statusbar getresstring ids_downloaddone getfilename theapp shownotifier getresstring ids_tbn_downloaddone _t getfilename tbn_downloadfinished getfilepath dwresult file_completion_thread_renamed cstring strfilepath getfullname pathstrippath strfilepath getbuffer strfilepath releasebuffer log_statusbar getresstring ids_downloadrenamed strfilepath m_pcollection ccollection hascollectionextention getfilename m_pcollection ccollection m_pcollection initcollectionfromfile getfilepath getfilename m_pcollection m_pcollection theapp startnextfileifprefs getcategory void c part file set file op e part file op e file op m efileop e file op cpartfile setfileop epartfileop efileop m_efileop efileop void c part file set file op progress uint u progress assert u progress 100 m ufileopprogress u progress cpartfile setfileopprogress uprogress uprogress m_ufileopprogress uprogress void c part file requestaich recovery uint16 n part if m paichhashset has valid master hash m paichhashset get status aich trusted m paichhashset get status aich verified add debug log line dlp default false t unable to request aich recoverydata because we have no trusted masterhash return if get file size uint64 emblocksize get file size partsize uint64 n part uint64 emblocksize return if caich hash set is client request pending this n part add debug log line dlp default false t requestaich recovery already a request for this part pending return first check if we have already the recoverydata no need to rerequest it then if m paichhashset is part data available uint64 n part partsize add debug log line dlp default false t found part recovery data in memory aich recovery data available n part return assert n part get part count find some random client which support aich to ask for the blocks first lets see how many we have at all we prefer high id very much uint32 caich clients 0 uint32 caich lowid clients 0 for position pos srclist get head position pos null c up down client p cur client srclist get next pos if p cur client is supportingaich p cur client get req fileaich hash null p cur client isaich req pending p cur client get req fileaich hash m paichhashset get master hash if p cur client has lowid caich lowid clients else caich clients if caich clients caich lowid clients 0 add debug log line dlp default false t unable to request aich recoverydata because found no client who supports it and has the same hash as the trusted one return uint32 n seclected client if caich clients 0 n seclected client rand caich clients 1 else n seclected client rand caich lowid clients 1 c up down client p client null for position pos srclist get head position pos null c up down client p cur client srclist get next pos if p cur client is supportingaich p cur client get req fileaich hash null p cur client isaich req pending p cur client get req fileaich hash m paichhashset get master hash if caich clients 0 if p cur client has lowid n seclected client else assert p cur client has lowid n seclected client if n seclected client 0 p client p cur client break if p client null assert false return add debug log line dlp default false t requesting aich hash s form client s caich clients t high id t lowid p client dbg get client info p client sendaich request this n part cpartfile requestaichrecovery npart m_paichhashset hasvalidmasterhash m_paichhashset getstatus aich_trusted m_paichhashset getstatus aich_verified adddebuglogline dlp_default _t getfilesize getfilesize npart caichhashset isclientrequestpending npart adddebuglogline dlp_default _t requestaichrecovery m_paichhashset ispartdataavailable npart adddebuglogline dlp_default _t partrecoverydata aichrecoverydataavailable npart npart getpartcount caichclients caichlowidclients getheadposition cupdownclient pcurclient getnext pcurclient issupportingaich pcurclient getreqfileaichhash pcurclient isaichreqpending pcurclient getreqfileaichhash m_paichhashset getmasterhash pcurclient haslowid caichlowidclients caichclients caichclients caichlowidclients adddebuglogline dlp_default _t nseclectedclient caichclients nseclectedclient caichclients nseclectedclient caichlowidclients cupdownclient pclient getheadposition cupdownclient pcurclient getnext pcurclient issupportingaich pcurclient getreqfileaichhash pcurclient isaichreqpending pcurclient getreqfileaichhash m_paichhashset getmasterhash caichclients pcurclient haslowid nseclectedclient pcurclient haslowid nseclectedclient nseclectedclient pclient pcurclient pclient adddebuglogline dlp_default _t caichclients _t highid _t pclient dbggetclientinfo pclient sendaichrequest npart void c part file aich recovery data available uint16 n part if get part count n part assert false return flush buffer true true true uint32 length partsize if ulonglong partsize uint64 n part 1 m hpartfile get length length uint m hpartfile get length ulonglong partsize uint64 n part assert length partsize if the part was already ok it would now be complete if is complete uint64 n part partsize uint64 n part partsize length 1 true add debug log line dlp default false t processing aich recovery data the part u is already complete canceling return caich hash tree p verified hash m paichhashset m phashtree find hash uint64 n part partsize length if p verified hash null p verified hash m bhashvalid add debug log line dlp default false t processing aich recovery data unable to get verified hash from hashset should never happen assert false return caich hash tree ht our hash p verified hash m ndatasize p verified hash m bisleftbranch p verified hash m nbasesize try m hpartfile seek longlong partsize uint64 n part 0 create hash m hpartfile length null ht our hash catch assert false return if ht our hash m bhashvalid add debug log line dlp default false t processing aich recovery data failed to retrieve aich hashset of corrupt part assert false return now compare the hash we just did to the verified hash and readd all blocks which are ok uint32 n recovered 0 for uint32 pos 0 pos length pos emblocksize const uint32 n block size min emblocksize length pos caich hash tree p verified block p verified hash find hash pos n block size caich hash tree p our block ht our hash find hash pos n block size if p verified block null p our block null p verified block m bhashvalid p our block m bhashvalid assert false continue if p our block m hash p verified block m hash fill gap partsize uint64 n part pos partsize uint64 n part pos n block size 1 remove block from list partsize uint64 n part pos partsize uint64 n part pos n block size 1 n recovered n block size tell the blackbox about the verified data m corruptionblackbox verified data partsize uint64 n part pos partsize uint64 n part pos n block size 1 else inform our blackbox about the corrupted block which may ban clients who sent it m corruptionblackbox corrupted data partsize uint64 n part pos partsize uint64 n part pos n block size 1 if m ucorruptionloss n recovered m ucorruptionloss n recovered if the prefs ses lost from corruption n recovered the prefs ses lost from corruption n recovered ok now some sanity checks if is complete uint64 n part partsize uint64 n part partsize length 1 true this is a bad but it could probably happen under some rare circumstances make sure that md4 agrres to this fact too if hash single part n part add debug log line dlp default false t processing aich recovery data the part u got completed while recovering but md4 says it corrupt setting hashset to error state deleting part now we are fu unhappy m paichhashset set status aich error add gap partsize uint64 n part uint64 n part partsize length 1 assert false return else add debug log line dlp default false t processing aich recovery data the part u got completed while recovering and md4 agrees alrighty not so bad position pos corrupted corrupted list find n part if pos corrupted corrupted list remove at pos corrupted if status ps empty the app emuledlg is running if get hash count geted2k part hash count hashsetneeded successfully recovered part make it available for sharing set status ps ready the app sharedfiles safe addk file this if the app emuledlg is running is this file finished if gaplist is empty complete file false end sanity check update met file save part file make sure the user appreciates our great recovering work p add log line true get res string ids aich worked cast itox bytes n recovered cast itox bytes length n part get file name aich successfully recovered s of s from part u for s cpartfile aichrecoverydataavailable npart getpartcount npart flushbuffer npart m_hpartfile getlength m_hpartfile getlength npart iscomplete npart npart adddebuglogline dlp_default _t caichhashtree pverifiedhash m_paichhashset m_phashtree findhash npart pverifiedhash pverifiedhash m_bhashvalid adddebuglogline dlp_default _t caichhashtree htourhash pverifiedhash m_ndatasize pverifiedhash m_bisleftbranch pverifiedhash m_nbasesize m_hpartfile npart createhash m_hpartfile htourhash htourhash m_bhashvalid adddebuglogline dlp_default _t nrecovered nblocksize caichhashtree pverifiedblock pverifiedhash findhash nblocksize caichhashtree pourblock htourhash findhash nblocksize pverifiedblock pourblock pverifiedblock m_bhashvalid pourblock m_bhashvalid pourblock m_hash pverifiedblock m_hash fillgap npart npart nblocksize removeblockfromlist npart npart nblocksize nrecovered nblocksize m_corruptionblackbox verifieddata npart npart nblocksize m_corruptionblackbox corrupteddata npart npart nblocksize m_ucorruptionloss nrecovered m_ucorruptionloss nrecovered theprefs seslostfromcorruption nrecovered theprefs seslostfromcorruption nrecovered iscomplete npart npart hashsinglepart npart adddebuglogline dlp_default _t m_paichhashset setstatus aich_error addgap npart npart adddebuglogline dlp_default _t poscorrupted corrupted_list npart poscorrupted corrupted_list removeat poscorrupted ps_empty theapp isrunning gethashcount geted2kparthashcount setstatus ps_ready theapp safeaddkfile theapp isrunning isempty completefile savepartfile addlogline getresstring ids_aich_worked castitoxbytes nrecovered castitoxbytes npart getfilename uint c part file get max sources const ignore any specified max sources value if not in extended mode don t use a parameter which was once specified in gui but can not be seen modified any longer return the prefs is ext controls enabled m umaxsources 0 the prefs get max source per file default m umaxsources cpartfile getmaxsources theprefs isextcontrolsenabled m_umaxsources theprefs getmaxsourceperfiledefault m_umaxsources uint c part file get max source per file soft const uint temp uint get max sources 9l 10 if temp max sources file soft return max sources file soft return temp cpartfile getmaxsourceperfilesoft getmaxsources max_sources_file_soft max_sources_file_soft uint c part file get max source per fileudp const uint temp uint get max sources 3l 4 if temp max sources file udp return max sources file udp return temp cpartfile getmaxsourceperfileudp getmaxsources max_sources_file_udp max_sources_file_udp bool c part file right file has higher prio c part file left c part file right if right return false if left the prefs get category right get category prio the prefs get category left get category prio the prefs get category right get category prio the prefs get category left get category prio right get down priority left get down priority right get down priority left get down priority right get category left get category right get category 0 the prefs get category right get category download in alphabetical order the prefs is ext controls enabled right get file name left get file name right get file name compare no case left get file name 0 return true else return false cpartfile rightfilehashigherprio cpartfile cpartfile theprefs getcategory getcategory theprefs getcategory getcategory theprefs getcategory getcategory theprefs getcategory getcategory getdownpriority getdownpriority getdownpriority getdownpriority getcategory getcategory getcategory theprefs getcategory getcategory downloadinalphabeticalorder theprefs isextcontrolsenabled getfilename getfilename getfilename comparenocase getfilename bool c part file get next empty block in part uint16 part number requested block struct result const gap struct first gap gap struct current gap uint64 end uint64 block limit find start of this part uint64 part start partsize uint64 part number uint64 start part start what is the end limit of this block i e can t go outside part or filesize uint64 part end partsize uint64 part number 1 1 if part end get file size part end get file size uint64 1 assert part start part end loop until find a suitable gap and return true or no more gaps and return false for first gap null find the first gap from the start position for position pos gaplist get head position pos 0 current gap gaplist get next pos want gaps that overlap start part end if current gap start part end current gap end start is this the first gap if first gap null current gap start first gap start first gap current gap if no gaps after start exit if first gap null return false update start position if gap starts after current pos if start first gap start start first gap start if this is not within part exit if start part end return false find end keeping within the max block size and the part limit end first gap end block limit part start emblocksize start part start emblocksize 1 1 if end block limit end block limit if end part end end part end if this gap has not already been requested we have found a valid entry if is already requested start end was this block to be returned if result null result start offset start result end offset end md4cpy result fileid get file hash result transferred 0 return true else uint64 temp start start uint64 temp end end bool shrink succeeded shrink to avoid already requested temp start temp end if shrink succeeded add debug log line false t shrunk interval to prevent collision with already requested block old interval i i new interval i i file s start end temp start temp end get file name was this block to be returned if result null result start offset temp start result end offset temp end md4cpy result fileid get file hash result transferred 0 return true else reposition to end of that gap start end 1 if tried all gaps then break out of the loop if end part end break no suitable gap found return false cpartfile getnextemptyblockinpart partnumber requested_block_struct gap_struct firstgap gap_struct currentgap blocklimit partstart partnumber partstart partend partnumber partend getfilesize partend getfilesize partstart partend firstgap getheadposition currentgap getnext partend currentgap partend currentgap firstgap currentgap firstgap firstgap currentgap firstgap firstgap firstgap partend firstgap blocklimit partstart partstart blocklimit blocklimit partend partend isalreadyrequested startoffset endoffset getfilehash tempstart tempend shrinksucceeded shrinktoavoidalreadyrequested tempstart tempend shrinksucceeded adddebuglogline _t tempstart tempend getfilename startoffset tempstart endoffset tempend getfilehash partend void c part file complete file bool b is hashing done the app downloadqueue remove local server request this if get kad file searchid kademlia c search manager stop search get kad file searchid false if srcarevisible the app emuledlg transferwnd downloadlistctrl hide sources this if b is hashing done set status ps completing datarate 0 c add file thread addfilethread c add file thread afx begin thread runtime class c add file thread thread priority below normal 0 create suspended if addfilethread set file op pfop hashing set file op progress 0 tchar mytemppath max path tcscpy mytemppath m fullname mytemppath tcslen mytemppath tcslen m partmetfilename 1 0 addfilethread set values 0 mytemppath remove file extension m partmetfilename this addfilethread resume thread else log error log statusbar get res string ids err filecompletionthread set status ps error return else stop file set status ps completing c win thread p thread afx begin thread complete thread proc this thread priority below normal 0 create suspended lord ki ron using threads for file completion if p thread set file op pfop copying set file op progress 0 p thread resume thread else log error log statusbar get res string ids err filecompletionthread set status ps error return the app emuledlg transferwnd downloadlistctrl show files count if the prefs show cat tab infos the app emuledlg transferwnd update cat tab titles update displayed info true cpartfile completefile bishashingdone theapp removelocalserverrequest getkadfilesearchid csearchmanager stopsearch getkadfilesearchid theapp hidesources bishashingdone setstatus ps_completing caddfilethread caddfilethread afxbeginthread runtime_class caddfilethread thread_priority_below_normal create_suspended setfileop pfop_hashing setfileopprogress max_path _tcscpy m_fullname _tcslen _tcslen m_partmetfilename setvalues removefileextension m_partmetfilename resumethread logerror log_statusbar getresstring ids_err_filecompletionthread setstatus ps_error stopfile setstatus ps_completing cwinthread pthread afxbeginthread completethreadproc thread_priority_below_normal create_suspended kiron pthread setfileop pfop_copying setfileopprogress pthread resumethread logerror log_statusbar getresstring ids_err_filecompletionthread setstatus ps_error theapp showfilescount theprefs showcattabinfos theapp updatecattabtitles updatedisplayedinfo void c part file create part file uint cat if m nfilesize uint64 max emule file size log error log statusbar get res string ids err createpartfile set status ps error return decide which tempfolder to use c string tempdirtouse the app downloadqueue get optimal temp dir cat get file size use lowest free partfilenumber for free file inter ceptor int i 0 c string filename do i filename format t s 03i part tempdirtouse i while path file exists filename m partmetfilename format t 03i part met i set path tempdirtouse m fullname format t s s tempdirtouse m partmetfilename c tag partnametag new c tag ft partfilename remove file extension m partmetfilename taglist add partnametag gap struct gap new gap struct gap start 0 gap end m nfilesize uint64 1 gaplist add tail gap c string partfull remove file extension m fullname set file path partfull if m hpartfile open partfull c file mode create c file mode read write c file share deny write c file os sequential scan log error log statusbar get res string ids err createpartfile set status ps error else if the prefs get sparse part files dword dw returned bytes 0 if device io control m hpartfile m hfile fsctl set sparse null 0 null 0 dw returned bytes null errors error invalid function returned by winxp when attempting to create a sparse file on a fat32 partition dword dw error get last error if dw error error invalid function the prefs get verbose log priority dlp verylow debug log error t failed to apply ntfs sparse file attribute to file s s partfull get error message dw error 1 struct stat fileinfo if tstat partfull fileinfo 0 m tlastmodified fileinfo st mtime m tcreated fileinfo st ctime else add debug log line false t failed to get file date for s hs partfull strerror errno m dwfileattributes get file attributes partfull if m dwfileattributes invalid file attributes m dwfileattributes 0 if geted2k part hash count 0 hashsetneeded false m srcpartfrequency set size get part count for uint i 0 i get part count i m srcpartfrequency i 0 paused false if the prefs auto filename cleanup set file name cleanup filename get file name save part file set active the app is connected cpartfile createpartfile m_nfilesize max_emule_file_size logerror log_statusbar getresstring ids_err_createpartfile setstatus ps_error cstring theapp getoptimaltempdir getfilesize interceptor cstring _t pathfileexists m_partmetfilename _t setpath m_fullname _t m_partmetfilename ctag ctag ft_partfilename removefileextension m_partmetfilename gap_struct gap_struct m_nfilesize addtail cstring removefileextension m_fullname setfilepath m_hpartfile cfile modecreate cfile modereadwrite cfile sharedenywrite cfile ossequentialscan logerror log_statusbar getresstring ids_err_createpartfile setstatus ps_error theprefs getsparsepartfiles dwreturnedbytes deviceiocontrol m_hpartfile m_hfile fsctl_set_sparse dwreturnedbytes error_invalid_function dwerror getlasterror dwerror error_invalid_function theprefs getverboselogpriority dlp_verylow debuglogerror _t geterrormessage dwerror _stat _tstat m_tlastmodified st_mtime m_tcreated st_ctime adddebuglogline _t m_dwfileattributes getfileattributes m_dwfileattributes invalid_file_attributes m_dwfileattributes geted2kparthashcount m_srcpartfrequency setsize getpartcount getpartcount m_srcpartfrequency theprefs autofilenamecleanup setfilename cleanupfilename getfilename savepartfile setactive theapp isconnected void c part file init newdate true m lastsearchtime 0 m lastsearchtimekad 0 m totalsearcheskad 0 lastpurgetime get tick count paused false stopped false status ps empty insufficient false m bcompletionerror false m utransferred 0 m ilastpausepurge time null m allocatethread null m iallocinfo 0 if the prefs get new auto down m idownpriority pr high m bautodownpriority true else m idownpriority pr normal m bautodownpriority false srcarevisible false memset m anstates 0 sizeof m anstates datarate 0 m umaxsources 0 hashsetneeded true count 0 percentcompleted 0 completedsize uint64 0 m bpreviewing false lastseencomplete null available parts count 0 m clientsrcanswered 0 m lastnoneededcheck 0 m urating 0 void m strcomment m ntotalbufferdata 0 m nlastbufferflushtime 0 m brecoveringarchive false m ucompressiongain 0 m ucorruptionloss 0 m upartssaveddueich 0 m category 0 m lastrefresheddldisplay 0 m blocalsrcreqqueued false memset src stats 0 sizeof src stats memset net stats 0 sizeof net stats m ncompletesourcestime time null m ncompletesourcescount 0 m ncompletesourcescountlo 0 m ncompletesourcescounthi 0 m dwfileattributes 0 m bdeleteafteralloc false m tactivated 0 m ndlactivetime 0 m tlastmodified uint 1 m tutclastmodified uint 1 m tcreated 0 m efileop pfop none m ufileopprogress 0 m bpreviewprio false m random update wait uint32 rand rand max 1000 last swap for source exchange tick get tick count m deadsourcelist init false cpartfile m_lastsearchtime m_lastsearchtimekad m_totalsearcheskad gettickcount ps_empty m_bcompletionerror m_utransferred m_ilastpausepurge m_allocatethread m_iallocinfo theprefs getnewautodown m_idownpriority pr_high m_bautodownpriority m_idownpriority pr_normal m_bautodownpriority m_anstates m_anstates m_umaxsources m_bpreviewing availablepartscount m_clientsrcanswered m_lastnoneededcheck m_urating m_strcomment m_ntotalbufferdata m_nlastbufferflushtime m_brecoveringarchive m_ucompressiongain m_ucorruptionloss m_upartssaveddueich m_category m_lastrefresheddldisplay m_blocalsrcreqqueued src_stats src_stats net_stats net_stats m_ncompletesourcestime m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi m_dwfileattributes m_bdeleteafteralloc m_tactivated m_ndlactivetime m_tlastmodified m_tutclastmodified m_tcreated m_efileop pfop_none m_ufileopprogress m_bpreviewprio m_random_update_wait rand_max lastswapforsourceexchangetick gettickcount m_deadsourcelist bool c part file perform file complete if that function is invoked from within the file completion thread it s ok if we wait and block the thread c single lock s lock m filecompletemutex true c string str partfilename remove file extension m fullname tchar newfilename tcsdup get file name tcscpy newfilename lpctstr strip invalid filename chars newfilename c string str newname c string indir if path file exists the prefs get category get category incomingpath indir the prefs get category get category incomingpath str newname format t s s indir newfilename else indir the prefs get incoming dir str newname format t s s indir newfilename close permanent handle try if m hpartfile m hfile invalid handle value m hpartfile close catch c file exception error tchar buffer max cfexp errormsg error get error message buffer arrsize buffer the app queue log line true get res string ids err fileerror m partmetfilename get file name buffer error delete return false bool renamed false if path file exists str newname renamed true int namecount 0 size t length tcslen newfilename assert length 0 name should never be 0 the file extension tchar ext tcsrchr newfilename t if ext null ext newfilename length tchar last ext new end is the file name before extension last 0 0 truncate file name search for matching s and check if it contains a number if ext newfilename tcsrchr newfilename t 1 last tchar first tcsrchr newfilename t if first null first bool found true for tchar step first step last 1 step if step t 0 step t 9 found false break if found namecount tstoi first last first 1 last 0 0 truncate again c string str test name do namecount str test name format t s s d s indir newfilename namecount min ext 1 newfilename length while path file exists str test name str newname str test name free newfilename dword dw move result if dw move result move completed part file str partfilename str newname this error success the app queue log line true get res string ids err completionfailed t s get error message dw move result get file name str newname if the destination file path is too long the default system error message may not be helpful for user to know what failed if str newname get length max path the app queue log line true get res string ids err completionfailed t s path too long get file name str newname paused true stopped true set status ps error m bcompletionerror true set file op pfop none if the app emuledlg the app emuledlg is running verify post message the app emuledlg m hwnd tm filecompleted file completion thread failed lparam this return false uncompress file str newname this to have the accurate date stored in known met we have to update the date of a just completed file if we don t update the file date here after commiting the file and before adding the record to known met that file will be rehashed at next startup and there would also be a duplicate entry hash size in known met because of different file date assert m hpartfile m hfile invalid handle value the file must be closed commited struct stat st if tstat str newname st 0 m tlastmodified st st mtime m tutclastmodified m tlastmodified adjustntfs daylight file time m tutclastmodified str newname remove part met file if tremove m fullname the app queue log line true get res string ids err deletefailed t c string strerror errno m fullname remove backup files c string bak name m fullname bak name append partmet bak ext if taccess bak name 0 0 delete file bak name the app queue log line true get res string ids err delete t get error message get last error bak name bak name m fullname bak name append partmet tmp ext if taccess bak name 0 0 delete file bak name the app queue log line true get res string ids err delete t get error message get last error bak name initialize this part file for being a complete file this is to be done before releasing the file mutex m fullname str newname set path indir set file path m fullname setstatus ps complete set status of c part file object but do not update gui to avoid multi thread problems paused false set file op pfop none clear the blackbox to free up memory m corruptionblackbox free explicitly unlock the file before posting something to the main thread s lock unlock if the app emuledlg the app emuledlg is running verify post message the app emuledlg m hwnd tm filecompleted file completion thread success renamed file completion thread renamed 0 lparam this return true cpartfile performfilecomplete csinglelock slock m_filecompletemutex cstring strpartfilename removefileextension m_fullname _tcsdup getfilename _tcscpy stripinvalidfilenamechars cstring strnewname cstring pathfileexists theprefs getcategory getcategory theprefs getcategory getcategory strnewname _t theprefs getincomingdir strnewname _t m_hpartfile m_hfile invalid_handle_value m_hpartfile cfileexception max_cfexp_errormsg geterrormessage theapp queuelogline getresstring ids_err_fileerror m_partmetfilename getfilename pathfileexists strnewname size_t _tcslen _tcsrchr _t _tcsrchr _t _tcsrchr _t _t _t _tstoi cstring strtestname strtestname _t pathfileexists strtestname strnewname strtestname dwmoveresult dwmoveresult movecompletedpartfile strpartfilename strnewname error_success theapp queuelogline getresstring ids_err_completionfailed _t geterrormessage dwmoveresult getfilename strnewname strnewname getlength max_path theapp queuelogline getresstring ids_err_completionfailed _t getfilename strnewname setstatus ps_error m_bcompletionerror setfileop pfop_none theapp theapp isrunning postmessage theapp m_hwnd tm_filecompleted file_completion_thread_failed uncompressfile strnewname m_hpartfile m_hfile invalid_handle_value _stat _tstat strnewname m_tlastmodified st_mtime m_tutclastmodified m_tlastmodified adjustntfsdaylightfiletime m_tutclastmodified strnewname _tremove m_fullname theapp queuelogline getresstring ids_err_deletefailed _t cstring m_fullname cstring bakname m_fullname bakname partmet_bak_ext _taccess bakname deletefile bakname theapp queuelogline getresstring ids_err_delete _t geterrormessage getlasterror bakname bakname m_fullname bakname partmet_tmp_ext _taccess bakname deletefile bakname theapp queuelogline getresstring ids_err_delete _t geterrormessage getlasterror bakname m_fullname strnewname setpath setfilepath m_fullname _setstatus ps_complete cpartfile setfileop pfop_none m_corruptionblackbox slock theapp theapp isrunning postmessage theapp m_hwnd tm_filecompleted file_completion_thread_success file_completion_thread_renamed uint c part file complete thread proc lpvoid pv params dbg set thread name part file complete init thread locale c part file p file c part file pv params if p file return uint 1 p file perform file complete return 0 cpartfile completethreadproc pvparams dbgsetthreadname partfilecomplete initthreadlocale cpartfile pfile cpartfile pvparams pfile pfile performfilecomplete uint afx cdecl c part file allocate space thread lpvoid lp param dbg set thread name partfile allocate space init thread locale c part file myfile c part file lp param the app queue debug log line false t alloc start s s myfile get file name cast itox bytes myfile m iallocinfo false false try if this is a ntfs compressed file and the current block is the 1st one to be written and there is not enough free disk space to hold the entire uncompressed file windows throws a disk full myfile m hpartfile set length myfile m iallocinfo allocate disk space may throw disk full force the alloc by temporary writing a non zero to the fileend byte x 255 myfile m hpartfile seek 1 c file end myfile m hpartfile write x 1 myfile m hpartfile flush x 0 myfile m hpartfile seek 1 c file end myfile m hpartfile write x 0 myfile m hpartfile flush catch c file exception error verify post message the app emuledlg m hwnd tm fileallocexc wparam myfile lparam error myfile m allocatethread null return 1 catch verify post message the app emuledlg m hwnd tm fileallocexc wparam myfile 0 myfile m allocatethread null return 2 myfile m allocatethread null the app queue debug log line false t alloc end s myfile get file name return 0 afx_cdecl cpartfile allocatespacethread lpparam dbgsetthreadname initthreadlocale cpartfile cpartfile lpparam theapp queuedebuglogline _t getfilename castitoxbytes m_iallocinfo diskfull m_hpartfile setlength m_iallocinfo diskfull m_hpartfile cfile m_hpartfile m_hpartfile m_hpartfile cfile m_hpartfile m_hpartfile cfileexception postmessage theapp m_hwnd tm_fileallocexc m_allocatethread postmessage theapp m_hwnd tm_fileallocexc m_allocatethread m_allocatethread theapp queuedebuglogline _t getfilename void c part file char fill range c string buffer uint32 start uint32 end char color const for uint32 i start i end i buffer set at i color cpartfile charfillrange cstring setat c client credits c client credits credit struct in credits m pcredits in credits initalize ident m dwunsecurewaittime 0 m dwsecurewaittime 0 m dwwaittimeip 0 cclientcredits cclientcredits creditstruct in_credits m_pcredits in_credits initalizeident m_dwunsecurewaittime m_dwsecurewaittime m_dwwaittimeip c client credits c client credits const uchar key m pcredits new credit struct memset m pcredits 0 sizeof credit struct md4cpy m pcredits aby key key initalize ident m dwunsecurewaittime get tick count m dwsecurewaittime get tick count m dwwaittimeip 0 cclientcredits cclientcredits m_pcredits creditstruct m_pcredits creditstruct m_pcredits abykey initalizeident m_dwunsecurewaittime gettickcount m_dwsecurewaittime gettickcount m_dwwaittimeip c client credits c client credits delete m pcredits cclientcredits cclientcredits m_pcredits void c client credits clear wait start time m dwunsecurewaittime 0 m dwsecurewaittime 0 cclientcredits clearwaitstarttime m_dwunsecurewaittime m_dwsecurewaittime void c client credits add downloaded uint32 bytes uint32 dw forip if get current ident state dw forip is idfailed get current ident state dw forip is idbadguy get current ident state dw forip is idneeded the app clientcredits crypto available return encode uint64 current m pcredits n downloaded hi current current 32 m pcredits n downloaded lo bytes recode m pcredits n downloaded lo uint32 current m pcredits n downloaded hi uint32 current 32 cclientcredits adddownloaded dwforip getcurrentidentstate dwforip is_idfailed getcurrentidentstate dwforip is_idbadguy getcurrentidentstate dwforip is_idneeded theapp cryptoavailable m_pcredits ndownloadedhi m_pcredits ndownloadedlo m_pcredits ndownloadedlo m_pcredits ndownloadedhi void c client credits add uploaded uint32 bytes uint32 dw forip if get current ident state dw forip is idfailed get current ident state dw forip is idbadguy get current ident state dw forip is idneeded the app clientcredits crypto available return encode uint64 current m pcredits n uploaded hi current current 32 m pcredits n uploaded lo bytes recode m pcredits n uploaded lo uint32 current m pcredits n uploaded hi uint32 current 32 cclientcredits adduploaded dwforip getcurrentidentstate dwforip is_idfailed getcurrentidentstate dwforip is_idbadguy getcurrentidentstate dwforip is_idneeded theapp cryptoavailable m_pcredits nuploadedhi m_pcredits nuploadedlo m_pcredits nuploadedlo m_pcredits nuploadedhi uint64 c client credits get uploaded total const return uint64 m pcredits n uploaded hi 32 m pcredits n uploaded lo cclientcredits getuploadedtotal m_pcredits nuploadedhi m_pcredits nuploadedlo uint64 c client credits get downloaded total const return uint64 m pcredits n downloaded hi 32 m pcredits n downloaded lo cclientcredits getdownloadedtotal m_pcredits ndownloadedhi m_pcredits ndownloadedlo float c client credits get score ratio uint32 dw forip const check the client ident status if get current ident state dw forip is idfailed get current ident state dw forip is idbadguy get current ident state dw forip is idneeded the app clientcredits crypto available bad guy no credits for you return 1 0f if get downloaded total 1000000 return 1 0f float result 0 0f if get uploaded total result 10 0f else result float double get downloaded total 2 0 double get uploaded total float result2 0 0f result2 float get downloaded total 1048576 0 result2 2 0f result2 float sqrt result2 if result result2 result result2 if result 1 0f return 1 0f else if result 10 0f return 10 0f return result cclientcredits getscoreratio dwforip getcurrentidentstate dwforip is_idfailed getcurrentidentstate dwforip is_idbadguy getcurrentidentstate dwforip is_idneeded theapp cryptoavailable getdownloadedtotal getuploadedtotal getdownloadedtotal getuploadedtotal getdownloadedtotal bool c client credits set secure ident const uchar pach ident uint8 n ident len verified public key cannot change use only if there is not public key yet if maxpubkeysize n ident len m pcredits n key size 0 return false memcpy m abypublickey pach ident n ident len m npublickeylen n ident len ident state is idneeded return true cclientcredits setsecureident pachident nidentlen nidentlen m_pcredits nkeysize m_abypublickey pachident nidentlen m_npublickeylen nidentlen identstate is_idneeded e ident state c client credits get current ident state uint32 dw forip const if ident state is identified return ident state else if dw forip m dwidentip return is identified else return is idbadguy mod note clients which just reconnected after an ip change and have to ident yet will also have this state for 1 2 seconds so don t try to spam such clients with bad guy messages besides spam messages are always bad eidentstate cclientcredits getcurrentidentstate dwforip identstate is_identified identstate dwforip m_dwidentip is_identified is_idbadguy uint32 c client credits get secure wait start time uint32 dw forip if m dwunsecurewaittime 0 m dwsecurewaittime 0 set sec wait start time dw forip if m pcredits n key size 0 this client is a secure hash client if get current ident state dw forip is identified good boy return m dwsecurewaittime else not so good boy if dw forip m dwwaittimeip return m dwunsecurewaittime else bad boy this can also happen if the client has not identified himself yet but will do later so maybe he is not a bad boy c string buffer2 buffer for uint16 i 0 i 16 i buffer2 format 02x this m pcredits aby key i buffer buffer2 if the prefs get log secure ident add debug log line false warning wait time resetted due to invalid ident for userhash s buffer m dwunsecurewaittime get tick count m dwwaittimeip dw forip return m dwunsecurewaittime else not a secure hash client handle it like before for now no security checks return m dwunsecurewaittime cclientcredits getsecurewaitstarttime dwforip m_dwunsecurewaittime m_dwsecurewaittime setsecwaitstarttime dwforip m_pcredits nkeysize securehash getcurrentidentstate dwforip is_identified m_dwsecurewaittime dwforip m_dwwaittimeip m_dwunsecurewaittime cstring m_pcredits abykey theprefs getlogsecureident adddebuglogline waittime m_dwunsecurewaittime gettickcount m_dwwaittimeip dwforip m_dwunsecurewaittime securehash m_dwunsecurewaittime void c client credits set sec wait start time uint32 dw forip m dwunsecurewaittime get tick count 1 m dwsecurewaittime get tick count 1 m dwwaittimeip dw forip cclientcredits setsecwaitstarttime dwforip m_dwunsecurewaittime gettickcount m_dwsecurewaittime gettickcount m_dwwaittimeip dwforip void c client credits verified uint32 dw forip m dwidentip dw forip client was verified copy the keyto store him if not done already if m pcredits n key size 0 m pcredits n key size m npublickeylen memcpy m pcredits aby secure ident m abypublickey m npublickeylen if get downloaded total 0 for security reason we have to delete all prior credits here m pcredits n downloaded hi 0 m pcredits n downloaded lo 1 m pcredits n uploaded hi 0 m pcredits n uploaded lo 1 in order to safe this client set 1 byte if the prefs get verbose debug only add debug log line false t credits deleted due to new secure ident ident state is identified cclientcredits dwforip m_dwidentip dwforip m_pcredits nkeysize m_pcredits nkeysize m_npublickeylen m_pcredits abysecureident m_abypublickey m_npublickeylen getdownloadedtotal m_pcredits ndownloadedhi m_pcredits ndownloadedlo m_pcredits nuploadedhi m_pcredits nuploadedlo theprefs getverbose debug_only adddebuglogline _t secureident identstate is_identified void c client credits initalize ident if m pcredits n key size 0 memset m abypublickey 0 80 for debugging m npublickeylen 0 ident state is notavailable else m npublickeylen m pcredits n key size memcpy m abypublickey m pcredits aby secure ident m npublickeylen ident state is idneeded m dwcryptrndchallengefor 0 m dwcryptrndchallengefrom 0 m dwidentip 0 cclientcredits initalizeident m_pcredits nkeysize m_abypublickey m_npublickeylen identstate is_notavailable m_npublickeylen m_pcredits nkeysize m_abypublickey m_pcredits abysecureident m_npublickeylen identstate is_idneeded m_dwcryptrndchallengefor m_dwcryptrndchallengefrom m_dwidentip c known file c known file m ipartcount 0 m ied2kpartcount 0 m ied2kparthashcount 0 m tutclastmodified uint 1 if the prefs get new auto up m iuppriority pr high m bautouppriority true else m iuppriority pr normal m bautouppriority false statistic file parent this void m strcomment m publisheded2k false kad file searchid 0 set last publish time kad src 0 0 m ncompletesourcestime time null m ncompletesourcescount 1 m ncompletesourcescountlo 1 m ncompletesourcescounthi 1 m umetadataver 0 m lastpublishtimekadsrc 0 m lastpublishtimekadnotes 0 m lastbuddyip 0 m paichhashset new caich hash set this m pcollection null cknownfile cknownfile m_ipartcount m_ied2kpartcount m_ied2kparthashcount m_tutclastmodified theprefs getnewautoup m_iuppriority pr_high m_bautouppriority m_iuppriority pr_normal m_bautouppriority fileparent m_strcomment m_publisheded2k kadfilesearchid setlastpublishtimekadsrc m_ncompletesourcestime m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi m_umetadataver m_lastpublishtimekadsrc m_lastpublishtimekadnotes m_lastbuddyip m_paichhashset caichhashset m_pcollection c known file c known file for int i 0 i hashlist get size i delete hashlist i delete m paichhashset delete m pcollection cknownfile cknownfile getsize m_paichhashset m_pcollection void c known file set file name lpctstr psz file name bool b replace invalid file system chars c known file p file null if this is called within the sharedfiles object during startup we cannot reference it yet if the app sharedfiles p file the app sharedfiles get file byid get file hash if p file p file this the app sharedfiles remove keywords this c abstract file set file name psz file name b replace invalid file system chars wordlist clear if m pcollection c string s key words s key words format t s s m pcollection get collection author key string get file name kademlia c search manager get words s key words wordlist else kademlia c search manager get words get file name wordlist if p file p file this the app sharedfiles add keywords this cknownfile setfilename pszfilename breplaceinvalidfilesystemchars cknownfile pfile theapp pfile theapp getfilebyid getfilehash pfile pfile theapp removekeywords cabstractfile setfilename pszfilename breplaceinvalidfilesystemchars m_pcollection cstring skeywords skeywords _t m_pcollection getcollectionauthorkeystring getfilename csearchmanager getwords skeywords csearchmanager getwords getfilename pfile pfile theapp addkeywords void c known file set path lpctstr path m strdirectory path cknownfile setpath m_strdirectory void c known file set file path lpctstr psz file path m strfilepath psz file path cknownfile setfilepath pszfilepath m_strfilepath pszfilepath void c known file add uploading client c up down client client position pos m clientuploadlist find client to be sure if pos null m clientuploadlist add tail client update auto up priority cknownfile adduploadingclient cupdownclient m_clientuploadlist m_clientuploadlist addtail updateautouppriority void c known file remove uploading client c up down client client position pos m clientuploadlist find client to be sure if pos null m clientuploadlist remove at pos update auto up priority cknownfile removeuploadingclient cupdownclient m_clientuploadlist m_clientuploadlist removeat updateautouppriority void c known file update parts info cache part count uint partcount get part count bool flag time null m ncompletesourcestime 0 reset part counters if uint m availpartfrequency get size partcount m availpartfrequency set size partcount for uint i 0 i partcount i m availpartfrequency i 0 c array uint16 uint16 count if flag count set size 0 m clientuploadlist get size for position pos m clientuploadlist get head position pos 0 c up down client cur src m clientuploadlist get next pos this could be a partfile that just completed many of these clients will not have this information if cur src m abyuppartstatus cur src get up part count partcount for uint i 0 i partcount i if cur src is up part available i m availpartfrequency i 1 if flag count add cur src get up complete sources count if flag m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi 0 if partcount 0 m ncompletesourcescount m availpartfrequency 0 for uint i 1 i partcount i if m ncompletesourcescount m availpartfrequency i m ncompletesourcescount m availpartfrequency i count add m ncompletesourcescount 1 plus 1 since we have the file complete too int n count get size if n 0 slugfiller heapsort completesrc int r for r n 2 r heap sort count r n 1 for r n r uint16 t count r count r count 0 count 0 t heap sort count 0 r 1 slugfiller heapsort completesrc calculate range int i n 1 n 2 int j n 3 2 n 3 4 int k n 7 3 n 7 8 for complete files trust the people your uploading to more for low guess and normal guess count if we see more sources then the guessed low and normal use what we see if we see less sources then the guessed low adjust network accounts for 100 we account for 0 with what we see and make sure we are still above the normal for high guess adjust 100 network and 0 what we see if n 20 if count get at i m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescount else m ncompletesourcescountlo count get at i m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi count get at j if m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcescounthi m ncompletesourcescount else many sources for low guess use what we see for normal guess adjust network accounts for 100 we account for 0 with what we see and make sure we are still above the low for high guess adjust network accounts for 100 we account for 0 with what we see and make sure we are still above the normal m ncompletesourcescountlo m ncompletesourcescount m ncompletesourcescount count get at j if m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescount m ncompletesourcescountlo m ncompletesourcescounthi count get at k if m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcescounthi m ncompletesourcescount m ncompletesourcestime time null 60 if the app emuledlg sharedfileswnd m hwnd the app emuledlg sharedfileswnd sharedfilesctrl update file this cknownfile updatepartsinfo getpartcount m_ncompletesourcestime m_availpartfrequency getsize m_availpartfrequency setsize m_availpartfrequency carray setsize m_clientuploadlist getsize m_clientuploadlist getheadposition cupdownclient cur_src m_clientuploadlist getnext cur_src m_abyuppartstatus cur_src getuppartcount cur_src isuppartavailable m_availpartfrequency cur_src getupcompletesourcescount m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi m_ncompletesourcescount m_availpartfrequency m_ncompletesourcescount m_availpartfrequency m_ncompletesourcescount m_availpartfrequency m_ncompletesourcescount getsize heapsortcompletesrc heapsort heapsort heapsortcompletesrc getat m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescountlo getat m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi getat m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescount getat m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescount m_ncompletesourcescountlo m_ncompletesourcescounthi getat m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcescounthi m_ncompletesourcescount m_ncompletesourcestime theapp m_hwnd theapp updatefile void c known file draw share status bar cdc dc lpcrect rect bool onlygreyrect bool b flat const s sharestatusbar set file size get file size s sharestatusbar set height rect bottom rect top s sharestatusbar set width rect right rect left if m clientuploadlist get size 0 m ncompletesourcescounthi 1 we have info about chunk frequency in the net so we will color the chunks we have after perceived availability const colorref cr missing rgb 255 0 0 s sharestatusbar fill cr missing if onlygreyrect colorref cr progress colorref cr have colorref cr pending if b flat cr progress rgb 0 150 0 cr have rgb 0 0 0 cr pending rgb 255 208 0 else cr progress rgb 0 224 0 cr have rgb 104 104 104 cr pending rgb 255 208 0 uint32 temp complete sources m ncompletesourcescountlo if temp complete sources 0 temp complete sources for uint i 0 i get part count i uint32 frequency temp complete sources if m availpartfrequency is empty frequency max m availpartfrequency i temp complete sources if frequency 0 colorref color rgb 0 22 frequency 1 210 0 210 22 frequency 1 255 s sharestatusbar fill range partsize uint64 i partsize uint64 i 1 color else we have no info about chunk frequency in the net so just color the chunk we have as black colorref cr noone asked if b flat cr noone asked rgb 0 0 0 else cr noone asked rgb 104 104 104 s sharestatusbar fill cr noone asked s sharestatusbar draw dc rect left rect top b flat cknownfile drawsharestatusbar bflat s_sharestatusbar setfilesize getfilesize s_sharestatusbar setheight s_sharestatusbar setwidth m_clientuploadlist getsize m_ncompletesourcescounthi crmissing s_sharestatusbar crmissing crprogress crhave crpending bflat crprogress crhave crpending crprogress crhave crpending tempcompletesources m_ncompletesourcescountlo tempcompletesources tempcompletesources getpartcount tempcompletesources m_availpartfrequency isempty m_availpartfrequency tempcompletesources s_sharestatusbar fillrange crnooneasked bflat crnooneasked crnooneasked s_sharestatusbar crnooneasked s_sharestatusbar bflat void c known file update file rating comment avail bool b old has comment m bhascomment uint u old user ratings m uuserrating m bhascomment false uint u ratings 0 uint u user ratings 0 for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos if m bhascomment entry get str tag value tag description is empty m bhascomment true uint rating uint entry get int tag value tag filerating if rating 0 u ratings u user ratings rating if u ratings m uuserrating u user ratings u ratings else m uuserrating 0 if b old has comment m bhascomment u old user ratings m uuserrating the app emuledlg sharedfileswnd sharedfilesctrl update file this cknownfile updatefileratingcommentavail boldhascomment m_bhascomment uolduserratings m_uuserrating m_bhascomment uratings uuserratings m_kadnotes getheadposition centry m_kadnotes getnext m_bhascomment getstrtagvalue tag_description isempty m_bhascomment getinttagvalue tag_filerating uratings uuserratings uratings m_uuserrating uuserratings uratings m_uuserrating boldhascomment m_bhascomment uolduserratings m_uuserrating theapp updatefile c statistic file requested 0 transferred 0 accepted 0 alltimerequested 0 alltimetransferred 0 alltimeaccepted 0 cstatisticfile void c statistic file merge file stats c statistic file to merge requested to merge get requests accepted to merge get accepts transferred to merge get transferred alltimerequested to merge get all time requests alltimetransferred to merge get all time transferred alltimeaccepted to merge get all time accepts cstatisticfile mergefilestats cstatisticfile tomerge tomerge getrequests tomerge getaccepts tomerge gettransferred tomerge getalltimerequests tomerge getalltimetransferred tomerge getalltimeaccepts void c statistic file add request requested alltimerequested the app knownfiles requested the app sharedfiles update file file parent cstatisticfile addrequest theapp theapp updatefile fileparent void c statistic file add accepted accepted alltimeaccepted the app knownfiles accepted the app sharedfiles update file file parent cstatisticfile addaccepted theapp theapp updatefile fileparent void c statistic file add transferred uint64 bytes transferred bytes alltimetransferred bytes the app knownfiles transferred bytes the app sharedfiles update file file parent cstatisticfile addtransferred theapp theapp updatefile fileparent m name name m type type m_name m_type bool is str const return m type tagtype string isstr m_type tagtype_string bool is num const return m type tagtype uint64 m type tagtype uint32 m type tagtype uint16 m type tagtype uint8 m type tagtype bool m type tagtype float32 m type 0xfe isnum m_type tagtype_uint64 m_type tagtype_uint32 m_type tagtype_uint16 m_type tagtype_uint8 m_type tagtype_bool m_type tagtype_float32 m_type bool is int const return m type tagtype uint64 m type tagtype uint32 m type tagtype uint16 m type tagtype uint8 m type 0xfe isint m_type tagtype_uint64 m_type tagtype_uint32 m_type tagtype_uint16 m_type tagtype_uint8 m_type bool is float const return m type tagtype float32 isfloat m_type tagtype_float32 bool is bsob const return m type tagtype bsob isbsob m_type tagtype_bsob bool is hash const return m type tagtype hash ishash m_type tagtype_hash virtual uint64 get int const assert 0 return 0 getint virtual float get float const assert 0 return 0 0f getfloat virtual const byte get bsob const assert 0 return null getbsob virtual uint8 get bsob size const assert 0 return 0 getbsobsize virtual bool get bool const assert 0 return false getbool virtual const byte get hash const assert 0 return null gethash int compare lpcstr psz const throw atlassert atl is valid string psz do a binary string compare independant from any codepage and or lc ctype setting return strcmp get string psz atlisvalidstring lc_ctype getstring int compare no case lpcstr psz const throw atlassert atl is valid string psz version 1 do a case insensitive ascii string compare note the current locale category lc ctype must be set to c return stricmp get string psz version 2 independant from any codepage and or lc ctype setting return ascii stricmp get string psz comparenocase atlisvalidstring lc_ctype getstring lc_ctype __ascii_stricmp getstring c kad tag name string operator lpcstr psz src c stringa operator psz src return this ckadtagnamestring pszsrc cstringa pszsrc int get length const throw return c stringa get length getlength cstringa getlength virtual c kad tag unk copy return new c kad tag unk this ckadtagunk ckadtagunk virtual c kad tag str copy return new c kad tag str this ckadtagstr ckadtagstr virtual c kad tagu int copy return new c kad tagu int this ckadtaguint ckadtaguint virtual uint64 get int const return m value getint m_value virtual c kad tagu int64 copy return new c kad tagu int64 this ckadtaguint64 ckadtaguint64 virtual uint64 get int const return m value getint m_value virtual c kad tagu int32 copy return new c kad tagu int32 this ckadtaguint32 ckadtaguint32 virtual uint64 get int const return m value getint m_value virtual c kad tag float copy return new c kad tag float this ckadtagfloat ckadtagfloat virtual float get float const return m value getfloat m_value virtual c kad tag bool copy return new c kad tag bool this ckadtagbool ckadtagbool virtual bool get bool const return m value getbool m_value virtual c kad tagu int16 copy return new c kad tagu int16 this ckadtaguint16 ckadtaguint16 virtual uint64 get int const return m value getint m_value virtual c kad tagu int8 copy return new c kad tagu int8 this ckadtaguint8 ckadtaguint8 virtual uint64 get int const return m value getint m_value c kad tag tagtype bsob name m value new byte n size memcpy m value value n size m size n size ckadtag tagtype_bsob m_value nsize m_value nsize m_size nsize c kad tag r tag m value new byte r tag m size memcpy m value r tag m value r tag m size m size r tag m size ckadtag rtag m_value rtag m_size m_value rtag m_value rtag m_size m_size rtag m_size c kad tag bsob delete m value ckadtagbsob m_value virtual c kad tag bsob copy return new c kad tag bsob this ckadtagbsob ckadtagbsob virtual const byte get bsob const return m value getbsob m_value virtual uint8 get bsob size const return m size getbsobsize m_size c kad tag tagtype hash name m value new byte 16 md4cpy m value value ckadtag tagtype_hash m_value m_value c kad tag r tag m value new byte 16 md4cpy m value r tag m value ckadtag rtag m_value m_value rtag m_value c kad tag hash delete m value ckadtaghash m_value virtual c kad tag hash copy return new c kad tag hash this ckadtaghash ckadtaghash virtual const byte get hash const return m value gethash m_value c kademlia error int i error code lpcstr sz error description m ierrorcode i error code m szerrordescription sz error description ckademliaerror ierrorcode szerrordescription m_ierrorcode ierrorcode m_szerrordescription szerrordescription uint32 get download time return time downloads time thisdownload uint32 get server duration return time server duration time thisserverduration void add2 total server duration time server duration time thisserverduration time thisserverduration 0 getdownloadtime timedownloads time_thisdownload getserverduration timeserverduration time_thisserverduration add2totalserverduration timeserverduration time_thisserverduration time_thisserverduration void reset down datarate overhead void add down data overhead source exchange uint32 data m ndowndataratemsoverhead data m ndowndataoverheadsourceexchange data resetdowndatarateoverhead adddowndataoverheadsourceexchange m_ndowndataratemsoverhead m_ndowndataoverheadsourceexchange m ndowndataoverheadsourceexchangepackets void add down data overhead file request uint32 data m ndowndataratemsoverhead data m ndowndataoverheadfilerequest data m_ndowndataoverheadsourceexchangepackets adddowndataoverheadfilerequest m_ndowndataratemsoverhead m_ndowndataoverheadfilerequest m ndowndataoverheadfilerequestpackets void add down data overhead server uint32 data m ndowndataratemsoverhead data m ndowndataoverheadserver data m_ndowndataoverheadfilerequestpackets adddowndataoverheadserver m_ndowndataratemsoverhead m_ndowndataoverheadserver m ndowndataoverheadserverpackets void add down data overhead other uint32 data m ndowndataratemsoverhead data m ndowndataoverheadother data m_ndowndataoverheadserverpackets adddowndataoverheadother m_ndowndataratemsoverhead m_ndowndataoverheadother m ndowndataoverheadotherpackets void add down data overhead kad uint32 data m ndowndataratemsoverhead data m ndowndataoverheadkad data m_ndowndataoverheadotherpackets adddowndataoverheadkad m_ndowndataratemsoverhead m_ndowndataoverheadkad void reset up datarate overhead void add up data overhead source exchange uint32 data m nupdataratemsoverhead data m nupdataoverheadsourceexchange data resetupdatarateoverhead addupdataoverheadsourceexchange m_nupdataratemsoverhead m_nupdataoverheadsourceexchange m nupdataoverheadsourceexchangepackets void add up data overhead file request uint32 data m nupdataratemsoverhead data m nupdataoverheadfilerequest data m_nupdataoverheadsourceexchangepackets addupdataoverheadfilerequest m_nupdataratemsoverhead m_nupdataoverheadfilerequest m nupdataoverheadfilerequestpackets void add up data overhead server uint32 data m nupdataratemsoverhead data m nupdataoverheadserver data m_nupdataoverheadfilerequestpackets addupdataoverheadserver m_nupdataratemsoverhead m_nupdataoverheadserver m nupdataoverheadserverpackets void add up data overhead kad uint32 data m nupdataratemsoverhead data m nupdataoverheadkad data m_nupdataoverheadserverpackets addupdataoverheadkad m_nupdataratemsoverhead m_nupdataoverheadkad m nupdataoverheadkadpackets void add up data overhead other uint32 data m nupdataratemsoverhead data m nupdataoverheadother data m_nupdataoverheadkadpackets addupdataoverheadother m_nupdataratemsoverhead m_nupdataoverheadother c statistics c statistics max down 0 max downavg 0 maxcum down 0 cum upavg 0 maxcum downavg 0 cum downavg 0 maxcum upavg 0 maxcum up 0 max up 0 max upavg 0 rate down 0 rate up 0 time transfers 0 time downloads 0 time uploads 0 start timetransfers 0 start timedownloads 0 start timeuploads 0 time thistransfer 0 time thisdownload 0 time thisupload 0 time server duration 0 time thisserverduration 0 session received bytes 0 session sent bytes 0 session sent bytes to friend 0 reconnects 0 transfer starttime 0 server connect time 0 filteredclients 0 starttime 0 m ndowndataratemsoverhead 0 m ndowndatarateoverhead 0 m ndowndataoverheadsourceexchange 0 m ndowndataoverheadsourceexchangepackets 0 m ndowndataoverheadfilerequest 0 m ndowndataoverheadfilerequestpackets 0 m ndowndataoverheadserver 0 m ndowndataoverheadserverpackets 0 m ndowndataoverheadkad 0 m ndowndataoverheadkadpackets 0 m ndowndataoverheadother 0 m ndowndataoverheadotherpackets 0 m sumavgddro 0 m nupdataratemsoverhead 0 m nupdatarateoverhead 0 m nupdataoverheadsourceexchange 0 m nupdataoverheadsourceexchangepackets 0 m nupdataoverheadfilerequest 0 m nupdataoverheadfilerequestpackets 0 m nupdataoverheadserver 0 m nupdataoverheadserverpackets 0 m nupdataoverheadkad 0 m nupdataoverheadkadpackets 0 m nupdataoverheadother 0 m nupdataoverheadotherpackets 0 m sumavgudro 0 cstatistics cstatistics maxdown maxdownavg maxcumdown cumupavg maxcumdownavg cumdownavg maxcumupavg maxcumup maxup maxupavg ratedown rateup timetransfers timedownloads timeuploads start_timetransfers start_timedownloads start_timeuploads time_thistransfer time_thisdownload time_thisupload timeserverduration time_thisserverduration sessionreceivedbytes sessionsentbytes sessionsentbytestofriend transferstarttime serverconnecttime m_ndowndataratemsoverhead m_ndowndatarateoverhead m_ndowndataoverheadsourceexchange m_ndowndataoverheadsourceexchangepackets m_ndowndataoverheadfilerequest m_ndowndataoverheadfilerequestpackets m_ndowndataoverheadserver m_ndowndataoverheadserverpackets m_ndowndataoverheadkad m_ndowndataoverheadkadpackets m_ndowndataoverheadother m_ndowndataoverheadotherpackets m_sumavgddro m_nupdataratemsoverhead m_nupdatarateoverhead m_nupdataoverheadsourceexchange m_nupdataoverheadsourceexchangepackets m_nupdataoverheadfilerequest m_nupdataoverheadfilerequestpackets m_nupdataoverheadserver m_nupdataoverheadserverpackets m_nupdataoverheadkad m_nupdataoverheadkadpackets m_nupdataoverheadother m_nupdataoverheadotherpackets m_sumavgudro void c statistics init maxcum down the prefs get conn max down rate cum upavg the prefs get conn avg up rate maxcum downavg the prefs get conn max avg down rate cum downavg the prefs get conn avg down rate maxcum upavg the prefs get conn max avg up rate maxcum up the prefs get conn max up rate cstatistics maxcumdown theprefs getconnmaxdownrate cumupavg theprefs getconnavguprate maxcumdownavg theprefs getconnmaxavgdownrate cumdownavg theprefs getconnavgdownrate maxcumupavg theprefs getconnmaxavguprate maxcumup theprefs getconnmaxuprate void c statistics record rate if the stats transfer starttime 0 return accurate datarate calculation uint32 stick get tick count transferred data newitemup uint the stats session sent bytes stick transferred data newitemdn uint the stats session received bytes stick downrate history push front newitemdn uprate history push front newitemup limit to maxmins uint u average milliseconds the prefs get stats average minutes 60000 while downrate history front timestamp downrate history back timestamp u average milliseconds downrate history pop back while uprate history front timestamp uprate history back timestamp u average milliseconds uprate history pop back cstatistics recordrate thestats transferstarttime gettickcount transferreddata thestats sessionsentbytes transferreddata thestats sessionreceivedbytes downratehistory push_front upratehistory push_front uaveragemilliseconds theprefs getstatsaverageminutes downratehistory downratehistory uaveragemilliseconds downratehistory pop_back upratehistory upratehistory uaveragemilliseconds upratehistory pop_back float c statistics get avg download rate int average type dword running switch average type case avg session if the stats transfer starttime 0 return 0 0f running get tick count the stats transfer starttime 1000 if running 5 return 0 0f return float the stats session received bytes 1024 running case avg total if the stats transfer starttime 0 return the prefs get conn avg down rate running get tick count the stats transfer starttime 1000 if running 5 return the prefs get conn avg down rate return float the stats session received bytes 1024 running the prefs get conn avg down rate 2 0f default if downrate history size 0 return 0 0f float deltat downrate history front timestamp downrate history back timestamp 1000 0f if deltat 0 0f return downrate history front datalen downrate history back datalen deltat 1024 0f return 0 0f cstatistics getavgdownloadrate averagetype averagetype avg_session thestats transferstarttime gettickcount thestats transferstarttime thestats sessionreceivedbytes avg_total thestats transferstarttime theprefs getconnavgdownrate gettickcount thestats transferstarttime theprefs getconnavgdownrate thestats sessionreceivedbytes theprefs getconnavgdownrate downratehistory downratehistory downratehistory downratehistory downratehistory float c statistics get avg upload rate int average type dword running switch average type case avg session if the stats transfer starttime 0 return 0 0f running get tick count the stats transfer starttime 1000 if running 5 return 0 0f return float the stats session sent bytes 1024 running case avg total if the stats transfer starttime 0 return the prefs get conn avg up rate running get tick count the stats transfer starttime 1000 if running 5 return the prefs get conn avg up rate return float the stats session sent bytes 1024 running the prefs get conn avg up rate 2 0f default if uprate history size 0 return 0 0f float deltat uprate history front timestamp uprate history back timestamp 1000 0f if deltat 0 0f return uprate history front datalen uprate history back datalen deltat 1024 0f return 0 0f cstatistics getavguploadrate averagetype averagetype avg_session thestats transferstarttime gettickcount thestats transferstarttime thestats sessionsentbytes avg_total thestats transferstarttime theprefs getconnavguprate gettickcount thestats transferstarttime theprefs getconnavguprate thestats sessionsentbytes theprefs getconnavguprate upratehistory upratehistory upratehistory upratehistory upratehistory void c statistics update connection stats float uploadrate float downloadrate rate up uploadrate rate down downloadrate if max up uploadrate max up uploadrate if maxcum up max up maxcum up max up the prefs set conn max up rate maxcum up if max down downloadrate max down downloadrate if maxcum down max down maxcum down max down the prefs set conn max down rate maxcum down cum downavg get avg download rate avg total if maxcum downavg cum downavg maxcum downavg cum downavg the prefs set conn max avg down rate maxcum downavg cum upavg get avg upload rate avg total if maxcum upavg cum upavg maxcum upavg cum upavg the prefs set conn max avg up rate maxcum upavg transfer times increment session if uploadrate 0 downloadrate 0 if start timetransfers 0 start timetransfers get tick count else time thistransfer get tick count start timetransfers 1000 if uploadrate 0 if start timeuploads 0 start timeuploads get tick count else time thisupload get tick count start timeuploads 1000 if downloadrate 0 if start timedownloads 0 start timedownloads get tick count else time thisdownload get tick count start timedownloads 1000 if uploadrate 0 downloadrate 0 time thistransfer 0 start timetransfers 0 time transfers time thistransfer time thistransfer 0 start timetransfers 0 if uploadrate 0 time thisupload 0 start timeuploads 0 time uploads time thisupload time thisupload 0 start timeuploads 0 if downloadrate 0 time thisdownload 0 start timedownloads 0 time downloads time thisdownload time thisdownload 0 start timedownloads 0 server durations if the stats server connect time 0 time thisserverduration 0 else time thisserverduration get tick count the stats server connect time 1000 cstatistics updateconnectionstats rateup ratedown maxup maxup maxcumup maxup maxcumup maxup theprefs setconnmaxuprate maxcumup maxdown maxdown maxcumdown maxdown maxcumdown maxdown theprefs setconnmaxdownrate maxcumdown cumdownavg getavgdownloadrate avg_total maxcumdownavg cumdownavg maxcumdownavg cumdownavg theprefs setconnmaxavgdownrate maxcumdownavg cumupavg getavguploadrate avg_total maxcumupavg cumupavg maxcumupavg cumupavg theprefs setconnmaxavguprate maxcumupavg start_timetransfers start_timetransfers gettickcount time_thistransfer gettickcount start_timetransfers start_timeuploads start_timeuploads gettickcount time_thisupload gettickcount start_timeuploads start_timedownloads start_timedownloads gettickcount time_thisdownload gettickcount start_timedownloads time_thistransfer start_timetransfers timetransfers time_thistransfer time_thistransfer start_timetransfers time_thisupload start_timeuploads timeuploads time_thisupload time_thisupload start_timeuploads time_thisdownload start_timedownloads timedownloads time_thisdownload time_thisdownload start_timedownloads thestats serverconnecttime time_thisserverduration time_thisserverduration gettickcount thestats serverconnecttime void c statistics comp down datarate overhead transferred data newitem m ndowndataratemsoverhead get tick count m avarageddro list add tail newitem m sumavgddro m ndowndataratemsoverhead m ndowndataratemsoverhead 0 while m avarageddro list get tail timestamp m avarageddro list get head timestamp maxaveragetime m sumavgddro m avarageddro list remove head datalen if m avarageddro list get count 10 dword dw duration m avarageddro list get tail timestamp m avarageddro list get head timestamp if dw duration m ndowndatarateoverhead 1000 m sumavgddro m avarageddro list get head datalen dw duration else m ndowndatarateoverhead 0 cstatistics compdowndatarateoverhead transferreddata m_ndowndataratemsoverhead gettickcount m_avarageddro_list addtail m_sumavgddro m_ndowndataratemsoverhead m_ndowndataratemsoverhead m_avarageddro_list gettail m_avarageddro_list gethead m_sumavgddro m_avarageddro_list removehead m_avarageddro_list getcount dwduration m_avarageddro_list gettail m_avarageddro_list gethead dwduration m_ndowndatarateoverhead m_sumavgddro m_avarageddro_list gethead dwduration m_ndowndatarateoverhead void c statistics reset down datarate overhead m ndowndataratemsoverhead 0 m avarageddro list remove all m sumavgddro 0 m ndowndatarateoverhead 0 cstatistics resetdowndatarateoverhead m_ndowndataratemsoverhead m_avarageddro_list removeall m_sumavgddro m_ndowndatarateoverhead void c statistics comp up datarate overhead transferred data newitem m nupdataratemsoverhead get tick count m avarageudro list add tail newitem m sumavgudro m nupdataratemsoverhead m nupdataratemsoverhead 0 while m avarageudro list get tail timestamp m avarageudro list get head timestamp maxaveragetime m sumavgudro m avarageudro list remove head datalen if m avarageudro list get count 10 dword dw duration m avarageudro list get tail timestamp m avarageudro list get head timestamp if dw duration m nupdatarateoverhead 1000 m sumavgudro m avarageudro list get head datalen dw duration else m nupdatarateoverhead 0 cstatistics compupdatarateoverhead transferreddata m_nupdataratemsoverhead gettickcount m_avarageudro_list addtail m_sumavgudro m_nupdataratemsoverhead m_nupdataratemsoverhead m_avarageudro_list gettail m_avarageudro_list gethead m_sumavgudro m_avarageudro_list removehead m_avarageudro_list getcount dwduration m_avarageudro_list gettail m_avarageudro_list gethead dwduration m_nupdatarateoverhead m_sumavgudro m_avarageudro_list gethead dwduration m_nupdatarateoverhead void c statistics reset up datarate overhead m nupdataratemsoverhead 0 m sumavgudro 0 m avarageudro list remove all m nupdatarateoverhead 0 cstatistics resetupdatarateoverhead m_nupdataratemsoverhead m_sumavgudro m_avarageudro_list removeall m_nupdatarateoverhead c source hostname resolve wnd c source hostname resolve wnd csourcehostnameresolvewnd csourcehostnameresolvewnd c source hostname resolve wnd c source hostname resolve wnd while m toresolve is empty delete m toresolve remove head csourcehostnameresolvewnd csourcehostnameresolvewnd m_toresolve isempty m_toresolve removehead void c source hostname resolve wnd add to resolve const uchar fileid lpcstr psz hostname uint16 port lpctstr pszurl bool b resolving m toresolve is empty double checking if the app downloadqueue get file byid fileid return hostname entry entry new hostname entry md4cpy entry fileid fileid entry str hostname psz hostname entry port port entry strurl pszurl m toresolve add tail entry if b resolving return memset m auchostnamebuffer 0 sizeof m auchostnamebuffer if wsa async get host by name m hwnd wm hostnameresolved entry str hostname m auchostnamebuffer sizeof m auchostnamebuffer 0 return m toresolve remove head delete entry csourcehostnameresolvewnd addtoresolve pszhostname bresolving m_toresolve isempty theapp getfilebyid hostname_entry hostname_entry strhostname pszhostname m_toresolve addtail bresolving m_auchostnamebuffer m_auchostnamebuffer wsaasyncgethostbyname m_hwnd wm_hostnameresolved strhostname m_auchostnamebuffer m_auchostnamebuffer m_toresolve removehead lresult c source hostname resolve wnd on hostname resolved wparam w param lparam l param if m toresolve is empty return true hostname entry resolved m toresolve remove head if wsagetasyncerror l param 0 int i buf len wsagetasyncbuflen l param if i buf len sizeof hostent lphostent p host lphostent m auchostnamebuffer if p host h length 4 p host h addr list p host h addr list 0 uint32 nip lpin addr p host h addr list 0 s addr c part file file the app downloadqueue get file byid resolved fileid if file if resolved strurl is empty c safe mem file sources 1 4 2 sources writeu int8 1 sources writeu int32 nip sources writeu int16 resolved port sources seek to begin file add sources sources 0 0 else file add source resolved strurl nip delete resolved while m toresolve is empty hostname entry entry m toresolve get head memset m auchostnamebuffer 0 sizeof m auchostnamebuffer if wsa async get host by name m hwnd wm hostnameresolved entry str hostname m auchostnamebuffer sizeof m auchostnamebuffer 0 return true m toresolve remove head delete entry return true csourcehostnameresolvewnd onhostnameresolved wparam lparam m_toresolve isempty hostname_entry m_toresolve removehead lparam ibuflen lparam ibuflen phost m_auchostnamebuffer phost h_length phost h_addr_list phost h_addr_list lpin_addr phost h_addr_list s_addr cpartfile theapp getfilebyid isempty csafememfile writeuint8 writeuint32 writeuint16 seektobegin addsources addsource m_toresolve isempty hostname_entry m_toresolve gethead m_auchostnamebuffer m_auchostnamebuffer wsaasyncgethostbyname m_hwnd wm_hostnameresolved strhostname m_auchostnamebuffer m_auchostnamebuffer m_toresolve removehead c add file thread c add file thread m powner null m partfile null caddfilethread caddfilethread m_powner m_partfile bool c add file thread init instance init thread locale return true caddfilethread initinstance initthreadlocale int c add file thread run dbg set thread name hashing s m strfilename if m powner m partfile m strfilename is empty the app emuledlg is running return 0 co initialize null locking that hashing thread is needed because we may create a couple of those threads at startup when rehashing potentially corrupted downloading part files if all those hash threads would run concurrently the io system would be under very heavy load and slowly progressing c single lock s lock1 the app hashing mut only one filehash at a time s lock1 lock c string str file path tmakepath str file path get buffer max path null m strdirectory m strfilename null str file path release buffer if m partfile log get res string ids hashingfile t s s m partfile get file name str file path else log get res string ids hashingfile t s str file path c known file newrecord new c known file if newrecord create from file m strdirectory m strfilename m partfile the app emuledlg the app emuledlg is running slugfiller safe hash in case of shutdown while still hashing if m partfile m partfile get file op pfop hashing m partfile set file op pfop none verify post message the app emuledlg m hwnd tm finishedhashing m powner 0 wparam m partfile lparam newrecord else if the app emuledlg the app emuledlg is running if m partfile m partfile get file op pfop hashing m partfile set file op pfop none slugfiller safe hash inform main program of hash failure if m powner the app emuledlg the app emuledlg is running unknownfile struct hashed new unknownfile struct hashed str directory m strdirectory hashed str name m strfilename verify post message the app emuledlg m hwnd tm hashfailed 0 lparam hashed slugfiller safe hash delete newrecord s lock1 unlock co uninitialize return 0 caddfilethread dbgsetthreadname m_strfilename m_powner m_partfile m_strfilename isempty theapp isrunning coinitialize csinglelock slock1 theapp hashing_mut slock1 cstring strfilepath _tmakepath strfilepath getbuffer max_path m_strdirectory m_strfilename strfilepath releasebuffer m_partfile getresstring ids_hashingfile _t m_partfile getfilename strfilepath getresstring ids_hashingfile _t strfilepath cknownfile cknownfile createfromfile m_strdirectory m_strfilename m_partfile theapp theapp isrunning safehash m_partfile m_partfile getfileop pfop_hashing m_partfile setfileop pfop_none postmessage theapp m_hwnd tm_finishedhashing m_powner m_partfile theapp theapp isrunning m_partfile m_partfile getfileop pfop_hashing m_partfile setfileop pfop_none safehash m_powner theapp theapp isrunning unknownfile_struct unknownfile_struct strdirectory m_strdirectory strname m_strfilename postmessage theapp m_hwnd tm_hashfailed safehash slock1 couninitialize void c add file thread set values c shared file list p owner lpctstr directory lpctstr filename c part file partfile m powner p owner m strdirectory directory m strfilename filename m partfile partfile caddfilethread setvalues csharedfilelist powner cpartfile m_powner powner m_strdirectory m_strfilename m_partfile c tray dialog base uidd p parent m nidicondata cb size notifyicondata v1 size m nidicondata h wnd 0 m nidicondata uid 1 m nidicondata u callback message um tray icon notify message m nidicondata h icon 0 m nidicondata sz tip 0 t 0 m nidicondata u flags nif message m btrayiconvisible false m pbminimizetotray null m ndefaultmenuitem 0 m hprevicondelete null m bcuricondelete false m bdoubleclicked false m usingleclicktimer 0 ctraydialogbase pparent m_nidicondata cbsize notifyicondata_v1_size m_nidicondata hwnd m_nidicondata m_nidicondata ucallbackmessage um_tray_icon_notify_message m_nidicondata hicon m_nidicondata sztip _t m_nidicondata uflags nif_message m_btrayiconvisible m_pbminimizetotray m_ndefaultmenuitem m_hprevicondelete m_bcuricondelete m_bdoubleclicked m_usingleclicktimer void c tray dialog tray set minimize to tray bool pb minimize to tray m pbminimizetotray pb minimize to tray ctraydialog traysetminimizetotray pbminimizetotray m_pbminimizetotray pbminimizetotray bool c tray dialog tray set menu uint n resourceid bool b success m mnutraymenu load menu n resourceid assert b success return b success ctraydialog traysetmenu nresourceid bsuccess m_mnutraymenu loadmenu nresourceid bsuccess bsuccess bool c tray dialog tray set menu hmenu h menu m mnutraymenu attach h menu return true ctraydialog traysetmenu hmenu m_mnutraymenu hmenu bool c tray dialog tray set menu lpctstr lpsz menu name bool b success m mnutraymenu load menu lpsz menu name assert b success return b success ctraydialog traysetmenu lpszmenuname bsuccess m_mnutraymenu loadmenu lpszmenuname bsuccess bsuccess bool c tray dialog tray update bool b success false if m btrayiconvisible b success shell notifyicon nim modify m nidicondata if b success assert 0 return false don t delete m hprevicondelete because it s still attached to the tray if m hprevicondelete null verify destroy icon m hprevicondelete m hprevicondelete null return b success ctraydialog trayupdate bsuccess m_btrayiconvisible bsuccess shell_notifyicon nim_modify m_nidicondata bsuccess m_hprevicondelete m_hprevicondelete destroyicon m_hprevicondelete m_hprevicondelete bsuccess bool c tray dialog tray show bool b success false if m btrayiconvisible b success shell notifyicon nim add m nidicondata if b success m btrayiconvisible true return b success ctraydialog trayshow bsuccess m_btrayiconvisible bsuccess shell_notifyicon nim_add m_nidicondata bsuccess m_btrayiconvisible bsuccess bool c tray dialog tray hide bool b success false if m btrayiconvisible b success shell notifyicon nim delete m nidicondata if b success m btrayiconvisible false return b success ctraydialog trayhide bsuccess m_btrayiconvisible bsuccess shell_notifyicon nim_delete m_nidicondata bsuccess m_btrayiconvisible bsuccess void c tray dialog tray set tool tip lpctstr lpsz tool tip assert tcslen lpsz tool tip 0 tcslen lpsz tool tip notifyicondata v1 tip size tcsncpy m nidicondata sz tip lpsz tool tip notifyicondata v1 tip size m nidicondata sz tip notifyicondata v1 tip size 1 t 0 m nidicondata u flags nif tip shell notifyicon nim modify m nidicondata ctraydialog traysettooltip lpsztooltip _tcslen lpsztooltip _tcslen lpsztooltip notifyicondata_v1_tip_size _tcsncpy m_nidicondata sztip lpsztooltip notifyicondata_v1_tip_size m_nidicondata sztip notifyicondata_v1_tip_size _t m_nidicondata uflags nif_tip shell_notifyicon nim_modify m_nidicondata void c tray dialog tray set icon hicon h icon bool b delete assert h icon if h icon assert m hprevicondelete null if m bcuricondelete assert m nidicondata h icon null m nidicondata u flags nif icon m hprevicondelete m nidicondata h icon m bcuricondelete b delete m nidicondata h icon h icon m nidicondata u flags nif icon ctraydialog trayseticon hicon bdelete hicon hicon m_hprevicondelete m_bcuricondelete m_nidicondata hicon m_nidicondata uflags nif_icon m_hprevicondelete m_nidicondata hicon m_bcuricondelete bdelete m_nidicondata hicon hicon m_nidicondata uflags nif_icon void c tray dialog tray set icon uint n resourceid tray set icon afx get app load icon n resourceid ctraydialog trayseticon nresourceid trayseticon afxgetapp loadicon nresourceid void c tray dialog tray set icon lpctstr lpsz resource name tray set icon afx get app load icon lpsz resource name ctraydialog trayseticon lpszresourcename trayseticon afxgetapp loadicon lpszresourcename bool c tray dialog tray is visible return m btrayiconvisible ctraydialog trayisvisible m_btrayiconvisible void c tray dialog tray minimize to tray change if m pbminimizetotray null return if m pbminimizetotray min tray btn hide else min tray btn show ctraydialog trayminimizetotraychange m_pbminimizetotray m_pbminimizetotray mintraybtnhide mintraybtnshow void c tray dialog restore window show window sw show ctraydialog restorewindow showwindow sw_show void c tray dialog on trayl button down c point pt ctraydialog ontraylbuttondown cpoint void c tray dialog on trayl button up c point pt ctraydialog ontraylbuttonup cpoint void c tray dialog on trayl button dbl clk c point pt m bdoubleclicked true ctraydialog ontraylbuttondblclk cpoint m_bdoubleclicked void c tray dialog on trayr button up c point pt ctraydialog ontrayrbuttonup cpoint void c tray dialog on trayr button dbl clk c point pt ctraydialog ontrayrbuttondblclk cpoint void c tray dialog on tray mouse move c point pt ctraydialog ontraymousemove cpoint void c tray dialog kill single click timer if m usingleclicktimer verify kill timer m usingleclicktimer m usingleclicktimer 0 ctraydialog killsingleclicktimer m_usingleclicktimer killtimer m_usingleclicktimer m_usingleclicktimer lresult c tray dialog on tray notify wparam w param lparam l param uint uid uint w param if uid 1 return 0 c point pt uint u msg uint l param switch u msg case wm mousemove get cursor pos pt client to screen pt on tray mouse move pt break case wm lbuttondown get cursor pos pt client to screen pt on trayl button down pt break case wm lbuttonup if m bdoubleclicked kill single click timer restore window m bdoubleclicked false else if m usingleclicktimer 0 if is window visible m usingleclicktimer set timer idt single click 300 null break case wm lbuttondblclk kill single click timer get cursor pos pt client to screen pt on trayl button dbl clk pt break case wm rbuttonup case wm contextmenu kill single click timer get cursor pos pt client to screen pt on trayr button up pt bond006 systray menu gets stuck bugfix break case wm rbuttondblclk kill single click timer get cursor pos pt client to screen pt on trayr button dbl clk pt break return 1 ctraydialog ontraynotify wparam lparam wparam cpoint umsg lparam umsg wm_mousemove getcursorpos clienttoscreen ontraymousemove wm_lbuttondown getcursorpos clienttoscreen ontraylbuttondown wm_lbuttonup m_bdoubleclicked killsingleclicktimer restorewindow m_bdoubleclicked m_usingleclicktimer iswindowvisible m_usingleclicktimer settimer idt_single_click wm_lbuttondblclk killsingleclicktimer getcursorpos clienttoscreen ontraylbuttondblclk wm_rbuttonup wm_contextmenu killsingleclicktimer getcursorpos clienttoscreen ontrayrbuttonup wm_rbuttondblclk killsingleclicktimer getcursorpos clienttoscreen ontrayrbuttondblclk lresult c tray dialog on task bar created wparam w param lparam l param if m btrayiconvisible bool b result shell notifyicon nim add m nidicondata if b result m btrayiconvisible false return 0 ctraydialog ontaskbarcreated wparam lparam m_btrayiconvisible bresult shell_notifyicon nim_add m_nidicondata bresult m_btrayiconvisible int c tray dialog on create lpcreatestruct lp create struct if c tray dialog base on create lp create struct 1 return 1 assert wm taskbarcreated m nidicondata h wnd m hwnd m nidicondata uid 1 return 0 ctraydialog oncreate lpcreatestruct ctraydialogbase oncreate lpcreatestruct wm_taskbarcreated m_nidicondata hwnd m_hwnd m_nidicondata void c tray dialog on destroy kill single click timer c tray dialog base on destroy shouldn t that be done before passing the message to def win proc if m nidicondata h wnd m nidicondata uid 0 tray is visible verify shell notifyicon nim delete m nidicondata ctraydialog ondestroy killsingleclicktimer ctraydialogbase ondestroy defwinproc m_nidicondata hwnd m_nidicondata trayisvisible shell_notifyicon nim_delete m_nidicondata void c tray dialog on sys command uint nid lparam l param if m pbminimizetotray null m pbminimizetotray if nid 0xfff0 sc minimize if tray show show window sw hide else c tray dialog base on sys command nid l param else if nid 0xfff0 mp minimizetotray if tray show show window sw hide else c tray dialog base on sys command nid l param ctraydialog onsyscommand lparam m_pbminimizetotray m_pbminimizetotray sc_minimize trayshow showwindow sw_hide ctraydialogbase onsyscommand lparam mp_minimizetotray trayshow showwindow sw_hide ctraydialogbase onsyscommand lparam void c tray dialog on timer uint nid event if nid event m usingleclicktimer on trayl button up c point 0 0 kill single click timer c dialog min tray btn c resizable dialog on timer nid event ctraydialog ontimer nidevent nidevent m_usingleclicktimer ontraylbuttonup cpoint killsingleclicktimer cdialogmintraybtn cresizabledialog ontimer nidevent c meter icon c meter icon m nnumbars 2 m sdimensions cx 16 m sdimensions cy 16 m nmaxval 100 m nspacingwidth 0 m hframe null m binit false m crbordercolor rgb 0 0 0 m plimits null m pcolors null m nentries 0 cmetericon cmetericon m_nnumbars m_sdimensions m_sdimensions m_nmaxval m_nspacingwidth m_hframe m_binit m_crbordercolor m_plimits m_pcolors m_nentries c meter icon c meter icon free color list memory delete m plimits delete m pcolors cmetericon cmetericon m_plimits m_pcolors p limits is an array of int that contain the upper limit for the corresponding color begin set color levels free exsisting memory delete m plimits m plimits null new may throw an exception delete m pcolors m pcolors null new may throw an exception allocate new memory m plimits new int n entries m pcolors new colorref n entries copy values for int i 0 i n entries i begin copy m plimits i p limits i m pcolors i p colors i end copy m nentries n entries return true plimits setcolorlevels m_plimits m_plimits m_pcolors m_pcolors m_plimits nentries m_pcolors nentries nentries m_plimits plimits m_pcolors pcolors m_nentries nentries colorref c meter icon set border color colorref cr color begin set border color colorref cr old m crbordercolor m crbordercolor cr color return cr old cmetericon setbordercolor crcolor setbordercolor crold m_crbordercolor m_crbordercolor crcolor crold int c meter icon set num bars int n num begin set num bars int n old m nnumbars m nnumbars n num return n old cmetericon setnumbars nnum setnumbars nold m_nnumbars m_nnumbars nnum nold int c meter icon set max value int n val begin set max value int n old m nmaxval m nmaxval n val return n old cmetericon setmaxvalue nval setmaxvalue nold m_nmaxval m_nmaxval nval nold int c meter icon set width int n width begin set width int n old m nspacingwidth m nspacingwidth n width return n old cmetericon setwidth nwidth setwidth nold m_nspacingwidth m_nspacingwidth nwidth nold return the previous dimension begin set dimensions size s old m sdimensions m sdimensions cx n width m sdimensions cy n height return s old setdimensions sold m_sdimensions m_sdimensions nwidth m_sdimensions nheight sold cr color is the outline color for the bars begin init set frame h frame set width n spacing width set max value n max val set dimensions n width n height set num bars n num bars set border color cr color m binit true return m binit crcolor setframe hframe setwidth nspacingwidth setmaxvalue nmaxval setdimensions nwidth nheight setnumbars nnumbars setbordercolor crcolor m_binit m_binit must call init once before calling begin create if m binit return null return create meter icon p bar data m_binit createmetericon pbardata return the old frame icon begin set frame hicon h old m hframe m hframe h icon return h old setframe hold m_hframe m_hframe hicon hold bool c meter icon draw icon meter hdc h destdc hdc h destdc mask int n level int n pos begin draw icon meter draw meter hbrush h brush create solid brush get meter color n level if h brush null begin error check return false end error check hgdiobj h old brush select object h destdc h brush if h old brush null begin error check return false end error check hpen h pen create pen ps solid 1 m crbordercolor if h pen null return false hgdiobj h old pen select object h destdc h pen if h old pen null return false if rectangle h destdc m sdimensions cx 1 m nnumbars n pos m nspacingwidth m sdimensions cy n level m sdimensions cy 1 m nmaxval 1 m sdimensions cx 1 m nnumbars n pos 1 1 m sdimensions cy begin error check return false end error check if delete object select object h destdc h old pen begin error check return false end error check if delete object select object h destdc h old brush begin error check return false end error check draw meter mask hbrush h destdc mask brush create solid brush rgb 0 0 0 if h destdc mask brush null begin error check return false end error check hgdiobj h old destdc mask brush select object h destdc mask h destdc mask brush if h old destdc mask brush null begin error check return false end error check hpen h mask pen create pen ps solid 1 rgb 0 0 0 if h mask pen null return false hgdiobj h old mask pen select object h destdc mask h mask pen if h old mask pen null return false if n level 0 if rectangle h destdc mask m sdimensions cx 2 m sdimensions cy n level m sdimensions cy 1 m nmaxval 1 m sdimensions cx m sdimensions cy begin error check return false end error check if delete object select object h destdc mask h old mask pen begin error check return false end error check if delete object select object h destdc mask h old destdc mask brush begin error check return false end error check return true cmetericon drawiconmeter hdestdc hdestdcmask nlevel npos drawiconmeter hbrush createsolidbrush getmetercolor nlevel hbrush holdbrush selectobject hdestdc hbrush holdbrush hpen createpen ps_solid m_crbordercolor hpen holdpen selectobject hdestdc hpen holdpen hdestdc m_sdimensions m_nnumbars npos m_nspacingwidth m_sdimensions nlevel m_sdimensions m_nmaxval m_sdimensions m_nnumbars npos m_sdimensions deleteobject selectobject hdestdc holdpen deleteobject selectobject hdestdc holdbrush hdestdcmaskbrush createsolidbrush hdestdcmaskbrush holddestdcmaskbrush selectobject hdestdcmask hdestdcmaskbrush holddestdcmaskbrush hmaskpen createpen ps_solid hmaskpen holdmaskpen selectobject hdestdcmask hmaskpen holdmaskpen nlevel hdestdcmask m_sdimensions m_sdimensions nlevel m_sdimensions m_nmaxval m_sdimensions m_sdimensions deleteobject selectobject hdestdcmask holdmaskpen deleteobject selectobject hdestdcmask holddestdcmaskbrush the returned icon must be cleaned up using destroy icon begin create meter icon iconinfo ii new icon 0 ii new icon f icon true set that it is an icon create dc s hdc h screendc getdc null hdc h icondc create compatibledc h screendc hdc h maskdc create compatibledc h screendc if h screendc null begin error check return null end error check if h icondc null begin error check return null end error check if h maskdc null begin error check return null end error check load bitmaps ii new icon hbm color create compatible bitmap h screendc m sdimensions cx m sdimensions cy if ii new icon hbm color null begin error check return null end error check if releasedc null h screendc release this asap begin dc not released return null end dc not released ii new icon hbm mask create compatible bitmap h maskdc m sdimensions cx m sdimensions cy if ii new icon hbm mask null begin error check return null end error check hgdiobj h old icondc select object h icondc ii new icon hbm color if h old icondc null begin error check return null end error check hgdiobj h old maskdc select object h maskdc ii new icon hbm mask if h old maskdc null begin error check return null end error check initilize the bitmaps if bit blt h icondc 0 0 m sdimensions cx m sdimensions cy null 0 0 blackness begin bit blt failed return null end bit blt failed if bit blt h maskdc 0 0 m sdimensions cx m sdimensions cy null 0 0 whiteness begin bit blt failed return null end bit blt failed draw the meters for int i 0 i m nnumbars i if draw icon meter h icondc h maskdc p bar data i i false return false if draw icon ex h icondc 0 0 m hframe m sdimensions cx m sdimensions cy null null di normal di image begin error check return null end error check if draw icon ex h maskdc 0 0 m hframe m sdimensions cx m sdimensions cy null null di normal di mask begin error check return null end error check create icon select object h icondc h old icondc select object h maskdc h old maskdc hicon h new icon create icon indirect ii new icon cleanup delete object ii new icon hbm color delete object ii new icon hbm mask deletedc h maskdc deletedc h icondc return h new icon destroyicon createmetericon iinewicon iinewicon ficon hscreendc hicondc createcompatibledc hscreendc hmaskdc createcompatibledc hscreendc hscreendc hicondc hmaskdc iinewicon hbmcolor createcompatiblebitmap hscreendc m_sdimensions m_sdimensions iinewicon hbmcolor hscreendc iinewicon hbmmask createcompatiblebitmap hmaskdc m_sdimensions m_sdimensions iinewicon hbmmask holdicondc selectobject hicondc iinewicon hbmcolor holdicondc holdmaskdc selectobject hmaskdc iinewicon hbmmask holdmaskdc bitblt hicondc m_sdimensions m_sdimensions bitblt bitblt bitblt hmaskdc m_sdimensions m_sdimensions bitblt bitblt m_nnumbars drawiconmeter hicondc hmaskdc pbardata drawiconex hicondc m_hframe m_sdimensions m_sdimensions di_normal di_image drawiconex hmaskdc m_hframe m_sdimensions m_sdimensions di_normal di_mask selectobject hicondc holdicondc selectobject hmaskdc holdmaskdc hnewicon createiconindirect iinewicon deleteobject iinewicon hbmcolor deleteobject iinewicon hbmmask hmaskdc hicondc hnewicon it the n level is greater than the values defined in m plimits the last value in the array is used begin get meter color for int i 0 i m nentries i if n level m plimits i return m pcolors i default to the last entry return m pcolors m nentries 1 nlevel m_plimits getmetercolor m_nentries nlevel m_plimits m_pcolors m_pcolors m_nentries c title menu c title menu m clleft get sys color color activecaption m clright get sys color color gradientactivecaption m cltext get sys color color captiontext m hlibmsimg32 null m pfngradientfill null if g blowcolordesktop m hlibmsimg32 load library t msimg32 dll if m hlibmsimg32 m pfngradientfill lpfngradientfill get proc address m hlibmsimg32 gradient fill m bdrawedge false m uedgeflags bdr sunkeninner m biconmenu false m mapiconpos init hash table 29 ctitlemenu ctitlemenu m_clleft getsyscolor color_activecaption m_clright getsyscolor color_gradientactivecaption m_cltext getsyscolor color_captiontext m_hlibmsimg32 m_pfngradientfill g_blowcolordesktop m_hlibmsimg32 loadlibrary _t m_hlibmsimg32 m_pfngradientfill getprocaddress m_hlibmsimg32 gradientfill m_bdrawedge m_uedgeflags bdr_sunkeninner m_biconmenu m_mapiconpos inithashtable c title menu c title menu if m hlibmsimg32 free library m hlibmsimg32 ctitlemenu ctitlemenu m_hlibmsimg32 freelibrary m_hlibmsimg32 void c title menu enable icons if the prefs get windows version winver xp the prefs get windows version winver 2k m biconmenu true m imagelist delete image list m imagelist create iconsize iconsize the app m idfltimagelistcolorflags ilc mask 0 1 m imagelist set bk color clr none if loadapi menuinfo mi mi f mask mim style mi cb size sizeof mi get menu info m hmenu mi mi dw style mns checkorbmp set menu info m hmenu mi ctitlemenu enableicons theprefs getwindowsversion _winver_xp_ theprefs getwindowsversion _winver_2k_ m_biconmenu m_imagelist deleteimagelist m_imagelist theapp m_idfltimagelistcolorflags ilc_mask m_imagelist setbkcolor clr_none fmask mim_style cbsize getmenuinfo m_hmenu dwstyle mns_checkorbmp setmenuinfo m_hmenu void c title menu add menu title lpctstr lpsz title bool b is icon menu insert an empty owner draw item at top to serve as the title note item is not selectable disabled but not grayed if lpsz title null m strtitle lpsz title m strtitle replace t t c menu insert menu 0 mf byposition mf ownerdraw mf string mf disabled mp title if b is icon menu enable icons ctitlemenu addmenutitle lpsztitle bisiconmenu lpsztitle m_strtitle lpsztitle m_strtitle _t _t cmenu insertmenu mf_byposition mf_ownerdraw mf_string mf_disabled mp_title bisiconmenu enableicons bool c title menu append menu uint n flags uint ptr nid new item lpctstr lpsz new item lpctstr lpsz icon name bool b result c menu append menu n flags nid new item lpsz new item if b result set menu bitmap n flags nid new item lpsz new item lpsz icon name return b result ctitlemenu appendmenu nflags uint_ptr nidnewitem lpsznewitem lpsziconname bresult cmenu appendmenu nflags nidnewitem lpsznewitem bresult setmenubitmap nflags nidnewitem lpsznewitem lpsziconname bresult bool c title menu insert menu uint n position uint n flags uint ptr nid new item lpctstr lpsz new item lpctstr lpsz icon name bool b result c menu insert menu n position n flags nid new item lpsz new item if b result set menu bitmap n flags nid new item lpsz new item lpsz icon name return b result ctitlemenu insertmenu nposition nflags uint_ptr nidnewitem lpsznewitem lpsziconname bresult cmenu insertmenu nposition nflags nidnewitem lpsznewitem bresult setmenubitmap nflags nidnewitem lpsznewitem lpsziconname bresult void c title menu measure item lpmeasureitemstruct mi if mi itemid mp title cdc dc dc attach getdc null hfont hfont old hfont select object dc m hdc hfont the app m fontdefaultbold c size size dc get text extent m strtitle select object dc m hdc hfont old size cx get system metrics sm cxmenucheck 8 releasedc null dc detach const int n border size 2 mi item width size cx n border size mi item height size cy n border size else c menu measure item mi if m biconmenu mi item height max mi item height 16 mi item width 18 ctitlemenu measureitem mp_title hfontold selectobject m_hdc theapp m_fontdefaultbold csize gettextextent m_strtitle selectobject m_hdc hfontold getsystemmetrics sm_cxmenucheck nbordersize itemwidth nbordersize itemheight nbordersize cmenu measureitem m_biconmenu itemheight itemheight itemwidth void c title menu draw item lpdrawitemstruct di if di itemid mp title colorref cr old bk set bk color di hdc m clleft if g blowcolordesktop m pfngradientfill m clleft m clright trivertex rc vertex 2 di rc item right exclude this point like fill rect does di rc item bottom rc vertex 0 x di rc item left rc vertex 0 y di rc item top rc vertex 0 red getr value m clleft 8 color values from 0x0000 to 0xff00 rc vertex 0 green getg value m clleft 8 rc vertex 0 blue getb value m clleft 8 rc vertex 0 alpha 0x0000 rc vertex 1 x di rc item right rc vertex 1 y di rc item bottom rc vertex 1 red getr value m clright 8 rc vertex 1 green getg value m clright 8 rc vertex 1 blue getb value m clright 8 rc vertex 1 alpha 0 gradient rect rect rect upper left 0 rect lower right 1 m pfngradientfill di hdc rc vertex 2 rect 1 gradient fill rect h else ext text out di hdc 0 0 eto opaque di rc item null 0 null if m bdrawedge draw edge di hdc di rc item m uedgeflags bf rect int mode old set bk mode di hdc transparent colorref cr old set text color di hdc m cltext hfont hfont old hfont select object di hdc hfont the app m fontdefaultbold di rc item left get system metrics sm cxmenucheck 8 draw text di hdc m strtitle 1 di rc item dt singleline dt vcenter dt left select object di hdc hfont old set text color di hdc cr old set bk mode di hdc mode old set bk color di hdc cr old bk else cdc dc cdc from handle di hdc int posy di rc item top di rc item bottom di rc item top iconsize 2 int n icon pos if m mapiconpos lookup di itemid n icon pos return if di item state ods grayed 0 draw mono icon n icon pos c point di rc item left posy dc return draw the bitmap on the menu m imagelist draw dc n icon pos c point di rc item left posy ild transparent ctitlemenu drawitem mp_title croldbk setbkcolor m_clleft g_blowcolordesktop m_pfngradientfill m_clleft m_clright rcvertex rcitem fillrect rcitem rcvertex rcitem rcvertex rcitem rcvertex getrvalue m_clleft rcvertex getgvalue m_clleft rcvertex getbvalue m_clleft rcvertex rcvertex rcitem rcvertex rcitem rcvertex getrvalue m_clright rcvertex getgvalue m_clright rcvertex getbvalue m_clright rcvertex gradient_rect upperleft lowerright m_pfngradientfill rcvertex gradient_fill_rect_h exttextout eto_opaque rcitem m_bdrawedge drawedge rcitem m_uedgeflags bf_rect modeold setbkmode crold settextcolor m_cltext hfontold selectobject theapp m_fontdefaultbold rcitem getsystemmetrics sm_cxmenucheck drawtext m_strtitle rcitem dt_singleline dt_vcenter dt_left selectobject hfontold settextcolor crold setbkmode modeold setbkcolor croldbk fromhandle rcitem rcitem rcitem niconpos m_mapiconpos niconpos itemstate ods_grayed drawmonoicon niconpos cpoint rcitem m_imagelist niconpos cpoint rcitem ild_transparent bool c title menu loadapi if m binitializedapi return set menu info 0 get menu info 0 m binitializedapi true hmodule h mod user32 get module handle t user32 bool b succeeded true b succeeded b succeeded set menu info null set menu info t set menu info get proc address h mod user32 set menu info null b succeeded b succeeded get menu info null get menu info t get menu info get proc address h mod user32 get menu info null if b succeeded freeapi return false return true ctitlemenu m_binitializedapi setmenuinfo getmenuinfo m_binitializedapi hmoduser32 getmodulehandle _t bsucceeded bsucceeded bsucceeded setmenuinfo setmenuinfo tsetmenuinfo getprocaddress hmoduser32 setmenuinfo bsucceeded bsucceeded getmenuinfo getmenuinfo tgetmenuinfo getprocaddress hmoduser32 getmenuinfo bsucceeded void c title menu freeapi set menu info null get menu info null ctitlemenu setmenuinfo getmenuinfo void c title menu draw mono icon int n icon pos c point n draw pos cdc dc c windowdc windowdc 0 cdc colordc colordc create compatibledc 0 colordc set layout dc get layout c bitmap bmp color bmp color create compatible bitmap windowdc iconsize iconsize c bitmap bmp old color colordc select object bmp color colordc fill solid rect 0 0 iconsize iconsize dc get bk color cx image img bk img gray img bk create fromhbitmap hbitmap bmp color m imagelist draw colordc n icon pos c point 0 0 ild transparent img gray create fromhbitmap hbitmap bmp color if img gray is valid img bk is valid img gray gray scale img bk gray scale img gray set trans index img gray get nearest index img bk get pixel color 0 0 img gray draw hdc dc n draw pos x n draw pos y colordc select object bmp old color colordc deletedc bmp color delete object ctitlemenu drawmonoicon niconpos cpoint ndrawpos cwindowdc createcompatibledc setlayout getlayout cbitmap bmpcolor bmpcolor createcompatiblebitmap cbitmap bmpoldcolor selectobject bmpcolor fillsolidrect getbkcolor cximage imgbk imggray imgbk createfromhbitmap bmpcolor m_imagelist niconpos cpoint ild_transparent imggray createfromhbitmap bmpcolor imggray isvalid imgbk isvalid imggray grayscale imgbk grayscale imggray settransindex imggray getnearestindex imgbk getpixelcolor imggray ndrawpos ndrawpos selectobject bmpoldcolor bmpcolor deleteobject void c title menu set menu bitmap uint n flags uint ptr nid new item lpctstr lpsz new item lpctstr lpsz icon name if m biconmenu n flags mf separator 0 the prefs get windows version winver xp the prefs get windows version winver 2k if m biconmenu lpsz icon name null assert 0 return those mfc warnings which are thrown when one opens certain context menus are because of sub menu items all the i ds shown in the warnings are sub menu handles seems to be a bug in mfc look at afxfindpopupmenufromid warning unknown wm measureitem for menu item 0x530601 warning unknown wm measureitem for menu item 0x4305e7 if n flags mf popup trace t title menu adding popup menu item id x str s n nid new item lpsz new item menuiteminfoex info zero memory info sizeof info info f mask miim bitmap info hbmp item hbmmenu callback info cb size sizeof info verify set menu item info nid new item menuiteminfo info false if lpsz icon name null hicon h icon the app load icon lpsz icon name if h icon int n pos m imagelist add h icon if n pos 1 m mapiconpos set at nid new item n pos it doesn t work to use api checkmark bitmaps in an sufficient way the size of those bitmaps is limited and smaller than our menu item bitmaps if n flags mf checked hdc hdc screen getdc hwnd desktop if hdc screen cdc pdc screen cdc from handle hdc screen cdc dc mem dc mem create compatibledc pdc screen c bitmap bmp checkmark bmp checkmark create compatible bitmap pdc screen iconsize 4 iconsize 4 c bitmap p bmp old dc mem select object bmp checkmark c rect rc 0 0 iconsize 4 iconsize 4 dc mem fill solid rect rc rgb 255 255 255 m imagelist draw dc mem n pos c point 0 0 ild transparent dc mem select object p bmp old menuiteminfo mii 0 mii cb size sizeof mii mii f mask miim checkmarks mii hbmp checked hbitmap bmp checkmark detach resource leak verify set menu item info nid new item mii releasedc hwnd desktop hdc screen verify destroy icon h icon ctitlemenu setmenubitmap nflags uint_ptr nidnewitem lpsznewitem lpsziconname m_biconmenu nflags mf_separator theprefs getwindowsversion _winver_xp_ theprefs getwindowsversion _winver_2k_ m_biconmenu lpsziconname ids _afxfindpopupmenufromid wm_measureitem wm_measureitem nflags mf_popup _t titlemenu nidnewitem lpsznewitem zeromemory fmask miim_bitmap hbmpitem hbmmenu_callback cbsize setmenuiteminfo nidnewitem lpsziconname hicon theapp loadicon lpsziconname hicon npos m_imagelist hicon npos m_mapiconpos setat nidnewitem npos nflags mf_checked hdcscreen hwnd_desktop hdcscreen pdcscreen fromhandle hdcscreen dcmem dcmem createcompatibledc pdcscreen cbitmap bmpcheckmark bmpcheckmark createcompatiblebitmap pdcscreen cbitmap pbmpold dcmem selectobject bmpcheckmark crect dcmem fillsolidrect m_imagelist dcmem npos cpoint ild_transparent dcmem selectobject pbmpold cbsize fmask miim_checkmarks hbmpchecked bmpcheckmark setmenuiteminfo nidnewitem hwnd_desktop hdcscreen destroyicon hicon c resizable dialog c transfer wnd idd p parent m uwnd2 wnd2 uploading m dwshowlistidc 0 m plastmousepoint x 1 m plastmousepoint y 1 m nlastcattt 1 m btnwnd1 new c drop down button m btnwnd2 new c drop down button m tooltipcats new c tool tip ctrlx cresizabledialog ctransferwnd pparent m_uwnd2 wnd2uploading m_dwshowlistidc m_plastmousepoint m_plastmousepoint m_nlastcattt m_btnwnd1 cdropdownbutton m_btnwnd2 cdropdownbutton m_tooltipcats ctooltipctrlx c transfer wnd c transfer wnd delete m btnwnd1 delete m btnwnd2 delete m tooltipcats ctransferwnd ctransferwnd m_btnwnd1 m_btnwnd2 m_tooltipcats void c transfer wnd show queue count uint32 number tchar buffer 100 stprintf buffer t u u get res string ids banned make lower t number the app clientlist get banned count get dlg item idc queuecount set window text buffer ctransferwnd showqueuecount _stprintf _t getresstring ids_banned makelower _t theapp getbannedcount getdlgitem idc_queuecount setwindowtext void c transfer wnd update list count e wnd2 listindex int i count 1 switch m dwshowlistidc case idc downloadlist idc uploadlist if m uwnd2 listindex return c string str buffer switch m uwnd2 case wnd2 uploading uint32 item count i count 1 uploadlistctrl get item count i count uint32 active count the app uploadqueue get active uploads count if active count item count str buffer format t i item count else str buffer format t i i active count item count m btnwnd2 set window text get res string ids uploading str buffer break case wnd2 on queue str buffer format t i i count 1 queuelistctrl get item count i count m btnwnd2 set window text get res string ids onqueue str buffer break case wnd2 clients str buffer format t i i count 1 clientlistctrl get item count i count m btnwnd2 set window text get res string ids clientlist str buffer break case wnd2 downloading str buffer format t i i count 1 downloadclientsctrl get item count i count m btnwnd2 set window text get res string ids downloading str buffer break default assert 0 break case idc downloadlist break case idc uploadlist if listindex wnd2 uploading c string str buffer uint32 item count i count 1 uploadlistctrl get item count i count uint32 active count the app uploadqueue get active uploads count if active count item count str buffer format t i item count else str buffer format t i i active count item count m btnwnd1 set window text get res string ids uploading str buffer break case idc queuelist if listindex wnd2 on queue c string str buffer str buffer format t i i count 1 queuelistctrl get item count i count m btnwnd1 set window text get res string ids onqueue str buffer break case idc clientlist if listindex wnd2 clients c string str buffer str buffer format t i i count 1 clientlistctrl get item count i count m btnwnd1 set window text get res string ids clientlist str buffer break case idc downloadclients if listindex wnd2 downloading c string str buffer str buffer format t i i count 1 downloadclientsctrl get item count i count m btnwnd1 set window text get res string ids downloading str buffer break default assert 0 ctransferwnd updatelistcount ewnd2 icount m_dwshowlistidc idc_downloadlist idc_uploadlist m_uwnd2 cstring strbuffer m_uwnd2 wnd2uploading itemcount icount getitemcount icount activecount theapp getactiveuploadscount activecount itemcount strbuffer _t itemcount strbuffer _t activecount itemcount m_btnwnd2 setwindowtext getresstring ids_uploading strbuffer wnd2onqueue strbuffer _t icount getitemcount icount m_btnwnd2 setwindowtext getresstring ids_onqueue strbuffer wnd2clients strbuffer _t icount getitemcount icount m_btnwnd2 setwindowtext getresstring ids_clientlist strbuffer wnd2downloading strbuffer _t icount getitemcount icount m_btnwnd2 setwindowtext getresstring ids_downloading strbuffer idc_downloadlist idc_uploadlist wnd2uploading cstring strbuffer itemcount icount getitemcount icount activecount theapp getactiveuploadscount activecount itemcount strbuffer _t itemcount strbuffer _t activecount itemcount m_btnwnd1 setwindowtext getresstring ids_uploading strbuffer idc_queuelist wnd2onqueue cstring strbuffer strbuffer _t icount getitemcount icount m_btnwnd1 setwindowtext getresstring ids_onqueue strbuffer idc_clientlist wnd2clients cstring strbuffer strbuffer _t icount getitemcount icount m_btnwnd1 setwindowtext getresstring ids_clientlist strbuffer idc_downloadclients wnd2downloading cstring strbuffer strbuffer _t icount getitemcount icount m_btnwnd1 setwindowtext getresstring ids_downloading strbuffer void c transfer wnd update files count int i count if m dwshowlistidc idc downloadlist m dwshowlistidc idc downloadlist idc uploadlist c string str buffer str buffer format t s u get res string ids tw downloads i count m btnwnd1 set window text str buffer ctransferwnd updatefilescount icount m_dwshowlistidc idc_downloadlist m_dwshowlistidc idc_downloadlist idc_uploadlist cstring strbuffer strbuffer _t getresstring ids_tw_downloads icount m_btnwnd1 setwindowtext strbuffer void c transfer wnd localize m btnwnd1 set window text get res string ids tw downloads m btnwnd1 set btn text mp view1 split window get res string ids split window m btnwnd1 set btn text mp view1 downloads get res string ids tw downloads m btnwnd1 set btn text mp view1 uploading get res string ids uploading m btnwnd1 set btn text mp view1 downloading get res string ids downloading m btnwnd1 set btn text mp view1 onqueue get res string ids onqueue m btnwnd1 set btn text mp view1 clients get res string ids clientlist get dlg item idc queuecount label set window text get res string ids tw queue get dlg item idc queue refresh button set window text get res string ids sv update uploadlistctrl localize queuelistctrl localize downloadlistctrl localize clientlistctrl localize downloadclientsctrl localize if m dwshowlistidc idc downloadlist idc uploadlist show split window else show list m dwshowlistidc update list count m uwnd2 ctransferwnd m_btnwnd1 setwindowtext getresstring ids_tw_downloads m_btnwnd1 setbtntext mp_view1_split_window getresstring ids_split_window m_btnwnd1 setbtntext mp_view1_downloads getresstring ids_tw_downloads m_btnwnd1 setbtntext mp_view1_uploading getresstring ids_uploading m_btnwnd1 setbtntext mp_view1_downloading getresstring ids_downloading m_btnwnd1 setbtntext mp_view1_onqueue getresstring ids_onqueue m_btnwnd1 setbtntext mp_view1_clients getresstring ids_clientlist getdlgitem idc_queuecount_label setwindowtext getresstring ids_tw_queue getdlgitem idc_queue_refresh_button setwindowtext getresstring ids_sv_update m_dwshowlistidc idc_downloadlist idc_uploadlist showsplitwindow showlist m_dwshowlistidc updatelistcount m_uwnd2 void c transfer wnd update cat tab titles bool force c point pt get cursor pos pt if force get tab under mouse pt 1 avoid cat tooltip jumping return for uint8 i 0 i m dltab get item count i edit cat tab label i i 0 get cat title the prefs get category 0 filter the prefs get category i title ctransferwnd updatecattabtitles cpoint getcursorpos gettabundermouse m_dltab getitemcount editcattablabel getcattitle theprefs getcategory theprefs getcategory void c transfer wnd verify cat tab size if m dwshowlistidc idc downloadlist m dwshowlistidc idc uploadlist idc downloadlist return int size 0 for int i 0 i m dltab get item count i c rect rect m dltab get item rect i rect size rect width size 4 int right windowplacement wp downloadlistctrl get window placement wp right wp rc normal position right m dltab get window placement wp if wp rc normal position right 0 return wp rc normal position right right int left wp rc normal position right size c rect rc btn wnd1 m btnwnd1 get window rect rc btn wnd1 screen to client rc btn wnd1 if left rc btn wnd1 right 10 left rc btn wnd1 right 10 wp rc normal position left left remove anchor m dltab m dltab set window placement wp add anchor m dltab top right ctransferwnd verifycattabsize m_dwshowlistidc idc_downloadlist m_dwshowlistidc idc_uploadlist idc_downloadlist m_dltab getitemcount crect m_dltab getitemrect getwindowplacement rcnormalposition m_dltab getwindowplacement rcnormalposition rcnormalposition rcnormalposition crect rcbtnwnd1 m_btnwnd1 getwindowrect rcbtnwnd1 screentoclient rcbtnwnd1 rcbtnwnd1 rcbtnwnd1 rcnormalposition removeanchor m_dltab m_dltab setwindowplacement addanchor m_dltab top_right int c transfer wnd add category c string newtitle c string newincoming c string newcomment c string newautocat bool add tab category struct newcat new category struct stprintf newcat title newtitle newcat prio pr normal stprintf newcat incomingpath newincoming stprintf newcat comment newcomment newcat regexp empty newcat ac regexpeval false newcat autocat newautocat newcat download in alphabetical order false newcat filter 0 newcat filter neg false newcat care4all false int index the prefs add cat newcat if add tab m dltab insert item index newtitle verify cat tab size return index ctransferwnd addcategory cstring cstring cstring cstring addtab category_struct category_struct _stprintf pr_normal _stprintf _stprintf ac_regexpeval downloadinalphabeticalorder filterneg theprefs addcat addtab m_dltab insertitem verifycattabsize void c transfer wnd switch upload list if m uwnd2 wnd2 uploading set wnd2 wnd2 on queue if the prefs is queue list disabled switch upload list return uploadlistctrl hide clientlistctrl hide downloadclientsctrl hide get dlg item idc queue refresh button show window sw show queuelistctrl visable m btnwnd2 set window text get res string ids onqueue else if m uwnd2 wnd2 on queue set wnd2 wnd2 clients if the prefs is known client list disabled switch upload list return uploadlistctrl hide queuelistctrl hide downloadclientsctrl hide clientlistctrl visable get dlg item idc queue refresh button show window sw hide m btnwnd2 set window text get res string ids clientlist else if m uwnd2 wnd2 clients set wnd2 wnd2 downloading queuelistctrl hide clientlistctrl hide uploadlistctrl hide downloadclientsctrl show get dlg item idc queue refresh button show window sw hide m btnwnd2 set window text get res string ids downloading else queuelistctrl hide clientlistctrl hide downloadclientsctrl hide uploadlistctrl visable get dlg item idc queue refresh button show window sw hide set wnd2 wnd2 uploading m btnwnd2 set window text get res string ids uploading update list count m uwnd2 set wnd2 icon ctransferwnd switchuploadlist m_uwnd2 wnd2uploading setwnd2 wnd2onqueue theprefs isqueuelistdisabled switchuploadlist getdlgitem idc_queue_refresh_button showwindow sw_show m_btnwnd2 setwindowtext getresstring ids_onqueue m_uwnd2 wnd2onqueue setwnd2 wnd2clients theprefs isknownclientlistdisabled switchuploadlist getdlgitem idc_queue_refresh_button showwindow sw_hide m_btnwnd2 setwindowtext getresstring ids_clientlist m_uwnd2 wnd2clients setwnd2 wnd2downloading getdlgitem idc_queue_refresh_button showwindow sw_hide m_btnwnd2 setwindowtext getresstring ids_downloading getdlgitem idc_queue_refresh_button showwindow sw_hide setwnd2 wnd2uploading m_btnwnd2 setwindowtext getresstring ids_uploading updatelistcount m_uwnd2 setwnd2icon void c transfer wnd reset trans toolbar bool b show toolbar bool b reset lists if m btnwnd1 m hwnd remove anchor m btnwnd1 c rect rc rc top 5 rc left wnd1 button xoff rc right rc left wnd1 button width b show toolbar num wina buttons dflt toolbar btn width 0 rc bottom rc top wnd1 button height m btnwnd1 init b show toolbar m btnwnd1 move window rc set wnd1 icons if b show toolbar m btnwnd1 modify style 0 tbstyle tooltips m btnwnd1 set extended style m btnwnd1 get extended style tbstyle ex mixedbuttons tbbutton atb 1 num wina buttons 0 atb 0 i bitmap w1i download files atb 0 id command idc download ico atb 0 fs state tbstate enabled atb 0 fs style btns button btns showtext atb 0 i string 1 atb 1 i bitmap w1i split window atb 1 id command mp view1 split window atb 1 fs state tbstate enabled atb 1 fs style btns button btns checkgroup btns autosize atb 1 i string 1 atb 2 i bitmap w1i download files atb 2 id command mp view1 downloads atb 2 fs state tbstate enabled atb 2 fs style btns button btns checkgroup btns autosize atb 2 i string 1 atb 3 i bitmap w1i uploading atb 3 id command mp view1 uploading atb 3 fs state tbstate enabled atb 3 fs style btns button btns checkgroup btns autosize atb 3 i string 1 atb 4 i bitmap w1i downloading atb 4 id command mp view1 downloading atb 4 fs state tbstate enabled atb 4 fs style btns button btns checkgroup btns autosize atb 4 i string 1 atb 5 i bitmap w1i on queue atb 5 id command mp view1 onqueue atb 5 fs state the prefs is queue list disabled 0 tbstate enabled atb 5 fs style btns button btns checkgroup btns autosize atb 5 i string 1 atb 6 i bitmap w1i clients known atb 6 id command mp view1 clients atb 6 fs state the prefs is known client list disabled 0 tbstate enabled atb 6 fs style btns button btns checkgroup btns autosize atb 6 i string 1 m btnwnd1 add buttons arrsize atb atb tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif size tbif byindex tbbi cx wnd1 button width m btnwnd1 set button info 0 tbbi c size size m btnwnd1 get max size size m btnwnd1 get window rect rc screen to client rc m btnwnd1 move window rc left rc top size cx rc height else m btnwnd1 modify style tbstyle tooltips 0 m btnwnd1 set extended style m btnwnd1 get extended style tbstyle ex mixedbuttons m btnwnd1 recalc layout true add anchor m btnwnd1 top left if b reset lists show split window true verify cat tab size ctransferwnd resettranstoolbar bshowtoolbar bresetlists m_btnwnd1 m_hwnd removeanchor m_btnwnd1 crect wnd1_button_xoff wnd1_button_width bshowtoolbar num_wina_buttons dflt_toolbar_btn_width wnd1_button_height m_btnwnd1 bshowtoolbar m_btnwnd1 movewindow setwnd1icons bshowtoolbar m_btnwnd1 modifystyle tbstyle_tooltips m_btnwnd1 setextendedstyle m_btnwnd1 getextendedstyle tbstyle_ex_mixedbuttons num_wina_buttons ibitmap w1idownloadfiles idcommand idc_download_ico fsstate tbstate_enabled fsstyle btns_button btns_showtext istring ibitmap w1isplitwindow idcommand mp_view1_split_window fsstate tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring ibitmap w1idownloadfiles idcommand mp_view1_downloads fsstate tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring ibitmap w1iuploading idcommand mp_view1_uploading fsstate tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring ibitmap w1idownloading idcommand mp_view1_downloading fsstate tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring ibitmap w1ionqueue idcommand mp_view1_onqueue fsstate theprefs isqueuelistdisabled tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring ibitmap w1iclientsknown idcommand mp_view1_clients fsstate theprefs isknownclientlistdisabled tbstate_enabled fsstyle btns_button btns_checkgroup btns_autosize istring m_btnwnd1 addbuttons cbsize dwmask tbif_size tbif_byindex wnd1_button_width m_btnwnd1 setbuttoninfo csize m_btnwnd1 getmaxsize m_btnwnd1 getwindowrect screentoclient m_btnwnd1 movewindow m_btnwnd1 modifystyle tbstyle_tooltips m_btnwnd1 setextendedstyle m_btnwnd1 getextendedstyle tbstyle_ex_mixedbuttons m_btnwnd1 recalclayout addanchor m_btnwnd1 top_left bresetlists showsplitwindow verifycattabsize void c transfer wnd set tool tips delay dword dw delay m tooltipcats set delay time ttdt initial dw delay c tool tip ctrl tooltip downloadlistctrl get tool tips if tooltip tooltip set delay time ttdt initial dw delay tooltip uploadlistctrl get tool tips if tooltip tooltip set delay time ttdt initial dw delay ctransferwnd settooltipsdelay dwdelay m_tooltipcats setdelaytime ttdt_initial dwdelay ctooltipctrl gettooltips setdelaytime ttdt_initial dwdelay gettooltips setdelaytime ttdt_initial dwdelay void c transfer wnd show wnd2 e wnd2 u wnd2 if u wnd2 wnd2 on queue the prefs is queue list disabled uploadlistctrl hide clientlistctrl hide downloadclientsctrl hide queuelistctrl visable get dlg item idc queue refresh button show window sw show m btnwnd2 set window text get res string ids onqueue set wnd2 u wnd2 else if u wnd2 wnd2 clients the prefs is known client list disabled uploadlistctrl hide queuelistctrl hide downloadclientsctrl hide clientlistctrl visable get dlg item idc queue refresh button show window sw hide m btnwnd2 set window text get res string ids clientlist set wnd2 u wnd2 else if u wnd2 wnd2 downloading uploadlistctrl hide queuelistctrl hide clientlistctrl hide downloadclientsctrl show get dlg item idc queue refresh button show window sw hide m btnwnd2 set window text get res string ids downloading set wnd2 u wnd2 else queuelistctrl hide clientlistctrl hide downloadclientsctrl hide uploadlistctrl visable get dlg item idc queue refresh button show window sw hide m btnwnd2 set window text get res string ids uploading set wnd2 wnd2 uploading update list count m uwnd2 set wnd2 icon ctransferwnd showwnd2 ewnd2 uwnd2 uwnd2 wnd2onqueue theprefs isqueuelistdisabled getdlgitem idc_queue_refresh_button showwindow sw_show m_btnwnd2 setwindowtext getresstring ids_onqueue setwnd2 uwnd2 uwnd2 wnd2clients theprefs isknownclientlistdisabled getdlgitem idc_queue_refresh_button showwindow sw_hide m_btnwnd2 setwindowtext getresstring ids_clientlist setwnd2 uwnd2 uwnd2 wnd2downloading getdlgitem idc_queue_refresh_button showwindow sw_hide m_btnwnd2 setwindowtext getresstring ids_downloading setwnd2 uwnd2 getdlgitem idc_queue_refresh_button showwindow sw_hide m_btnwnd2 setwindowtext getresstring ids_uploading setwnd2 wnd2uploading updatelistcount m_uwnd2 setwnd2icon void c transfer wnd set wnd2 e wnd2 u wnd2 m uwnd2 u wnd2 the prefs set transfer wnd2 m uwnd2 ctransferwnd setwnd2 ewnd2 uwnd2 m_uwnd2 uwnd2 theprefs settransferwnd2 m_uwnd2 void c transfer wnd do resize int delta c splitter control change height downloadlistctrl delta c splitter control change height uploadlistctrl delta cw bottomalign c splitter control change height queuelistctrl delta cw bottomalign c splitter control change height clientlistctrl delta cw bottomalign c splitter control change height downloadclientsctrl delta cw bottomalign update splitter range if m dwshowlistidc idc downloadlist idc uploadlist downloadlistctrl invalidate downloadlistctrl update window switch m uwnd2 case wnd2 uploading uploadlistctrl invalidate uploadlistctrl update window break case wnd2 on queue queuelistctrl invalidate queuelistctrl update window break case wnd2 clients clientlistctrl invalidate clientlistctrl update window break case wnd2 downloading downloadclientsctrl invalidate downloadclientsctrl update window break default assert 0 ctransferwnd doresize csplittercontrol changeheight csplittercontrol changeheight cw_bottomalign csplittercontrol changeheight cw_bottomalign csplittercontrol changeheight cw_bottomalign csplittercontrol changeheight cw_bottomalign updatesplitterrange m_dwshowlistidc idc_downloadlist idc_uploadlist updatewindow m_uwnd2 wnd2uploading updatewindow wnd2onqueue updatewindow wnd2clients updatewindow wnd2downloading updatewindow void c transfer wnd update splitter range c rect rc wnd get window rect rc wnd c rect rc down downloadlistctrl get window rect rc down screen to client rc down c rect rc up downloadclientsctrl get window rect rc up screen to client rc up the prefs set splitterbar position rc down bottom 100 rc wnd height remove anchor idc downloadlist remove anchor idc uploadlist remove anchor idc queuelist remove anchor idc clientlist remove anchor idc downloadclients add anchor idc downloadlist top left c size 100 the prefs get splitterbar position add anchor idc uploadlist c size 0 the prefs get splitterbar position bottom right add anchor idc queuelist c size 0 the prefs get splitterbar position bottom right add anchor idc clientlist c size 0 the prefs get splitterbar position bottom right add anchor idc downloadclients c size 0 the prefs get splitterbar position bottom right m wndsplitter set range rc down top 50 rc up bottom 40 ctransferwnd updatesplitterrange crect rcwnd getwindowrect rcwnd crect rcdown getwindowrect rcdown screentoclient rcdown crect rcup getwindowrect rcup screentoclient rcup theprefs setsplitterbarposition rcdown rcwnd removeanchor idc_downloadlist removeanchor idc_uploadlist removeanchor idc_queuelist removeanchor idc_clientlist removeanchor idc_downloadclients addanchor idc_downloadlist top_left csize theprefs getsplitterbarposition addanchor idc_uploadlist csize theprefs getsplitterbarposition bottom_right addanchor idc_queuelist csize theprefs getsplitterbarposition bottom_right addanchor idc_clientlist csize theprefs getsplitterbarposition bottom_right addanchor idc_downloadclients csize theprefs getsplitterbarposition bottom_right m_wndsplitter setrange rcdown rcup void c transfer wnd set all icons set wnd1 icons set wnd2 icon ctransferwnd setallicons setwnd1icons setwnd2icon void c transfer wnd set wnd1 icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 1 1 iml add c temp icon loader t split window iml add c temp icon loader t download files iml add c temp icon loader t upload iml add c temp icon loader t download iml add c temp icon loader t clients on queue iml add c temp icon loader t clients known c image list p iml old m btnwnd1 set image list iml iml detach if p iml old p iml old delete image list ctransferwnd setwnd1icons cimagelist theapp m_idfltimagelistcolorflags ilc_mask ctempiconloader _t splitwindow ctempiconloader _t downloadfiles ctempiconloader _t ctempiconloader _t ctempiconloader _t clientsonqueue ctempiconloader _t clientsknown cimagelist pimlold m_btnwnd1 setimagelist pimlold pimlold deleteimagelist void c transfer wnd set wnd2 icon if m uwnd2 wnd2 on queue m btnwnd2 set icon t clients on queue else if m uwnd2 wnd2 uploading m btnwnd2 set icon t upload else if m uwnd2 wnd2 clients m btnwnd2 set icon t clients known else if m uwnd2 wnd2 downloading m btnwnd2 set icon t download else assert 0 ctransferwnd setwnd2icon m_uwnd2 wnd2onqueue m_btnwnd2 seticon _t clientsonqueue m_uwnd2 wnd2uploading m_btnwnd2 seticon _t m_uwnd2 wnd2clients m_btnwnd2 seticon _t clientsknown m_uwnd2 wnd2downloading m_btnwnd2 seticon _t void c transfer wnd update tab tool tips int tab if tab 1 for int i 0 i m tooltipcats get tool count i m tooltipcats del tool m dltab i 1 for int i 0 i m dltab get item count i c rect r m dltab get item rect i r verify m tooltipcats add tool m dltab get tab statistic i r i 1 else c rect r m dltab get item rect tab r m tooltipcats del tool m dltab tab 1 verify m tooltipcats add tool m dltab get tab statistic tab r tab 1 ctransferwnd updatetabtooltips m_tooltipcats gettoolcount m_tooltipcats deltool m_dltab m_dltab getitemcount crect m_dltab getitemrect m_tooltipcats addtool m_dltab gettabstatistic crect m_dltab getitemrect m_tooltipcats deltool m_dltab m_tooltipcats addtool m_dltab gettabstatistic c string c transfer wnd get tab statistic int tab uint16 count dwl err paus count dwl err paus 0 float speed 0 uint64 size 0 uint64 trsize 0 uint64 disksize 0 for int i 0 i the app downloadqueue get file count i const c part file cur file the app downloadqueue get file by index i if cur file 0 continue if cur file check show item in given cat tab count if cur file get transferring src count 0 dwl speed cur file get datarate 1024 0f size uint64 cur file get file size trsize uint64 cur file get completed size if cur file is allocating disksize uint64 cur file get real file size if cur file get status ps error err if cur file get status ps paused paus int total int compl the app emuledlg transferwnd downloadlistctrl get complete downloads tab total c string prio switch the prefs get category tab prio case pr low prio get res string ids priolow break case pr high prio get res string ids priohigh break default prio get res string ids prionormal break c string title title format t s i n n s i n s i n s i n s i n n s s n n s 1f s n s s s n s s get res string ids files count compl get res string ids downloading dwl get res string ids paused paus get res string ids errorlike err get res string ids dl transfcompl compl get res string ids priority prio get res string ids dl speed speed get res string ids kbytespersec get res string ids dl size cast itox bytes trsize false false cast itox bytes size false false get res string ids ondisk cast itox bytes disksize false false return title cstring ctransferwnd gettabstatistic theapp getfilecount cpartfile cur_file theapp getfilebyindex cur_file cur_file checkshowitemingivencat cur_file gettransferringsrccount cur_file getdatarate cur_file getfilesize cur_file getcompletedsize cur_file isallocating cur_file getrealfilesize cur_file getstatus ps_error cur_file getstatus ps_paused theapp getcompletedownloads cstring theprefs getcategory pr_low getresstring ids_priolow pr_high getresstring ids_priohigh getresstring ids_prionormal cstring _t getresstring ids_files getresstring ids_downloading getresstring ids_paused getresstring ids_errorlike getresstring ids_dl_transfcompl getresstring ids_priority getresstring ids_dl_speed getresstring ids_kbytespersec getresstring ids_dl_size castitoxbytes castitoxbytes getresstring ids_ondisk castitoxbytes int c transfer wnd get tab under mouse c point point tchittestinfo hitinfo c rect rect m dltab get window rect rect point offset 0 rect left 0 rect top hitinfo pt point if m dltab get item rect 0 rect if hitinfo pt y rect top 30 hitinfo pt y rect top 30 hitinfo pt y rect top find the destination tab unsigned int n tab m dltab hit test hitinfo if hitinfo flags tcht nowhere return n tab else return 1 ctransferwnd gettabundermouse cpoint crect m_dltab getwindowrect m_dltab getitemrect ntab m_dltab hittest tcht_nowhere ntab int c transfer wnd get item under mouse c list ctrl ctrl c point pt get cursor pos pt ctrl screen to client pt lvhittestinfo hit subhit hit pt pt subhit pt pt ctrl sub item hit test subhit int sel ctrl hit test hit if sel lb err hit flags lvht onitem if subhit i sub item 0 return sel return lb err ctransferwnd getitemundermouse clistctrl cpoint getcursorpos screentoclient subitemhittest hittest lb_err lvht_onitem isubitem lb_err c string c transfer wnd get cat title int catid switch catid case 0 return get res string ids all case 1 return get res string ids allothers case 2 return get res string ids status notcompleted case 3 return get res string ids dl transfcompl case 4 return get res string ids waiting case 5 return get res string ids downloading case 6 return get res string ids errorlike case 7 return get res string ids paused case 8 return get res string ids seencompl case 10 return get res string ids video case 11 return get res string ids audio case 12 return get res string ids search arc case 13 return get res string ids search cdimg case 14 return get res string ids search doc case 15 return get res string ids search pics case 16 return get res string ids search prg case 18 return get res string ids regexpression return t cstring ctransferwnd getcattitle getresstring ids_all getresstring ids_allothers getresstring ids_status_notcompleted getresstring ids_dl_transfcompl getresstring ids_waiting getresstring ids_downloading getresstring ids_errorlike getresstring ids_paused getresstring ids_seencompl getresstring ids_video getresstring ids_audio getresstring ids_search_arc getresstring ids_search_cdimg getresstring ids_search_doc getresstring ids_search_pics getresstring ids_search_prg getresstring ids_regexpression _t void c transfer wnd edit cat tab label int index c string newlabel tcitem tabitem tabitem mask tcif param m dltab get item index tabitem tabitem mask tcif text newlabel replace t t if index newlabel empty if index index the prefs get cat filter index 0 if index newlabel append t if the prefs get cat filter neg index newlabel append t if the prefs get cat filter index 18 newlabel append t the prefs get category index regexp t else newlabel append get cat title the prefs get cat filter index if index newlabel append t int count dwl if the prefs show cat tab infos c part file cur file count dwl 0 for int i 0 i the app downloadqueue get file count i cur file the app downloadqueue get file by index i if cur file 0 continue if cur file check show item in given cat index if cur file get transferring src count 0 dwl c string title newlabel the app emuledlg transferwnd downloadlistctrl get complete downloads index count newlabel format t s i i title dwl count tabitem psz text newlabel lock buffer m dltab set item index tabitem newlabel unlock buffer verify cat tab size ctransferwnd editcattablabel cstring tcif_param m_dltab getitem tcif_text _t _t theprefs getcatfilter _t theprefs getcatfilterneg _t theprefs getcatfilter _t theprefs getcategory _t getcattitle theprefs getcatfilter _t theprefs showcattabinfos cpartfile cur_file theapp getfilecount cur_file theapp getfilebyindex cur_file cur_file checkshowitemingivencat cur_file gettransferringsrccount cstring theapp getcompletedownloads _t psztext lockbuffer m_dltab setitem unlockbuffer verifycattabsize void c transfer wnd edit cat tab label int i edit cat tab label i i 0 get cat title the prefs get allcat type the prefs get category i title ctransferwnd editcattablabel editcattablabel getcattitle theprefs getallcattype theprefs getcategory void c transfer wnd show list uint32 dw listidc c rect rc wnd get window rect rc wnd screen to client rc wnd c rect rc down get dlg item dw listidc get window rect rc down screen to client rc down rc down bottom rc wnd bottom 20 rc down top 28 m wndsplitter destroy window remove anchor dw listidc m btnwnd2 show window sw hide m dwshowlistidc dw listidc uploadlistctrl show window m dwshowlistidc idc uploadlist sw show sw hide queuelistctrl show window m dwshowlistidc idc queuelist sw show sw hide downloadclientsctrl show window m dwshowlistidc idc downloadclients sw show sw hide clientlistctrl show window m dwshowlistidc idc clientlist sw show sw hide downloadlistctrl show window m dwshowlistidc idc downloadlist sw show sw hide m dltab show window m dwshowlistidc idc downloadlist sw show sw hide get dlg item idc queue refresh button show window m dwshowlistidc idc queuelist sw show sw hide switch dw listidc case idc downloadlist downloadlistctrl move window rc down downloadlistctrl show files count m btnwnd1 check button mp view1 downloads change dl icon w1i download files the prefs set transfer wnd1 1 break case idc uploadlist uploadlistctrl move window rc down update list count wnd2 uploading m btnwnd1 check button mp view1 uploading change dl icon w1i uploading the prefs set transfer wnd1 2 break case idc queuelist queuelistctrl move window rc down update list count wnd2 on queue m btnwnd1 check button mp view1 onqueue change dl icon w1i on queue the prefs set transfer wnd1 3 break case idc downloadclients downloadclientsctrl move window rc down update list count wnd2 downloading m btnwnd1 check button mp view1 downloading change dl icon w1i downloading the prefs set transfer wnd1 4 break case idc clientlist clientlistctrl move window rc down update list count wnd2 clients m btnwnd1 check button mp view1 clients change dl icon w1i clients known the prefs set transfer wnd1 5 break default assert 0 add anchor dw listidc top left bottom right ctransferwnd showlist dwlistidc crect rcwnd getwindowrect rcwnd screentoclient rcwnd crect rcdown getdlgitem dwlistidc getwindowrect rcdown screentoclient rcdown rcdown rcwnd rcdown m_wndsplitter destroywindow removeanchor dwlistidc m_btnwnd2 showwindow sw_hide m_dwshowlistidc dwlistidc showwindow m_dwshowlistidc idc_uploadlist sw_show sw_hide showwindow m_dwshowlistidc idc_queuelist sw_show sw_hide showwindow m_dwshowlistidc idc_downloadclients sw_show sw_hide showwindow m_dwshowlistidc idc_clientlist sw_show sw_hide showwindow m_dwshowlistidc idc_downloadlist sw_show sw_hide m_dltab showwindow m_dwshowlistidc idc_downloadlist sw_show sw_hide getdlgitem idc_queue_refresh_button showwindow m_dwshowlistidc idc_queuelist sw_show sw_hide dwlistidc idc_downloadlist movewindow rcdown showfilescount m_btnwnd1 checkbutton mp_view1_downloads changedlicon w1idownloadfiles theprefs settransferwnd1 idc_uploadlist movewindow rcdown updatelistcount wnd2uploading m_btnwnd1 checkbutton mp_view1_uploading changedlicon w1iuploading theprefs settransferwnd1 idc_queuelist movewindow rcdown updatelistcount wnd2onqueue m_btnwnd1 checkbutton mp_view1_onqueue changedlicon w1ionqueue theprefs settransferwnd1 idc_downloadclients movewindow rcdown updatelistcount wnd2downloading m_btnwnd1 checkbutton mp_view1_downloading changedlicon w1idownloading theprefs settransferwnd1 idc_clientlist movewindow rcdown updatelistcount wnd2clients m_btnwnd1 checkbutton mp_view1_clients changedlicon w1iclientsknown theprefs settransferwnd1 addanchor dwlistidc top_left bottom_right void c transfer wnd change dl icon e wnd1 icon i icon tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif image tbbi i image i icon m btnwnd1 set button info get window long m btnwnd1 gwl id tbbi ctransferwnd changedlicon ewnd1icon iicon cbsize dwmask tbif_image iimage iicon m_btnwnd1 setbuttoninfo getwindowlong m_btnwnd1 gwl_id void c transfer wnd show split window bool b re draw the prefs set transfer wnd1 0 m dltab show window sw show if b re draw m dwshowlistidc idc downloadlist idc uploadlist return m btnwnd1 check button mp view1 split window change dl icon w1i download files c rect rc wnd get window rect rc wnd screen to client rc wnd long splitpos the prefs get splitterbar position rc wnd height 100 do some more magic don t ask just fix it if b re draw m dwshowlistidc 0 m dwshowlistidc idc downloadlist idc uploadlist splitpos 10 c rect rc down downloadlistctrl get window rect rc down screen to client rc down rc down bottom splitpos 5 magic constant 5 downloadlistctrl move window rc down uploadlistctrl get window rect rc down screen to client rc down rc down right rc wnd right 7 rc down bottom rc wnd bottom 20 rc down top splitpos 20 uploadlistctrl move window rc down queuelistctrl get window rect rc down screen to client rc down rc down right rc wnd right 7 rc down bottom rc wnd bottom 20 rc down top splitpos 20 queuelistctrl move window rc down clientlistctrl get window rect rc down screen to client rc down rc down right rc wnd right 7 rc down bottom rc wnd bottom 20 rc down top splitpos 20 clientlistctrl move window rc down downloadclientsctrl get window rect rc down screen to client rc down rc down right rc wnd right 7 rc down bottom rc wnd bottom 20 rc down top splitpos 20 downloadclientsctrl move window rc down c rect rc spl rc spl left wnd2 button xoff wnd2 button width 8 rc spl right rc down right rc spl top splitpos wnd splitter yoff rc spl bottom rc spl top wnd splitter height if m wndsplitter m wndsplitter create ws child ws visible rc spl this idc splitter else m wndsplitter move window rc spl true do resize 0 m dwshowlistidc idc downloadlist idc uploadlist downloadlistctrl show files count m btnwnd2 show window sw show remove anchor idc downloadlist remove anchor idc uploadlist remove anchor idc queuelist remove anchor idc downloadclients remove anchor idc clientlist remove anchor idc upload ico add anchor idc downloadlist top left c size 100 the prefs get splitterbar position add anchor idc uploadlist c size 0 the prefs get splitterbar position bottom right add anchor idc queuelist c size 0 the prefs get splitterbar position bottom right add anchor idc clientlist c size 0 the prefs get splitterbar position bottom right add anchor idc downloadclients c size 0 the prefs get splitterbar position bottom right add anchor idc upload ico c size 0 the prefs get splitterbar position bottom right downloadlistctrl show window sw show uploadlistctrl show window m uwnd2 wnd2 uploading sw show sw hide queuelistctrl show window m uwnd2 wnd2 on queue sw show sw hide downloadclientsctrl show window m uwnd2 wnd2 downloading sw show sw hide clientlistctrl show window m uwnd2 wnd2 clients sw show sw hide get dlg item idc queue refresh button show window m uwnd2 wnd2 on queue sw show sw hide update list count m uwnd2 ctransferwnd showsplitwindow bredraw theprefs settransferwnd1 m_dltab showwindow sw_show bredraw m_dwshowlistidc idc_downloadlist idc_uploadlist m_btnwnd1 checkbutton mp_view1_split_window changedlicon w1idownloadfiles crect rcwnd getwindowrect rcwnd screentoclient rcwnd theprefs getsplitterbarposition rcwnd bredraw m_dwshowlistidc m_dwshowlistidc idc_downloadlist idc_uploadlist crect rcdown getwindowrect rcdown screentoclient rcdown rcdown movewindow rcdown getwindowrect rcdown screentoclient rcdown rcdown rcwnd rcdown rcwnd rcdown movewindow rcdown getwindowrect rcdown screentoclient rcdown rcdown rcwnd rcdown rcwnd rcdown movewindow rcdown getwindowrect rcdown screentoclient rcdown rcdown rcwnd rcdown rcwnd rcdown movewindow rcdown getwindowrect rcdown screentoclient rcdown rcdown rcwnd rcdown rcwnd rcdown movewindow rcdown crect rcspl rcspl wnd2_button_xoff wnd2_button_width rcspl rcdown rcspl wnd_splitter_yoff rcspl rcspl wnd_splitter_height m_wndsplitter m_wndsplitter ws_child ws_visible rcspl idc_splitter m_wndsplitter movewindow rcspl doresize m_dwshowlistidc idc_downloadlist idc_uploadlist showfilescount m_btnwnd2 showwindow sw_show removeanchor idc_downloadlist removeanchor idc_uploadlist removeanchor idc_queuelist removeanchor idc_downloadclients removeanchor idc_clientlist removeanchor idc_upload_ico addanchor idc_downloadlist top_left csize theprefs getsplitterbarposition addanchor idc_uploadlist csize theprefs getsplitterbarposition bottom_right addanchor idc_queuelist csize theprefs getsplitterbarposition bottom_right addanchor idc_clientlist csize theprefs getsplitterbarposition bottom_right addanchor idc_downloadclients csize theprefs getsplitterbarposition bottom_right addanchor idc_upload_ico csize theprefs getsplitterbarposition bottom_right showwindow sw_show showwindow m_uwnd2 wnd2uploading sw_show sw_hide showwindow m_uwnd2 wnd2onqueue sw_show sw_hide showwindow m_uwnd2 wnd2downloading sw_show sw_hide showwindow m_uwnd2 wnd2clients sw_show sw_hide getdlgitem idc_queue_refresh_button showwindow m_uwnd2 wnd2onqueue sw_show sw_hide updatelistcount m_uwnd2 bool c transfer wnd pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 return false else if p msg message wm lbuttondblclk if p msg hwnd m dltab m hwnd on dblclick dltab return true else if p msg message wm mousemove point point get cursor pos point if point x m plastmousepoint x point y m plastmousepoint y m plastmousepoint point handle tooltip updating when mouse is moved from one item to another c point pt point m ndropindex get tab under mouse pt if m ndropindex m nlastcattt m nlastcattt m ndropindex if m ndropindex 1 update tab tool tips m ndropindex else if p msg message wm mbuttonup if downloadlistactive downloadlistctrl show selected file details else if m dwshowlistidc idc downloadlist idc uploadlist switch m dwshowlistidc case idc uploadlist uploadlistctrl show selected user details break case idc queuelist queuelistctrl show selected user details break case idc clientlist clientlistctrl show selected user details break case idc downloadclients downloadclientsctrl show selected user details break default assert 0 else switch m uwnd2 case wnd2 on queue queuelistctrl show selected user details break case wnd2 uploading uploadlistctrl show selected user details break case wnd2 clients clientlistctrl show selected user details break case wnd2 downloading downloadclientsctrl show selected user details break default assert 0 return true return c resizable dialog pre translate message p msg ctransferwnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control pmsg wm_lbuttondblclk pmsg m_dltab m_hwnd ondblclickdltab pmsg wm_mousemove getcursorpos m_plastmousepoint m_plastmousepoint m_plastmousepoint cpoint m_ndropindex gettabundermouse m_ndropindex m_nlastcattt m_nlastcattt m_ndropindex m_ndropindex updatetabtooltips m_ndropindex pmsg wm_mbuttonup showselectedfiledetails m_dwshowlistidc idc_downloadlist idc_uploadlist m_dwshowlistidc idc_uploadlist showselecteduserdetails idc_queuelist showselecteduserdetails idc_clientlist showselecteduserdetails idc_downloadclients showselecteduserdetails m_uwnd2 wnd2onqueue showselecteduserdetails wnd2uploading showselecteduserdetails wnd2clients showselecteduserdetails wnd2downloading showselecteduserdetails cresizabledialog pretranslatemessage pmsg void c transfer wnd do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc download ico m btnwnd1 ddx control pdx idc upload ico m btnwnd2 ddx control pdx idc dltab m dltab ddx control pdx idc uploadlist uploadlistctrl ddx control pdx idc downloadlist downloadlistctrl ddx control pdx idc queuelist queuelistctrl ddx control pdx idc clientlist clientlistctrl ddx control pdx idc downloadclients downloadclientsctrl ctransferwnd dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_download_ico m_btnwnd1 ddx_control idc_upload_ico m_btnwnd2 ddx_control idc_dltab m_dltab ddx_control idc_uploadlist ddx_control idc_downloadlist ddx_control idc_queuelist ddx_control idc_clientlist ddx_control idc_downloadclients bool c transfer wnd on init dialog c resizable dialog on init dialog init window styles this reset trans toolbar the prefs is trans toolbar enabled false m btnwnd2 init true uploadlistctrl init downloadlistctrl init queuelistctrl init clientlistctrl init downloadclientsctrl init m uwnd2 e wnd2 the prefs get transfer wnd2 show wnd2 m uwnd2 add anchor idc downloadlist top left c size 100 the prefs get splitterbar position add anchor idc uploadlist c size 0 the prefs get splitterbar position bottom right add anchor idc queuelist c size 0 the prefs get splitterbar position bottom right add anchor idc clientlist c size 0 the prefs get splitterbar position bottom right add anchor m btnwnd2 c size 0 the prefs get splitterbar position bottom right add anchor idc downloadclients c size 0 the prefs get splitterbar position bottom right add anchor idc queuecount bottom left add anchor idc queuecount label bottom left add anchor idc queue refresh button bottom right add anchor idc dltab c size 50 0 top right switch the prefs get transfer wnd1 default case 0 splitting functionality c rect rc get window rect rc screen to client rc c rect rc spl rc spl left 55 rc spl right rc right rc spl top rc bottom 100 rc spl bottom rc spl top wnd splitter height m wndsplitter create ws child ws visible rc spl this idc splitter show split window break case 1 show list idc downloadlist break case 2 show list idc uploadlist break case 3 show list idc queuelist break case 4 show list idc downloadclients break case 5 show list idc clientlist break cats rightclickindex 1 downloadlistactive true m bisdragging false show cat tabs stprintf the prefs get category 0 title t s get cat title the prefs get category 0 filter stprintf the prefs get category 0 incomingpath t s the prefs get incoming dir the prefs get category 0 care4all true for int ix 0 ix the prefs get cat count ix m dltab insert item ix the prefs get category ix title create tooltip control for download categories m tooltipcats create this tts noprefix m dltab set tool tips m tooltipcats update cat tab titles update tab tool tips m tooltipcats set margin c rect 4 4 4 4 m tooltipcats send message ttm setmaxtipwidth 0 shrt max recognize n chars m tooltipcats set delay time ttdt autopop 20000 m tooltipcats set delay time ttdt initial the prefs get tool tip delay 1000 m tooltipcats activate true verify cat tab size localize return true ctransferwnd oninitdialog cresizabledialog oninitdialog initwindowstyles resettranstoolbar theprefs istranstoolbarenabled m_btnwnd2 m_uwnd2 ewnd2 theprefs gettransferwnd2 showwnd2 m_uwnd2 addanchor idc_downloadlist top_left csize theprefs getsplitterbarposition addanchor idc_uploadlist csize theprefs getsplitterbarposition bottom_right addanchor idc_queuelist csize theprefs getsplitterbarposition bottom_right addanchor idc_clientlist csize theprefs getsplitterbarposition bottom_right addanchor m_btnwnd2 csize theprefs getsplitterbarposition bottom_right addanchor idc_downloadclients csize theprefs getsplitterbarposition bottom_right addanchor idc_queuecount bottom_left addanchor idc_queuecount_label bottom_left addanchor idc_queue_refresh_button bottom_right addanchor idc_dltab csize top_right theprefs gettransferwnd1 crect getwindowrect screentoclient crect rcspl rcspl rcspl rcspl rcspl rcspl wnd_splitter_height m_wndsplitter ws_child ws_visible rcspl idc_splitter showsplitwindow showlist idc_downloadlist showlist idc_uploadlist showlist idc_queuelist showlist idc_downloadclients showlist idc_clientlist m_bisdragging _stprintf theprefs getcategory _t getcattitle theprefs getcategory _stprintf theprefs getcategory _t theprefs getincomingdir theprefs getcategory theprefs getcatcount m_dltab insertitem theprefs getcategory m_tooltipcats tts_noprefix m_dltab settooltips m_tooltipcats updatecattabtitles updatetabtooltips m_tooltipcats setmargin crect m_tooltipcats sendmessage ttm_setmaxtipwidth shrt_max m_tooltipcats setdelaytime ttdt_autopop m_tooltipcats setdelaytime ttdt_initial theprefs gettooltipdelay m_tooltipcats verifycattabsize lresult c transfer wnd def window proc uint message wparam w param lparam l param switch message arrange transferwindow layout case wm paint if m wndsplitter c rect rc wnd get window rect rc wnd if rc wnd height 0 c rect rc down downloadlistctrl get window rect rc down screen to client rc down splitter paint update c rect rc spl rc spl left wnd2 button xoff wnd2 button width 8 rc spl right rc down right rc spl top rc down bottom wnd splitter yoff rc spl bottom rc spl top wnd splitter height m wndsplitter move window rc spl true m btnwnd2 move window wnd2 button xoff rc spl top wnd splitter yoff 1 wnd2 button width wnd2 button height update splitter range workaround to solve a glitch with wm settingchange message if m btnwnd1 m btnwnd1 m hwnd m btnwnd1 get btn width idc download ico wnd1 button width m btnwnd1 set btn width idc download ico wnd1 button width break return c resizable dialog def window proc message w param l param ctransferwnd defwindowproc wparam lparam wm_paint m_wndsplitter crect rcwnd getwindowrect rcwnd rcwnd crect rcdown getwindowrect rcdown screentoclient rcdown crect rcspl rcspl wnd2_button_xoff wnd2_button_width rcspl rcdown rcspl rcdown wnd_splitter_yoff rcspl rcspl wnd_splitter_height m_wndsplitter movewindow rcspl m_btnwnd2 movewindow wnd2_button_xoff rcspl wnd_splitter_yoff wnd2_button_width wnd2_button_height updatesplitterrange wm_settingchange m_btnwnd1 m_btnwnd1 m_hwnd m_btnwnd1 getbtnwidth idc_download_ico wnd1_button_width m_btnwnd1 setbtnwidth idc_download_ico wnd1_button_width cresizabledialog defwindowproc wparam lparam bool c transfer wnd on command wparam w param lparam l param category filter menuitems if w param mp cat set0 w param mp cat set0 99 if w param mp cat set0 17 the prefs get category m isetcatmenu care4all the prefs get category m isetcatmenu care4all else if w param mp cat set0 19 negate the prefs set cat filter neg m isetcatmenu the prefs get cat filter neg m isetcatmenu else set the view filter if w param mp cat set0 1 dont negate all filter the prefs set cat filter neg m isetcatmenu false the prefs set cat filter m isetcatmenu w param mp cat set0 m nlastcattt 1 set to regexp but none is set for that category if w param mp cat set0 18 the prefs get category m isetcatmenu regexp is empty m nlastcattt 1 c cat dialog dialog rightclickindex dialog do modal still no regexp if the prefs get category m isetcatmenu regexp is empty the prefs set cat filter m isetcatmenu 0 downloadlistctrl update current category view edit cat tab label m isetcatmenu the prefs save cats return true switch w param case mp cat add m nlastcattt 1 int newindex add category t the prefs get incoming dir t t false c cat dialog dialog newindex dialog do modal if dialog was cancelled the prefs remove cat newindex else the app emuledlg searchwnd update cat tabs m dltab insert item newindex the prefs get category newindex title edit cat tab label newindex the prefs save cats verify cat tab size if compare directories the prefs get incoming dir the prefs get cat path newindex the app emuledlg sharedfileswnd reload break case mp cat edit m nlastcattt 1 c string oldincpath the prefs get cat path rightclickindex c cat dialog dialog rightclickindex dialog do modal c string cs name cs name format t s the prefs get category rightclickindex title edit cat tab label rightclickindex cs name the app emuledlg searchwnd update cat tabs the app emuledlg transferwnd downloadlistctrl update current category view the prefs save cats if compare directories oldincpath the prefs get cat path rightclickindex the app emuledlg sharedfileswnd reload break case mp cat remove m nlastcattt 1 bool toreload tcsicmp the prefs get cat path rightclickindex the prefs get incoming dir 0 the app downloadqueue reset cat parts rightclickindex the prefs remove cat rightclickindex m dltab delete item rightclickindex m dltab set cur sel 0 downloadlistctrl change category 0 the prefs save cats if the prefs get cat count 1 the prefs get category 0 filter 0 the app emuledlg searchwnd update cat tabs verify cat tab size if toreload the app emuledlg sharedfileswnd reload break case mp priolow the prefs get category rightclickindex prio pr low the prefs save cats break case mp prionormal the prefs get category rightclickindex prio pr normal the prefs save cats break case mp priohigh the prefs get category rightclickindex prio pr high the prefs save cats break case mp pause the app downloadqueue set cat status rightclickindex mp pause break case mp stop the app downloadqueue set cat status rightclickindex mp stop break case mp cancel if afx message box get res string ids q canceldl mb iconquestion mb yesno idyes the app downloadqueue set cat status rightclickindex mp cancel break case mp resume the app downloadqueue set cat status rightclickindex mp resume break case mp resumenext the app downloadqueue start next file rightclickindex false break case mp download alphabetical bool new setting the prefs get category rightclickindex download in alphabetical order the prefs get category rightclickindex download in alphabetical order new setting the prefs save cats if new setting any auto prio files will be set to normal now the app downloadqueue remove auto prio in cat rightclickindex pr normal break case idc upload ico switch upload list break case mp view2 uploading show wnd2 wnd2 uploading break case mp view2 downloading show wnd2 wnd2 downloading break case mp view2 onqueue show wnd2 wnd2 on queue break case mp view2 clients show wnd2 wnd2 clients break case idc queue refresh button on bn clicked queue refresh button break case idc download ico on bn clicked change view break case mp view1 split window show split window break case mp view1 downloads show list idc downloadlist break case mp view1 uploading show list idc uploadlist break case mp view1 downloading show list idc downloadclients break case mp view1 onqueue show list idc queuelist break case mp view1 clients show list idc clientlist break case mp hm openinc shell execute null t open the prefs get category m isetcatmenu incomingpath null null sw show break return true ctransferwnd oncommand wparam lparam wparam mp_cat_set0 wparam mp_cat_set0 wparam mp_cat_set0 theprefs getcategory m_isetcatmenu theprefs getcategory m_isetcatmenu wparam mp_cat_set0 theprefs setcatfilterneg m_isetcatmenu theprefs getcatfilterneg m_isetcatmenu wparam mp_cat_set0 theprefs setcatfilterneg m_isetcatmenu theprefs setcatfilter m_isetcatmenu wparam mp_cat_set0 m_nlastcattt wparam mp_cat_set0 theprefs getcategory m_isetcatmenu isempty m_nlastcattt ccatdialog domodal theprefs getcategory m_isetcatmenu isempty theprefs setcatfilter m_isetcatmenu updatecurrentcategoryview editcattablabel m_isetcatmenu theprefs savecats wparam mp_cat_add m_nlastcattt addcategory _t theprefs getincomingdir _t _t ccatdialog domodal wascancelled theprefs removecat theapp updatecattabs m_dltab insertitem theprefs getcategory editcattablabel theprefs savecats verifycattabsize comparedirectories theprefs getincomingdir theprefs getcatpath theapp mp_cat_edit m_nlastcattt cstring theprefs getcatpath ccatdialog domodal cstring csname csname _t theprefs getcategory editcattablabel csname theapp updatecattabs theapp updatecurrentcategoryview theprefs savecats comparedirectories theprefs getcatpath theapp mp_cat_remove m_nlastcattt _tcsicmp theprefs getcatpath theprefs getincomingdir theapp resetcatparts theprefs removecat m_dltab deleteitem m_dltab setcursel changecategory theprefs savecats theprefs getcatcount theprefs getcategory theapp updatecattabs verifycattabsize theapp mp_priolow theprefs getcategory pr_low theprefs savecats mp_prionormal theprefs getcategory pr_normal theprefs savecats mp_priohigh theprefs getcategory pr_high theprefs savecats mp_pause theapp setcatstatus mp_pause mp_stop theapp setcatstatus mp_stop mp_cancel afxmessagebox getresstring ids_q_canceldl mb_iconquestion mb_yesno theapp setcatstatus mp_cancel mp_resume theapp setcatstatus mp_resume mp_resumenext theapp startnextfile mp_download_alphabetical newsetting theprefs getcategory downloadinalphabeticalorder theprefs getcategory downloadinalphabeticalorder newsetting theprefs savecats newsetting theapp removeautoprioincat pr_normal idc_upload_ico switchuploadlist mp_view2_uploading showwnd2 wnd2uploading mp_view2_downloading showwnd2 wnd2downloading mp_view2_onqueue showwnd2 wnd2onqueue mp_view2_clients showwnd2 wnd2clients idc_queue_refresh_button onbnclickedqueuerefreshbutton idc_download_ico onbnclickedchangeview mp_view1_split_window showsplitwindow mp_view1_downloads showlist idc_downloadlist mp_view1_uploading showlist idc_uploadlist mp_view1_downloading showlist idc_downloadclients mp_view1_onqueue showlist idc_queuelist mp_view1_clients showlist idc_clientlist mp_hm_openinc shellexecute _t theprefs getcategory m_isetcatmenu sw_show void c transfer wnd on hover upload list nmhdr pnmhdr lresult p result downloadlistactive false p result 0 ctransferwnd onhoveruploadlist presult presult void c transfer wnd on hover download list nmhdr pnmhdr lresult p result downloadlistactive true p result 0 ctransferwnd onhoverdownloadlist presult presult void c transfer wnd on tcn selchange dltab nmhdr pnmhdr lresult p result downloadlistctrl change category m dltab get cur sel p result 0 ctransferwnd ontcnselchangedltab presult changecategory m_dltab getcursel presult void c transfer wnd onnm rclick dltab nmhdr pnmhdr lresult p result point point get cursor pos point c point pt point rightclickindex get tab under mouse pt if rightclickindex 1 return c menu prio menu prio menu create menu category struct category struct the prefs get category rightclickindex prio menu append menu mf string mp priolow get res string ids priolow prio menu check menu item mp priolow category struct category struct prio pr low mf checked mf unchecked prio menu append menu mf string mp prionormal get res string ids prionormal prio menu check menu item mp prionormal category struct category struct prio pr low category struct prio pr high mf checked mf unchecked prio menu append menu mf string mp priohigh get res string ids priohigh prio menu check menu item mp priohigh category struct category struct prio pr high mf checked mf unchecked c title menu menu menu create popup menu if rightclickindex menu add menu title get res string ids cat t the prefs get category rightclickindex title t true else menu add menu title get res string ids cat true m isetcatmenu rightclickindex c menu cat menu cat menu create menu cat menu append menu mf string mp cat set0 get res string ids all uint flag the prefs get category rightclickindex care4all rightclickindex mf grayed mf string cat menu append menu flag mp cat set0 1 get res string ids allothers selector for regular expression view filter if rightclickindex if the prefs is ext controls enabled cat menu append menu mf string mp cat set0 18 get res string ids regexpression flag mf string if the prefs get category rightclickindex care4all flag flag mf checked mf bycommand if the prefs is ext controls enabled cat menu append menu flag mp cat set0 17 get res string ids care4all cat menu append menu mf separator cat menu append menu mf string mp cat set0 2 get res string ids status notcompleted cat menu append menu mf string mp cat set0 3 get res string ids dl transfcompl cat menu append menu mf string mp cat set0 4 get res string ids waiting cat menu append menu mf string mp cat set0 5 get res string ids downloading cat menu append menu mf string mp cat set0 6 get res string ids errorlike cat menu append menu mf string mp cat set0 7 get res string ids paused cat menu append menu mf string mp cat set0 8 get res string ids seencompl cat menu append menu mf separator cat menu append menu mf string mp cat set0 10 get res string ids video cat menu append menu mf string mp cat set0 11 get res string ids audio cat menu append menu mf string mp cat set0 12 get res string ids search arc cat menu append menu mf string mp cat set0 13 get res string ids search cdimg cat menu append menu mf string mp cat set0 14 get res string ids search doc cat menu append menu mf string mp cat set0 15 get res string ids search pics cat menu append menu mf string mp cat set0 16 get res string ids search prg cat menu append menu mf string mp cat set0 20 get res string ids search emulecollection if the prefs is ext controls enabled cat menu append menu mf separator cat menu append menu the prefs get cat filter rightclickindex 0 mf string mf grayed mp cat set0 19 get res string ids negatefilter if the prefs get cat filter neg rightclickindex cat menu check menu item mp cat set0 19 mf checked mf bycommand cat menu check menu item mp cat set0 the prefs get cat filter rightclickindex mf checked mf bycommand menu append menu mf string mf popup uint ptr cat menu m hmenu get res string ids changecatview t searchparams menu append menu mf separator menu append menu mf string mf popup uint ptr prio menu m hmenu get res string ids priority t filepriority menu append menu mf string mp cancel get res string ids main btn cancel t delete menu append menu mf string mp stop get res string ids dl stop t stop menu append menu mf string mp pause get res string ids dl pause t pause menu append menu mf string mp resume get res string ids dl resume t resume menu append menu mf string mp resumenext get res string ids dl resumenext t resume if rightclickindex 0 the prefs is ext controls enabled menu append menu mf string mp download alphabetical get res string ids download alphabetical menu check menu item mp download alphabetical category struct category struct download in alphabetical order mf checked mf unchecked menu append menu mf separator menu append menu mf string mp hm openinc get res string ids openinc t folders flag rightclickindex 0 mf grayed mf string menu append menu mf separator menu append menu mf string mp cat add get res string ids cat add menu append menu flag mp cat edit get res string ids cat edit menu append menu flag mp cat remove get res string ids cat remove menu track popup menu tpm leftalign tpm rightbutton point x point y this verify prio menu destroy menu verify cat menu destroy menu verify menu destroy menu p result 0 ctransferwnd onnmrclickdltab presult getcursorpos cpoint gettabundermouse cmenu priomenu priomenu createmenu category_struct category_struct theprefs getcategory priomenu appendmenu mf_string mp_priolow getresstring ids_priolow priomenu checkmenuitem mp_priolow category_struct category_struct pr_low mf_checked mf_unchecked priomenu appendmenu mf_string mp_prionormal getresstring ids_prionormal priomenu checkmenuitem mp_prionormal category_struct category_struct pr_low category_struct pr_high mf_checked mf_unchecked priomenu appendmenu mf_string mp_priohigh getresstring ids_priohigh priomenu checkmenuitem mp_priohigh category_struct category_struct pr_high mf_checked mf_unchecked ctitlemenu createpopupmenu addmenutitle getresstring ids_cat _t theprefs getcategory _t addmenutitle getresstring ids_cat m_isetcatmenu cmenu catmenu catmenu createmenu catmenu appendmenu mf_string mp_cat_set0 getresstring ids_all theprefs getcategory mf_grayed mf_string catmenu appendmenu mp_cat_set0 getresstring ids_allothers theprefs isextcontrolsenabled catmenu appendmenu mf_string mp_cat_set0 getresstring ids_regexpression mf_string theprefs getcategory mf_checked mf_bycommand theprefs isextcontrolsenabled catmenu appendmenu mp_cat_set0 getresstring ids_care4all catmenu appendmenu mf_separator catmenu appendmenu mf_string mp_cat_set0 getresstring ids_status_notcompleted catmenu appendmenu mf_string mp_cat_set0 getresstring ids_dl_transfcompl catmenu appendmenu mf_string mp_cat_set0 getresstring ids_waiting catmenu appendmenu mf_string mp_cat_set0 getresstring ids_downloading catmenu appendmenu mf_string mp_cat_set0 getresstring ids_errorlike catmenu appendmenu mf_string mp_cat_set0 getresstring ids_paused catmenu appendmenu mf_string mp_cat_set0 getresstring ids_seencompl catmenu appendmenu mf_separator catmenu appendmenu mf_string mp_cat_set0 getresstring ids_video catmenu appendmenu mf_string mp_cat_set0 getresstring ids_audio catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_arc catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_cdimg catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_doc catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_pics catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_prg catmenu appendmenu mf_string mp_cat_set0 getresstring ids_search_emulecollection theprefs isextcontrolsenabled catmenu appendmenu mf_separator catmenu appendmenu theprefs getcatfilter mf_string mf_grayed mp_cat_set0 getresstring ids_negatefilter theprefs getcatfilterneg catmenu checkmenuitem mp_cat_set0 mf_checked mf_bycommand catmenu checkmenuitem mp_cat_set0 theprefs getcatfilter mf_checked mf_bycommand appendmenu mf_string mf_popup uint_ptr catmenu m_hmenu getresstring ids_changecatview _t appendmenu mf_separator appendmenu mf_string mf_popup uint_ptr priomenu m_hmenu getresstring ids_priority _t appendmenu mf_string mp_cancel getresstring ids_main_btn_cancel _t appendmenu mf_string mp_stop getresstring ids_dl_stop _t appendmenu mf_string mp_pause getresstring ids_dl_pause _t appendmenu mf_string mp_resume getresstring ids_dl_resume _t appendmenu mf_string mp_resumenext getresstring ids_dl_resumenext _t theprefs isextcontrolsenabled appendmenu mf_string mp_download_alphabetical getresstring ids_download_alphabetical checkmenuitem mp_download_alphabetical category_struct category_struct downloadinalphabeticalorder mf_checked mf_unchecked appendmenu mf_separator appendmenu mf_string mp_hm_openinc getresstring ids_openinc _t mf_grayed mf_string appendmenu mf_separator appendmenu mf_string mp_cat_add getresstring ids_cat_add appendmenu mp_cat_edit getresstring ids_cat_edit appendmenu mp_cat_remove getresstring ids_cat_remove trackpopupmenu tpm_leftalign tpm_rightbutton priomenu destroymenu catmenu destroymenu destroymenu presult void c transfer wnd on lvn begindrag nmhdr pnmhdr lresult p result int i sel downloadlistctrl get selection mark if i sel 1 return if ctrlitem struct downloadlistctrl get item data i sel type file type return m bisdragging true point pt get cursor pos pt lpnmlistview pnmlv reinterpret cast lpnmlistview pnmhdr m ndragindex pnmlv i item m pdragimage downloadlistctrl create drag image downloadlistctrl get selection mark pt m pdragimage begin drag 0 c point 0 0 m pdragimage drag enter get desktop window pnmlv pt action set capture m ndropindex 1 p result 0 ctransferwnd onlvnbegindrag presult isel getselectionmark isel ctrlitem_struct getitemdata isel file_type m_bisdragging getcursorpos reinterpret_cast m_ndragindex iitem m_pdragimage createdragimage getselectionmark m_pdragimage begindrag cpoint m_pdragimage dragenter getdesktopwindow ptaction setcapture m_ndropindex presult void c transfer wnd on tab movement nmhdr pnmhdr lresult p result uint from m dltab get last movement source uint to m dltab get last movement destionation if from 0 to 0 from to 1 return do the reorder rearrange the cat map if the prefs move cat from to return update partfile stored assignment the app downloadqueue move cat uint8 from uint8 to move category of completed files downloadlistctrl move completedfiles cat uint8 from uint8 to of the tabcontrol itself m dltab reorder tab from to update cat tab titles the app emuledlg searchwnd update cat tabs if to from to m dltab set cur sel to downloadlistctrl change category to ctransferwnd ontabmovement presult m_dltab getlastmovementsource m_dltab getlastmovementdestionation theprefs movecat theapp movecat movecompletedfilescat m_dltab reordertab updatecattabtitles theapp updatecattabs m_dltab setcursel changecategory void c transfer wnd on mouse move uint n flags c point point if n flags mk lbutton m bisdragging false if m bisdragging c point pt point get our current mouse coordinates client to screen pt convert to screen coordinates m ndropindex get tab under mouse pt if m ndropindex 0 the prefs get category m ndropindex care4all not droppable m dltab set cur sel 1 else m dltab set cur sel m ndropindex m dltab invalidate get cursor pos pt pt y 10 m pdragimage drag move pt move the drag image to those coordinates ctransferwnd onmousemove nflags cpoint nflags mk_lbutton m_bisdragging m_bisdragging cpoint clienttoscreen m_ndropindex gettabundermouse m_ndropindex theprefs getcategory m_ndropindex m_dltab setcursel m_dltab setcursel m_ndropindex m_dltab getcursorpos m_pdragimage dragmove void c transfer wnd onl button up uint n flags c point point if m bisdragging release capture m bisdragging false m pdragimage drag leave get desktop window m pdragimage end drag delete m pdragimage if m ndropindex 1 downloadlistctrl cur tab 0 downloadlistctrl cur tab 0 uint m ndropindex downloadlistctrl cur tab c part file file for multiselections c typed ptr list c ptr list c part file selected list position pos downloadlistctrl get first selected item position while pos null int index downloadlistctrl get next selected item pos if index 1 ctrlitem struct downloadlistctrl get item data index type file type selected list add tail c part file ctrlitem struct downloadlistctrl get item data index value while selected list is empty file selected list get head selected list remove head file set category m ndropindex m dltab set cur sel downloadlistctrl cur tab if m dltab get cur sel 0 the prefs get allcat type 1 m dltab get cur sel 0 downloadlistctrl update current category view update cat tab titles else m dltab set cur sel downloadlistctrl cur tab downloadlistctrl invalidate ctransferwnd onlbuttonup nflags cpoint m_bisdragging releasecapture m_bisdragging m_pdragimage dragleave getdesktopwindow m_pdragimage enddrag m_pdragimage m_ndropindex curtab curtab m_ndropindex curtab cpartfile ctypedptrlist cptrlist cpartfile selectedlist getfirstselecteditemposition getnextselecteditem ctrlitem_struct getitemdata file_type selectedlist addtail cpartfile ctrlitem_struct getitemdata selectedlist isempty selectedlist gethead selectedlist removehead setcategory m_ndropindex m_dltab setcursel curtab m_dltab getcursel theprefs getallcattype m_dltab getcursel updatecurrentcategoryview updatecattabtitles m_dltab setcursel curtab void c transfer wnd on lvn keydown downloadlist nmhdr pnmhdr lresult p result lpnmlvkeydown plv key dow reinterpret cast lpnmlvkeydown pnmhdr int i item downloadlistctrl get selection mark if i item 1 bool b alt key get async key state vk menu 0 int i action expand collapse if plv key dow wv key vk add b alt key plv key dow wv key vk right i action expand only else if plv key dow wv key vk subtract b alt key plv key dow wv key vk left i action collapse only if i action expand collapse downloadlistctrl expand collapse item i item i action true p result 0 ctransferwnd onlvnkeydowndownloadlist presult plvkeydow reinterpret_cast iitem getselectionmark iitem baltkey getasynckeystate vk_menu iaction expand_collapse plvkeydow wvkey vk_add baltkey plvkeydow wvkey vk_right iaction expand_only plvkeydow wvkey vk_subtract baltkey plvkeydow wvkey vk_left iaction collapse_only iaction expand_collapse expandcollapseitem iitem iaction presult void c transfer wnd on sys color change c resizable dialog on sys color change set all icons m btnwnd1 invalidate ctransferwnd onsyscolorchange cresizabledialog onsyscolorchange setallicons m_btnwnd1 void c transfer wnd on setting change uint u flags lpctstr lpsz section c resizable dialog on setting change u flags lpsz section it does not work to reset the width of 1st button here m btnwnd1 set btn width idc download ico wnd1 button width ctransferwnd onsettingchange uflags lpszsection cresizabledialog onsettingchange uflags lpszsection m_btnwnd1 setbtnwidth idc_download_ico wnd1_button_width void c transfer wnd on dblclick dltab point point get cursor pos point c point pt point int tab get tab under mouse pt if tab 1 return rightclickindex tab on command mp cat edit 0 ctransferwnd ondblclickdltab getcursorpos cpoint gettabundermouse oncommand mp_cat_edit void c transfer wnd on bn clicked queue refresh button c up down client update the app uploadqueue get next client null while update the app emuledlg transferwnd queuelistctrl refresh client update update the app uploadqueue get next client update ctransferwnd onbnclickedqueuerefreshbutton cupdownclient theapp getnextclient theapp refreshclient theapp getnextclient void c transfer wnd on bn clicked change view switch m dwshowlistidc case idc downloadlist show list idc uploadlist break case idc uploadlist show list idc downloadclients break case idc downloadclients if the prefs is queue list disabled show list idc queuelist break case idc queuelist if the prefs is known client list disabled show list idc clientlist break case idc clientlist show split window break case idc uploadlist idc downloadlist show list idc downloadlist break ctransferwnd onbnclickedchangeview m_dwshowlistidc idc_downloadlist showlist idc_uploadlist idc_uploadlist showlist idc_downloadclients idc_downloadclients theprefs isqueuelistdisabled showlist idc_queuelist idc_queuelist theprefs isknownclientlistdisabled showlist idc_clientlist idc_clientlist showsplitwindow idc_uploadlist idc_downloadlist showlist idc_downloadlist void c transfer wnd on wnd1 btn drop down nmhdr pnmhdr lresult p result c title menu menu menu create popup menu menu enable icons menu append menu mf string m dwshowlistidc idc downloadlist idc uploadlist mf grayed 0 mp view1 split window get res string ids split window t split window menu append menu mf separator menu append menu mf string m dwshowlistidc idc downloadlist mf grayed 0 mp view1 downloads get res string ids tw downloads t download files menu append menu mf string m dwshowlistidc idc uploadlist mf grayed 0 mp view1 uploading get res string ids uploading t upload menu append menu mf string m dwshowlistidc idc downloadclients mf grayed 0 mp view1 downloading get res string ids downloading t download if the prefs is queue list disabled menu append menu mf string m dwshowlistidc idc queuelist mf grayed 0 mp view1 onqueue get res string ids onqueue t clients on queue if the prefs is known client list disabled menu append menu mf string m dwshowlistidc idc clientlist mf grayed 0 mp view1 clients get res string ids clientlist t clients known c rect rc m btnwnd1 get window rect rc menu track popup menu tpm leftalign tpm rightbutton rc left rc bottom this ctransferwnd onwnd1btndropdown presult ctitlemenu createpopupmenu enableicons appendmenu mf_string m_dwshowlistidc idc_downloadlist idc_uploadlist mf_grayed mp_view1_split_window getresstring ids_split_window _t splitwindow appendmenu mf_separator appendmenu mf_string m_dwshowlistidc idc_downloadlist mf_grayed mp_view1_downloads getresstring ids_tw_downloads _t downloadfiles appendmenu mf_string m_dwshowlistidc idc_uploadlist mf_grayed mp_view1_uploading getresstring ids_uploading _t appendmenu mf_string m_dwshowlistidc idc_downloadclients mf_grayed mp_view1_downloading getresstring ids_downloading _t theprefs isqueuelistdisabled appendmenu mf_string m_dwshowlistidc idc_queuelist mf_grayed mp_view1_onqueue getresstring ids_onqueue _t clientsonqueue theprefs isknownclientlistdisabled appendmenu mf_string m_dwshowlistidc idc_clientlist mf_grayed mp_view1_clients getresstring ids_clientlist _t clientsknown crect m_btnwnd1 getwindowrect trackpopupmenu tpm_leftalign tpm_rightbutton void c transfer wnd on wnd2 btn drop down nmhdr pnmhdr lresult p result c title menu menu menu create popup menu menu enable icons menu append menu mf string m uwnd2 wnd2 uploading mf grayed 0 mp view2 uploading get res string ids uploading t upload menu append menu mf string m uwnd2 wnd2 downloading mf grayed 0 mp view2 downloading get res string ids downloading t download if the prefs is queue list disabled menu append menu mf string m uwnd2 wnd2 on queue mf grayed 0 mp view2 onqueue get res string ids onqueue t clients on queue if the prefs is known client list disabled menu append menu mf string m uwnd2 wnd2 clients mf grayed 0 mp view2 clients get res string ids clientlist t clients known c rect rc m btnwnd2 get window rect rc menu track popup menu tpm leftalign tpm rightbutton rc left rc bottom this ctransferwnd onwnd2btndropdown presult ctitlemenu createpopupmenu enableicons appendmenu mf_string m_uwnd2 wnd2uploading mf_grayed mp_view2_uploading getresstring ids_uploading _t appendmenu mf_string m_uwnd2 wnd2downloading mf_grayed mp_view2_downloading getresstring ids_downloading _t theprefs isqueuelistdisabled appendmenu mf_string m_uwnd2 wnd2onqueue mf_grayed mp_view2_onqueue getresstring ids_onqueue _t clientsonqueue theprefs isknownclientlistdisabled appendmenu mf_string m_uwnd2 wnd2clients mf_grayed mp_view2_clients getresstring ids_clientlist _t clientsknown crect m_btnwnd2 getwindowrect trackpopupmenu tpm_leftalign tpm_rightbutton void c transfer wnd on splitter moved nmhdr pnmhdr lresult p result spc nmhdr p hdr spc nmhdr pnmhdr do resize p hdr delta ctransferwnd onsplittermoved presult spc_nmhdr phdr spc_nmhdr doresize phdr void c transfer wnd on window pos changed windowpos lpwndpos if m wndsplitter c rect rc wnd get window rect rc wnd if rc wnd height 0 invalidate c resizable dialog on window pos changed lpwndpos ctransferwnd onwindowposchanged m_wndsplitter crect rcwnd getwindowrect rcwnd rcwnd cresizabledialog onwindowposchanged c splitter control c splitter control mouse is pressed down or not m bispressed false min and max range of the splitter m nmin m nmax 1 csplittercontrol csplittercontrol m_bispressed m_nmin m_nmax c splitter control c splitter control csplittercontrol csplittercontrol void c splitter control create dword dw style const c rect rect c wnd p parent uint nid c rect rc rect dw style ss notify determine default type base on it s size m ntype rc width rc height sps vertical sps horizontal if m ntype sps vertical rc right rc left 5 else sps horizontal rc bottom rc top 5 c static create t dw style rc p parent nid if m hcurmovevert m hcurmovevert afx get app load standard cursor idc sizewe m hcurmovehorz afx get app load standard cursor idc sizens force the splitter not to be splited set range 0 0 1 csplittercontrol dwstyle crect cwnd pparent crect dwstyle ss_notify m_ntype sps_vertical sps_horizontal m_ntype sps_vertical sps_horizontal cstatic _t dwstyle pparent m_hcurmovevert m_hcurmovevert afxgetapp loadstandardcursor idc_sizewe m_hcurmovehorz afxgetapp loadstandardcursor idc_sizens setrange int c splitter control get style return m ntype csplittercontrol getstyle m_ntype int c splitter control set style int n style int m noldstyle m ntype m ntype n style return m noldstyle csplittercontrol setstyle nstyle m_noldstyle m_ntype m_ntype nstyle m_noldstyle void c splitter control set range int n min int n max m nmin n min m nmax n max csplittercontrol setrange nmin nmax m_nmin nmin m_nmax nmax void c splitter control set range int n subtraction int n addition int n root if n root 0 c rect rc wnd get window rect rc wnd if m ntype sps vertical n root rc wnd left rc wnd width 2 else if m ntype sps horizontal n root rc wnd top rc wnd height 2 m nmin n root n subtraction m nmax n root n addition csplittercontrol setrange nsubtraction naddition nroot nroot crect rcwnd getwindowrect rcwnd m_ntype sps_vertical nroot rcwnd rcwnd m_ntype sps_horizontal nroot rcwnd rcwnd m_nmin nroot nsubtraction m_nmax nroot naddition void c splitter control change pos c wnd p wnd int dx int dy c wnd p parent p wnd get parent if p parent is window p parent m hwnd c rect rc wnd p wnd get window rect rc wnd p parent screen to client rc wnd rc wnd offset rect dx dy p wnd move window rc wnd csplittercontrol changepos cwnd pwnd cwnd pparent pwnd getparent pparent iswindow pparent m_hwnd crect rcwnd pwnd getwindowrect rcwnd pparent screentoclient rcwnd rcwnd offsetrect pwnd movewindow rcwnd void c splitter control change width c wnd p wnd int dx dword dw flag c wnd p parent p wnd get parent if p parent is window p parent m hwnd c rect rc wnd p wnd get window rect rc wnd p parent screen to client rc wnd if dw flag cw leftalign rc wnd right dx else if dw flag cw rightalign rc wnd left dx p wnd move window rc wnd csplittercontrol changewidth cwnd pwnd dwflag cwnd pparent pwnd getparent pparent iswindow pparent m_hwnd crect rcwnd pwnd getwindowrect rcwnd pparent screentoclient rcwnd dwflag cw_leftalign rcwnd dwflag cw_rightalign rcwnd pwnd movewindow rcwnd void c splitter control change height c wnd p wnd int dy dword dw flag c wnd p parent p wnd get parent if p parent is window p parent m hwnd c rect rc wnd p wnd get window rect rc wnd p parent screen to client rc wnd if dw flag cw topalign rc wnd bottom dy else if dw flag cw bottomalign rc wnd top dy p wnd move window rc wnd else assert 0 csplittercontrol changeheight cwnd pwnd dwflag cwnd pparent pwnd getparent pparent iswindow pparent m_hwnd crect rcwnd pwnd getwindowrect rcwnd pparent screentoclient rcwnd dwflag cw_topalign rcwnd dwflag cw_bottomalign rcwnd pwnd movewindow rcwnd void c splitter control move window to c point pt c rect rc get window rect rc c wnd p parent p parent get parent if p parent is window p parent m hwnd return p parent screen to client rc if m ntype sps vertical int n midx rc left rc right 2 int dx pt x n midx rc offset rect dx 0 else int n midy rc top rc bottom 2 int dy pt y n midy rc offset rect 0 dy move window rc csplittercontrol movewindowto cpoint crect getwindowrect cwnd pparent pparent getparent pparent iswindow pparent m_hwnd pparent screentoclient m_ntype sps_vertical nmidx nmidx offsetrect nmidy nmidy offsetrect movewindow void c splitter control draw line cdc pdc int x int y int n rop pdc setrop2 r2 notxorpen c rect rc wnd get window rect rc wnd c pen pen pen create pen 0 1 rgb 200 200 200 c pen pop pdc select object pen int d 1 if m ntype sps vertical pdc move to m nx d rc wnd top pdc line to m nx d rc wnd bottom pdc move to m nx d rc wnd top pdc line to m nx d rc wnd bottom else m ntype sps horizontal pdc move to rc wnd left m ny d pdc line to rc wnd right m ny d pdc move to rc wnd left m ny d pdc line to rc wnd right m ny d pdc setrop2 n rop pdc select object pop csplittercontrol drawline nrop r2_notxorpen crect rcwnd getwindowrect rcwnd cpen createpen cpen selectobject m_ntype sps_vertical moveto m_nx rcwnd lineto m_nx rcwnd moveto m_nx rcwnd lineto m_nx rcwnd m_ntype sps_horizontal moveto rcwnd m_ny lineto rcwnd m_ny moveto rcwnd m_ny lineto rcwnd m_ny nrop selectobject void c splitter control on paint c paintdc dc this device context for painting c rect rc client get client rect rc client dc fill solid rect rc client get sys color color 3dface dc draw3d rect rc client get sys color color btnhighlight get sys color color btnshadow csplittercontrol onpaint cpaintdc crect rcclient getclientrect rcclient fillsolidrect rcclient getsyscolor color_3dface draw3drect rcclient getsyscolor color_btnhighlight getsyscolor color_btnshadow void c splitter control on mouse move uint n flags c point point if m bispressed c windowdc dc null draw line dc m nx m ny c point pt point client to screen pt get parent screen to client pt if pt x m nmin pt x m nmin if pt y m nmin pt y m nmin if pt x m nmax pt x m nmax if pt y m nmax pt y m nmax get parent client to screen pt m nx pt x m ny pt y draw line dc m nx m ny c static on mouse move n flags point csplittercontrol onmousemove nflags cpoint m_bispressed cwindowdc drawline m_nx m_ny cpoint clienttoscreen getparent screentoclient m_nmin m_nmin m_nmin m_nmin m_nmax m_nmax m_nmax m_nmax getparent clienttoscreen m_nx m_ny drawline m_nx m_ny cstatic onmousemove nflags bool c splitter control on set cursor c wnd p wnd uint n hit test uint message if n hit test htclient m ntype sps vertical set cursor m hcurmovevert set cursor m hcurmovehorz return 0 else return c static on set cursor p wnd n hit test message csplittercontrol onsetcursor cwnd pwnd nhittest nhittest m_ntype sps_vertical setcursor m_hcurmovevert setcursor m_hcurmovehorz cstatic onsetcursor pwnd nhittest void c splitter control onl button down uint n flags c point point c static onl button down n flags point m bispressed true set capture c rect rc wnd get window rect rc wnd if m ntype sps vertical m nx rc wnd left rc wnd width 2 else m ny rc wnd top rc wnd height 2 if m ntype sps vertical m nsavepos m nx else m nsavepos m ny c windowdc dc null draw line dc m nx m ny csplittercontrol onlbuttondown nflags cpoint cstatic onlbuttondown nflags m_bispressed setcapture crect rcwnd getwindowrect rcwnd m_ntype sps_vertical m_nx rcwnd rcwnd m_ny rcwnd rcwnd m_ntype sps_vertical m_nsavepos m_nx m_nsavepos m_ny cwindowdc drawline m_nx m_ny void c splitter control onl button up uint n flags c point point if m bispressed client to screen point c windowdc dc null draw line dc m nx m ny c point pt m nx m ny m bispressed false c wnd p owner get owner if p owner is window p owner m hwnd c rect rc p owner get client rect rc p owner screen to client pt move window to pt int delta if m ntype sps vertical delta m nx m nsavepos else delta m ny m nsavepos spc nmhdr nmsp nmsp hdr hwnd from m hwnd nmsp hdr id from get dlg ctrlid nmsp hdr code um spn sized nmsp delta delta p owner send message wm notify nmsp hdr id from lparam nmsp c static onl button up n flags point release capture csplittercontrol onlbuttonup nflags cpoint m_bispressed clienttoscreen cwindowdc drawline m_nx m_ny cpoint m_nx m_ny m_bispressed cwnd powner getowner powner iswindow powner m_hwnd crect powner getclientrect powner screentoclient movewindowto m_ntype sps_vertical m_nx m_nsavepos m_ny m_nsavepos spc_nmhdr hwndfrom m_hwnd idfrom getdlgctrlid um_spn_sized powner sendmessage wm_notify idfrom cstatic onlbuttonup nflags releasecapture static void add2 down session completed files ses down completed files static void add2 session transfer data uint u clientid uint u client port bool b frompf bool b up down uint32 bytes bool sent to friend false static void add2 down successful sessions ses down successful sessions cum down successful sessions add2downsessioncompletedfiles sesdowncompletedfiles add2sessiontransferdata uclientid uclientport bfrompf bupdown senttofriend add2downsuccessfulsessions sesdownsuccessfulsessions cumdownsuccessfulsessions static void add2 down successful sessions ses down successful sessions cum down successful sessions static void add2 down failed sessions ses down failed sessions cum down failed sessions add2downsuccessfulsessions sesdownsuccessfulsessions cumdownsuccessfulsessions add2downfailedsessions sesdownfailedsessions cumdownfailedsessions cumulative client breakdown stats for sent bytes static uint64 get up total client data return getcumupdata edonkey getcumupdata edonkeyhybrid getcumupdata emule getcumupdata mldonkey getcumupdata amule getcumupdata emulecompat getuptotalclientdata getcumupdata_edonkey getcumupdata_edonkeyhybrid getcumupdata_emule getcumupdata_mldonkey getcumupdata_amule getcumupdata_emulecompat session client breakdown stats for sent bytes static uint64 get up session client data return sesupdata edonkey sesupdata edonkeyhybrid sesupdata emule sesupdata mldonkey sesupdata amule sesupdata emulecompat getupsessionclientdata sesupdata_edonkey sesupdata_edonkeyhybrid sesupdata_emule sesupdata_mldonkey sesupdata_amule sesupdata_emulecompat cumulative port breakdown stats for sent bytes static uint64 get up total port data return getcumupdataport 4662 getcumupdataport other getuptotalportdata getcumupdataport_4662 getcumupdataport_other session port breakdown stats for sent bytes static uint64 get up session port data return sesupdataport 4662 sesupdataport other getupsessionportdata sesupdataport_4662 sesupdataport_other cumulative client breakdown stats for received bytes static uint64 get down total client data return getcumdowndata edonkey getcumdowndata edonkeyhybrid getcumdowndata emule getcumdowndata mldonkey getcumdowndata amule getcumdowndata emulecompat getcumdowndata shareaza getdowntotalclientdata getcumdowndata_edonkey getcumdowndata_edonkeyhybrid getcumdowndata_emule getcumdowndata_mldonkey getcumdowndata_amule getcumdowndata_emulecompat getcumdowndata_shareaza session client breakdown stats for received bytes static uint64 get down session client data return sesdowndata edonkey sesdowndata edonkeyhybrid sesdowndata emule sesdowndata mldonkey sesdowndata amule sesdowndata emulecompat sesdowndata shareaza getdownsessionclientdata sesdowndata_edonkey sesdowndata_edonkeyhybrid sesdowndata_emule sesdowndata_mldonkey sesdowndata_amule sesdowndata_emulecompat sesdowndata_shareaza cumulative port breakdown stats for received bytes static uint64 get down total port data return getcumdowndataport 4662 getcumdowndataport other getdowntotalportdata getcumdowndataport_4662 getcumdowndataport_other session port breakdown stats for received bytes static uint64 get down session data port return sesdowndataport 4662 sesdowndataport other getdownsessiondataport sesdowndataport_4662 sesdowndataport_other word c preferences get languageid return m wlanguageid cpreferences getlanguageid m_wlanguageid void c preferences set languageid word lid m wlanguageid lid cpreferences setlanguageid m_wlanguageid void c preferences get languages c word array a languagei ds const s language p lang alanguages while p lang lid if p lang b supported show all languages offer download if not supported ones later a languagei ds add p lang lid p lang cpreferences getlanguages cwordarray alanguageids slanguage plang _alanguages plang plang bsupported alanguageids plang plang void c preferences set language init languages get lang dir bool b found lang false if m wlanguageid b found lang load lang lib get lang dir m wlanguageid if b found lang langid lid locale langid get thread locale langid lid locale pri primarylangid get thread locale langid lid locale sub sublangid get thread locale b found lang load lang lib get lang dir lid locale if b found lang load lang lib get lang dir langid en us m wlanguageid langid en us c string str lng english get res string ids mb languageinfo afx message box str lng english mb iconasterisk else m wlanguageid lid locale if loading a string fails set language to english if get res string ids mb languageinfo is empty load lang lib get lang dir langid en us m wlanguageid langid en us init thread locale cpreferences setlanguage initlanguages getlangdir bfoundlang m_wlanguageid bfoundlang loadlanglib getlangdir m_wlanguageid bfoundlang lidlocale getthreadlocale lidlocalepri getthreadlocale lidlocalesub getthreadlocale bfoundlang loadlanglib getlangdir lidlocale bfoundlang loadlanglib getlangdir langid_en_us m_wlanguageid langid_en_us cstring strlngenglish getresstring ids_mb_languageinfo afxmessagebox strlngenglish mb_iconasterisk m_wlanguageid lidlocale getresstring ids_mb_languageinfo isempty loadlanglib getlangdir langid_en_us m_wlanguageid langid_en_us initthreadlocale bool c preferences is language supported langid lid selected bool b update before init languages get lang dir b update before if lid selected langid en us return true const s language p lang alanguages for p lang lid p lang if p lang lid lid selected p lang b supported return check langdll version get lang dir c string p lang psziso locale t dll return false cpreferences islanguagesupported lidselected bupdatebefore initlanguages getlangdir bupdatebefore lidselected langid_en_us slanguage plang _alanguages plang plang plang lidselected plang bsupported checklangdllversion getlangdir cstring plang pszisolocale _t c string c preferences get langdll name byid langid lid selected const s language p lang alanguages for p lang lid p lang if p lang lid lid selected return c string p lang psziso locale t dll assert false return c string t cstring cpreferences getlangdllnamebyid lidselected slanguage plang _alanguages plang plang plang lidselected cstring plang pszisolocale _t cstring _t void c preferences init thread locale assert m wlanguageid 0 note this function is for testing multi language support only note this function is not to be enabled in release builds nor to be offered by any mod if the app get profile int t e mule t set languageacp 0 0 lcid lcid user get user defaultlcid installation or altered by user in control panel winxp get the ansi codepage which is to be used for all non unicode conversions langid lid system m wlanguageid get user s sorting preferences uint u sort id user sortidfromlcid lcid user uint u sort ver user sortversionfromlcid lcid user we can t use the same sorting paramters for 2 different languages uint u sort id user sort default uint u sort ver user 0 set thread locale this is used for mbcs unicode conversions e g search results unicode mbcs conversions e g publishing local files names in network or savint text files on local disk lcid lcid makesortlcid lid system u sort id user u sort ver user set thread locale lcid if we set the thread locale see comments above we also have to specify the proper codepage for the c rtl otherwise we may not be able to store some strings as mbcs unicode mbcs conversion may fail set rtl locale lcid else if the app get profile int t e mule t set systemacp 0 0 lcid lcid system get system defaultlcid installation or altered by user in control panel winxp lcid lcid user get user defaultlcid installation or altered by user in control panel winxp get the ansi codepage which is to be used for all non unicode conversions langid lid system langidfromlcid lcid system get user s sorting preferences uint u sort id user sortidfromlcid lcid user uint u sort ver user sortversionfromlcid lcid user we can t use the same sorting paramters for 2 different languages uint u sort id user sort default uint u sort ver user 0 create a thread locale which gives full backward compability for users which had run ansi emule on a system where the system s code page did not match the user s language lcid lcid makesortlcid lid system u sort id user u sort ver user lcid lcid thread get thread locale if lcid thread lcid trace setting thread locale 0x 08x n lcid set thread locale lcid if we set the thread locale see comments above we also have to specify the proper codepage for the c rtl otherwise we may not be able to store some strings as mbcs unicode mbcs conversion may fail set rtl locale lcid cpreferences initthreadlocale m_wlanguageid theapp getprofileint _t emule _t setlanguageacp lciduser getuserdefaultlcid lidsystem m_wlanguageid usortiduser lciduser usortveruser lciduser usortiduser sort_default usortveruser lidsystem usortiduser usortveruser setthreadlocale setrtllocale theapp getprofileint _t emule _t setsystemacp lcidsystem getsystemdefaultlcid lciduser getuserdefaultlcid lidsystem lcidsystem usortiduser lciduser usortveruser lciduser usortiduser sort_default usortveruser lidsystem usortiduser usortveruser lcidthread getthreadlocale lcidthread setthreadlocale setrtllocale void c preferences set rtl locale lcid lcid const s language p langs alanguages while p langs lid if p langs lid langidfromlcid lcid if p langs u codepage c string str codepage str codepage format t u p langs u codepage tsetlocale lc ctype str codepage break p langs cpreferences setrtllocale slanguage plangs _alanguages plangs plangs plangs ucodepage cstring strcodepage strcodepage _t plangs ucodepage _tsetlocale lc_ctype strcodepage plangs c string c preferences get html charset assert m wlanguageid 0 lpctstr psz html charset null const s language p langs alanguages while p langs lid if p langs lid m wlanguageid psz html charset p langs psz html charset break p langs if psz html charset null psz html charset 0 t 0 assert 0 should never come here try to get charset from codepage lpctstr psz lc locale tsetlocale lc ctype null if psz lc locale tchar sz localeid 128 uint u codepage 0 if stscanf psz lc locale t a za z u sz localeid u codepage 2 u codepage 0 c string str html codepage str html codepage format t windows u u codepage return str html codepage return psz html charset cstring cpreferences gethtmlcharset m_wlanguageid pszhtmlcharset slanguage plangs _alanguages plangs plangs m_wlanguageid pszhtmlcharset plangs pszhtmlcharset plangs pszhtmlcharset pszhtmlcharset _t pszlclocale _tsetlocale lc_ctype pszlclocale szlocaleid ucodepage _stscanf pszlclocale _t z_ szlocaleid ucodepage ucodepage cstring strhtmlcodepage strhtmlcodepage _t ucodepage strhtmlcodepage pszhtmlcharset static void add2 down session completed files ses down completed files static void add2 session transfer data uint u clientid uint u client port bool b frompf bool b up down uint32 bytes bool sent to friend false static void add2 down successful sessions ses down successful sessions cum down successful sessions add2downsessioncompletedfiles sesdowncompletedfiles add2sessiontransferdata uclientid uclientport bfrompf bupdown senttofriend add2downsuccessfulsessions sesdownsuccessfulsessions cumdownsuccessfulsessions static void add2 down successful sessions ses down successful sessions cum down successful sessions static void add2 down failed sessions ses down failed sessions cum down failed sessions add2downsuccessfulsessions sesdownsuccessfulsessions cumdownsuccessfulsessions add2downfailedsessions sesdownfailedsessions cumdownfailedsessions cumulative client breakdown stats for sent bytes static uint64 get up total client data return getcumupdata edonkey getcumupdata edonkeyhybrid getcumupdata emule getcumupdata mldonkey getcumupdata amule getcumupdata emulecompat getuptotalclientdata getcumupdata_edonkey getcumupdata_edonkeyhybrid getcumupdata_emule getcumupdata_mldonkey getcumupdata_amule getcumupdata_emulecompat session client breakdown stats for sent bytes static uint64 get up session client data return sesupdata edonkey sesupdata edonkeyhybrid sesupdata emule sesupdata mldonkey sesupdata amule sesupdata emulecompat getupsessionclientdata sesupdata_edonkey sesupdata_edonkeyhybrid sesupdata_emule sesupdata_mldonkey sesupdata_amule sesupdata_emulecompat cumulative port breakdown stats for sent bytes static uint64 get up total port data return getcumupdataport 4662 getcumupdataport other getuptotalportdata getcumupdataport_4662 getcumupdataport_other session port breakdown stats for sent bytes static uint64 get up session port data return sesupdataport 4662 sesupdataport other getupsessionportdata sesupdataport_4662 sesupdataport_other cumulative client breakdown stats for received bytes static uint64 get down total client data return getcumdowndata edonkey getcumdowndata edonkeyhybrid getcumdowndata emule getcumdowndata mldonkey getcumdowndata amule getcumdowndata emulecompat getcumdowndata shareaza getdowntotalclientdata getcumdowndata_edonkey getcumdowndata_edonkeyhybrid getcumdowndata_emule getcumdowndata_mldonkey getcumdowndata_amule getcumdowndata_emulecompat getcumdowndata_shareaza session client breakdown stats for received bytes static uint64 get down session client data return sesdowndata edonkey sesdowndata edonkeyhybrid sesdowndata emule sesdowndata mldonkey sesdowndata amule sesdowndata emulecompat sesdowndata shareaza getdownsessionclientdata sesdowndata_edonkey sesdowndata_edonkeyhybrid sesdowndata_emule sesdowndata_mldonkey sesdowndata_amule sesdowndata_emulecompat sesdowndata_shareaza cumulative port breakdown stats for received bytes static uint64 get down total port data return getcumdowndataport 4662 getcumdowndataport other getdowntotalportdata getcumdowndataport_4662 getcumdowndataport_other session port breakdown stats for received bytes static uint64 get down session data port return sesdowndataport 4662 sesdowndataport other getdownsessiondataport sesdowndataport_4662 sesdowndataport_other check to see if the column is hidden bool is column hidden int i column const if i column 1 i column m icolumnstracked return false return m acolumns i column b hidden iscolumnhidden icolumn icolumn icolumn m_icolumnstracked m_acolumns icolumn bhidden get the correct column width even if column is hidden int get column width int i column const if i column 0 i column m icolumnstracked return 0 if m acolumns i column b hidden return m acolumns i column i width else return c list ctrl get column width i column getcolumnwidth icolumn icolumn icolumn m_icolumnstracked m_acolumns icolumn bhidden m_acolumns icolumn iwidth clistctrl getcolumnwidth icolumn call set redraw to allow changes to be redrawn or to prevent changes from being redrawn void set redraw bool b redraw true if b redraw if m iredrawcount 0 m iredrawcount 0 c list ctrl set redraw true else if m iredrawcount 0 c list ctrl set redraw false setredraw setredraw bredraw bredraw m_iredrawcount m_iredrawcount clistctrl setredraw m_iredrawcount clistctrl setredraw places a sort arrow in a column void set sort arrow int i column bool b ascending set sort arrow i column b ascending arrow up arrow down setsortarrow icolumn bascending setsortarrow icolumn bascending arrowup arrowdown int get hidden column count const int i hidden 0 for int i 0 i m icolumnstracked i if m acolumns i b hidden i hidden return i hidden gethiddencolumncount ihidden m_icolumnstracked m_acolumns bhidden ihidden ihidden c mule list ctrl c mule list ctrl pfnlvcompare pfn compare dword dw param sort m sortproc pfn compare m dwparamsort dw param sort m bcustomdraw false m icurrentsortitem 1 m icolumnstracked 0 m acolumns null m iredrawcount 0 just in case m crwindow 0 m crwindowtext 0 m crwindowtextbk m crwindow m crhighlight 0 m crhighlighttext m crwindowtext m crglow 0 m crfocusline 0 m crnohighlight 0 m crnofocusline 0 m bgeneralpurposefind false m bcansearchinallcolumns false m bfindmatchcase false m ifinddirection 1 m ifindcolumn 0 m haccel null m uidaccel idr listview cmulelistctrl cmulelistctrl pfncompare dwparamsort m_sortproc pfncompare m_dwparamsort dwparamsort m_bcustomdraw m_icurrentsortitem m_icolumnstracked m_acolumns m_iredrawcount m_crwindow m_crwindowtext m_crwindowtextbk m_crwindow m_crhighlight m_crhighlighttext m_crwindowtext m_crglow m_crfocusline m_crnohighlight m_crnofocusline m_bgeneralpurposefind m_bcansearchinallcolumns m_bfindmatchcase m_ifinddirection m_ifindcolumn m_haccel m_uidaccel idr_listview c mule list ctrl c mule list ctrl delete m acolumns cmulelistctrl cmulelistctrl m_acolumns int c mule list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort return 0 cmulelistctrl sortproc lparam1 lparam2 lparamsort void c mule list ctrl set name lpctstr lpsz name m name lpsz name cmulelistctrl setname lpszname m_name lpszname void c mule list ctrl save settings assert m name is empty if m name is empty return c ini ini the prefs get config file t list control setup show window sw hide int pi sort hist new int max sortorderhistory int i 0 position pos1 pos2 for pos1 m lisorthistory get head position pos2 pos1 null m lisorthistory get next pos1 pi sort hist i m lisorthistory get at pos2 1 ini ser get false pi sort hist i m name t sort history store additional settings ini write int m name t table sort item get sort item ini write int m name t table sort ascending get sort type m atsortarrow int pi col widths new int m icolumnstracked int pi col hidden new int m icolumnstracked int pi col orders new int m icolumnstracked for i 0 i m icolumnstracked i pi col widths i get column width i pi col hidden i is column hidden i show column i get header ctrl get order array pi col orders m icolumnstracked ini ser get false pi col widths m icolumnstracked m name t column widths ini ser get false pi col hidden m icolumnstracked m name t column hidden ini ser get false pi col orders m icolumnstracked m name t column orders for i 0 i m icolumnstracked i if pi col hidden i 1 hide column i show window sw show delete pi sort hist delete pi col orders delete pi col widths delete pi col hidden cmulelistctrl savesettings m_name isempty m_name isempty cini theprefs getconfigfile _t listcontrolsetup showwindow sw_hide pisorthist max_sortorderhistory m_lisorthistory getheadposition m_lisorthistory getnext pisorthist m_lisorthistory getat serget pisorthist m_name _t sorthistory writeint m_name _t tablesortitem getsortitem writeint m_name _t tablesortascending getsorttype m_atsortarrow picolwidths m_icolumnstracked picolhidden m_icolumnstracked picolorders m_icolumnstracked m_icolumnstracked picolwidths getcolumnwidth picolhidden iscolumnhidden showcolumn getheaderctrl getorderarray picolorders m_icolumnstracked serget picolwidths m_icolumnstracked m_name _t columnwidths serget picolhidden m_icolumnstracked m_name _t columnhidden serget picolorders m_icolumnstracked m_name _t columnorders m_icolumnstracked picolhidden hidecolumn showwindow sw_show pisorthist picolorders picolwidths picolhidden void c mule list ctrl load settings assert m name is empty if m name is empty return c ini ini the prefs get config file t list control setup c header ctrl p header ctrl get header ctrl sort history int pi sort hist new int max sortorderhistory ini ser get true pi sort hist max sortorderhistory m name t sort history m lisorthistory remove all for int i 0 i max sortorderhistory i if pi sort hist i 0 m lisorthistory add tail pi sort hist i 1 else break m icurrentsortitem ini get int m name t table sort item 0 m atsortarrow get arrow type ini get int m name t table sort ascending arrow up if m lisorthistory is empty m lisorthistory add tail m icurrentsortitem columns settings int pi col widths new int m icolumnstracked int pi col hidden new int m icolumnstracked int pi col orders new int m icolumnstracked ini ser get true pi col widths m icolumnstracked m name t column widths ini ser get true pi col hidden m icolumnstracked m name t column hidden ini ser get true pi col orders m icolumnstracked m name t column orders apply columnwidths and verify sortorder int pi array new int m icolumnstracked for int i 0 i m icolumnstracked i pi array i i if pi col widths i 2 don t allow column widths of 0 and 1 just because it looks very confusing in gui set column width i pi col widths i int i order pi col orders i if i 0 i order 0 i order m icolumnstracked i order i pi array i i order m acolumns i i location pi array i pi array 0 0 for int i 0 i m icolumnstracked i m acolumns pi array i i location i p header ctrl set order array m icolumnstracked pi array for int i 1 i m icolumnstracked i if pi col hidden i hide column i delete pi array delete pi col orders delete pi col widths delete pi col hidden delete pi sort hist cmulelistctrl loadsettings m_name isempty m_name isempty cini theprefs getconfigfile _t listcontrolsetup cheaderctrl pheaderctrl getheaderctrl pisorthist max_sortorderhistory serget pisorthist max_sortorderhistory m_name _t sorthistory m_lisorthistory removeall max_sortorderhistory pisorthist m_lisorthistory addtail pisorthist m_icurrentsortitem getint m_name _t tablesortitem m_atsortarrow getarrowtype getint m_name _t tablesortascending arrowup m_lisorthistory isempty m_lisorthistory addtail m_icurrentsortitem picolwidths m_icolumnstracked picolhidden m_icolumnstracked picolorders m_icolumnstracked serget picolwidths m_icolumnstracked m_name _t columnwidths serget picolhidden m_icolumnstracked m_name _t columnhidden serget picolorders m_icolumnstracked m_name _t columnorders piarray m_icolumnstracked m_icolumnstracked piarray picolwidths setcolumnwidth picolwidths iorder picolorders iorder iorder m_icolumnstracked iorder piarray iorder m_acolumns ilocation piarray piarray m_icolumnstracked m_acolumns piarray ilocation pheaderctrl setorderarray m_icolumnstracked piarray m_icolumnstracked picolhidden hidecolumn piarray picolorders picolwidths picolhidden pisorthist void c mule list ctrl hide column int i column c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count if i column 1 i column i count m acolumns i column b hidden return stop it from redrawing set redraw false shrink width to 0 hditem item item mask hdi width p header ctrl get item i column item m acolumns i column i width item cxy item cxy 0 p header ctrl set item i column item move to front of list int pi array new int m icolumnstracked p header ctrl get order array pi array m icolumnstracked int i from m acolumns i column i location for int i 0 i m icolumnstracked i if m acolumns i i location m acolumns i column i location m acolumns i b hidden i from for int i i from i 0 i pi array i pi array i 1 pi array 0 i column p header ctrl set order array m icolumnstracked pi array delete pi array update entry m acolumns i column b hidden true redraw set redraw true invalidate false cmulelistctrl hidecolumn icolumn cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount icolumn icolumn icount m_acolumns icolumn bhidden setredraw hdi_width pheaderctrl getitem icolumn m_acolumns icolumn iwidth pheaderctrl setitem icolumn piarray m_icolumnstracked pheaderctrl getorderarray piarray m_icolumnstracked ifrom m_acolumns icolumn ilocation m_icolumnstracked m_acolumns ilocation m_acolumns icolumn ilocation m_acolumns bhidden ifrom ifrom piarray piarray piarray icolumn pheaderctrl setorderarray m_icolumnstracked piarray piarray m_acolumns icolumn bhidden setredraw void c mule list ctrl show column int i column c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count if i column 1 i column i count m acolumns i column b hidden return stop it from redrawing set redraw false restore position in list int pi array new int m icolumnstracked p header ctrl get order array pi array m icolumnstracked int i current index to order p header ctrl i column for i current index to order p header ctrl 0 i current m icolumnstracked 1 i current pi array i current pi array i current 1 for m acolumns i column i location m acolumns p header ctrl order to index i current 1 i location i current m icolumnstracked 1 i current pi array i current pi array i current 1 pi array i current i column p header ctrl set order array m icolumnstracked pi array delete pi array and then restore original width hditem item item mask hdi width item cxy m acolumns i column i width p header ctrl set item i column item update entry m acolumns i column b hidden false redraw set redraw true invalidate false cmulelistctrl showcolumn icolumn cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount icolumn icolumn icount m_acolumns icolumn bhidden setredraw piarray m_icolumnstracked pheaderctrl getorderarray piarray m_icolumnstracked icurrent indextoorder pheaderctrl icolumn icurrent indextoorder pheaderctrl icurrent m_icolumnstracked icurrent piarray icurrent piarray icurrent m_acolumns icolumn ilocation m_acolumns pheaderctrl ordertoindex icurrent ilocation icurrent m_icolumnstracked icurrent piarray icurrent piarray icurrent piarray icurrent icolumn pheaderctrl setorderarray m_icolumnstracked piarray piarray hdi_width m_acolumns icolumn iwidth pheaderctrl setitem icolumn m_acolumns icolumn bhidden setredraw int c mule list ctrl get sort type arrow type at switch at case arrow down return 0 case arrow up return 1 case arrow double down return 2 case arrow double up return 3 return 0 cmulelistctrl getsorttype arrowtype arrowdown arrowup arrowdoubledown arrowdoubleup c mule list ctrl arrow type c mule list ctrl get arrow type int iat switch iat case 0 return arrow down case 1 return arrow up case 2 return arrow double down case 3 return arrow double up return arrow down cmulelistctrl arrowtype cmulelistctrl getarrowtype arrowdown arrowup arrowdoubledown arrowdoubleup arrowdown void c mule list ctrl set sort arrow int i column arrow type at type hditem header item header item mask hdi format c header ctrl p header ctrl get header ctrl if i column m icurrentsortitem p header ctrl get item m icurrentsortitem header item header item fmt hdf image hdf bitmap on right p header ctrl set item m icurrentsortitem header item m icurrentsortitem i column m imlheaderctrl delete image list place new arrow unless we were given an invalid column if i column 0 p header ctrl get item i column header item m atsortarrow at type hinstance h inst res afx find resource handle makeintresource m atsortarrow rt bitmap if h inst res null hbitmap hbm sort states hbitmap load image h inst res makeintresource m atsortarrow image bitmap 0 0 lr createdibsection lr loadmap3dcolors if hbm sort states null c bitmap bm sort states bm sort states attach hbm sort states c image list iml sort states if iml sort states create 14 14 the app m idfltimagelistcolorflags ilc mask 1 0 verify iml sort states add bm sort states rgb 255 0 255 1 to avoid drawing problems which occure only with an image list with a mask while resizing list view columns which have the header control bitmap right aligned set the background color of the image list if the app m ullcomctrlver makedllverull 6 0 0 0 iml sort states set bk color get sys color color btnface when setting the image list for the header control for the first time we ll get the image list of the listview control so better store the header control imagelist separate void p header ctrl set image list iml sort states m imlheaderctrl delete image list m imlheaderctrl attach iml sort states detach use smaller bitmap margins this saves some pixels which may be required for rather small column titles if the app m ullcomctrlver makedllverull 5 8 0 0 int i bmp margin p header ctrl get bitmap margin int i new bmp margin get system metrics sm cxedge get system metrics sm cxedge 2 if i new bmp margin i bmp margin p header ctrl set bitmap margin i new bmp margin header item mask hdi image header item fmt hdf image hdf bitmap on right header item i image 0 p header ctrl set item i column header item cmulelistctrl setsortarrow icolumn arrowtype attype headeritem headeritem hdi_format cheaderctrl pheaderctrl getheaderctrl icolumn m_icurrentsortitem pheaderctrl getitem m_icurrentsortitem headeritem headeritem hdf_image hdf_bitmap_on_right pheaderctrl setitem m_icurrentsortitem headeritem m_icurrentsortitem icolumn m_imlheaderctrl deleteimagelist icolumn pheaderctrl getitem icolumn headeritem m_atsortarrow attype hinstres afxfindresourcehandle m_atsortarrow rt_bitmap hinstres hbmsortstates loadimage hinstres m_atsortarrow image_bitmap lr_createdibsection lr_loadmap3dcolors hbmsortstates cbitmap bmsortstates bmsortstates hbmsortstates cimagelist imlsortstates imlsortstates theapp m_idfltimagelistcolorflags ilc_mask imlsortstates bmsortstates theapp m_ullcomctrlver imlsortstates setbkcolor getsyscolor color_btnface pheaderctrl setimagelist imlsortstates m_imlheaderctrl deleteimagelist m_imlheaderctrl imlsortstates theapp m_ullcomctrlver ibmpmargin pheaderctrl getbitmapmargin inewbmpmargin getsystemmetrics sm_cxedge getsystemmetrics sm_cxedge inewbmpmargin ibmpmargin pheaderctrl setbitmapmargin inewbmpmargin headeritem hdi_image headeritem hdf_image hdf_bitmap_on_right headeritem iimage pheaderctrl setitem icolumn headeritem himagelist c mule list ctrl apply image list himagelist himl himagelist himl old himagelist send message lvm setimagelist lvsil small lparam himl if m imlheaderctrl m himagelist null must again set the image list for the header control because lvm setimagelist always resets any already specified header control image lists get header ctrl set image list m imlheaderctrl return himl old cmulelistctrl applyimagelist himlold sendmessage lvm_setimagelist lvsil_small m_imlheaderctrl m_himagelist lvm_setimagelist getheaderctrl setimagelist m_imlheaderctrl himlold void c mule list ctrl do find int i start item int i direction 1 down 0 up bool b show error c wait cursor cur hourglass if i start item 0 message beep mb ok return int i num items i direction get item count 0 int i item i start item while i direction i item i num items i item 0 c string str item text get item text i item m ifindcolumn if str item text is empty if m bfindmatchcase tcsstr str item text m strfindtext null stristr str item text m strfindtext null deselect all listview entries set item state 1 0 lvis selected select the found listview entry set item state i item lvis selected lvis focused lvis selected lvis focused set selection mark i item ensure visible i item false b partialok set focus return if i direction i item else i item if b show error afx message box get res string ids search noresult mb iconinformation else message beep mb ok cmulelistctrl dofind istartitem idirection bshowerror cwaitcursor curhourglass istartitem messagebeep mb_ok inumitems idirection getitemcount iitem istartitem idirection iitem inumitems iitem cstring stritemtext getitemtext iitem m_ifindcolumn stritemtext isempty m_bfindmatchcase _tcsstr stritemtext m_strfindtext stritemtext m_strfindtext setitemstate lvis_selected setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark iitem ensurevisible iitem bpartialok setfocus idirection iitem iitem bshowerror afxmessagebox getresstring ids_search_noresult mb_iconinformation messagebeep mb_ok void c mule list ctrl do find next bool b show error int i start item get next item 1 lvni selected lvni focused if i start item 1 i start item 0 else i start item i start item m ifinddirection 1 1 do find i start item m ifinddirection b show error cmulelistctrl dofindnext bshowerror istartitem getnextitem lvni_selected lvni_focused istartitem istartitem istartitem istartitem m_ifinddirection dofind istartitem m_ifinddirection bshowerror void c mule list ctrl auto select item int i item get next item 1 lvis selected lvis focused if i item 1 i item get next item 1 lvis focused if i item 1 set item state i item lvis selected lvis selected set selection mark i item cmulelistctrl autoselectitem iitem getnextitem lvis_selected lvis_focused iitem iitem getnextitem lvis_focused iitem setitemstate iitem lvis_selected lvis_selected setselectionmark iitem int c mule list ctrl get next sort order int dw current sort order const position pos1 pos2 for pos1 m lisorthistory get head position pos2 pos1 null m lisorthistory get next pos1 if m lisorthistory get at pos2 dw current sort order if pos1 null return 1 there is no further sortorder stored else return m lisorthistory get at pos1 current one not found shouldn t happen assert false return 1 cmulelistctrl getnextsortorder dwcurrentsortorder m_lisorthistory getheadposition m_lisorthistory getnext m_lisorthistory getat dwcurrentsortorder m_lisorthistory getat void c mule list ctrl update sort history int dw new order int dw inverse value int dw inverse dw new order dw inverse value dw new order dw inverse value dw new order dw inverse value delete the value or its inverse sorting value if it appears already in the list position pos1 pos2 for pos1 m lisorthistory get head position pos2 pos1 null m lisorthistory get next pos1 if m lisorthistory get at pos2 dw new order m lisorthistory get at pos2 dw inverse m lisorthistory remove at pos2 m lisorthistory add head dw new order limit it to max sortorderhistory entries for now just for performance if m lisorthistory get size max sortorderhistory m lisorthistory remove tail cmulelistctrl updatesorthistory dwneworder dwinversevalue dwinverse dwneworder dwinversevalue dwneworder dwinversevalue dwneworder dwinversevalue m_lisorthistory getheadposition m_lisorthistory getnext m_lisorthistory getat dwneworder m_lisorthistory getat dwinverse m_lisorthistory removeat m_lisorthistory addhead dwneworder max_sortorderhistory m_lisorthistory getsize max_sortorderhistory m_lisorthistory removetail void c mule list ctrl pre subclass window set colors c list ctrl pre subclass window send message ccm setunicodeformat true modify style lvs singlesel lvs list lvs icon lvs smallicon lvs report lvs singlesel lvs report set extended style lvs ex headerdragdrop if we want to handle the vk return key we have to do that via accelerators if m uidaccel uint 1 m haccel load accelerators afx get resource handle makeintresource m uidaccel assert m haccel cmulelistctrl presubclasswindow setcolors clistctrl presubclasswindow sendmessage ccm_setunicodeformat modifystyle lvs_singlesel lvs_list lvs_icon lvs_smallicon lvs_report lvs_singlesel lvs_report setextendedstyle lvs_ex_headerdragdrop vk_return m_uidaccel m_haccel loadaccelerators afxgetresourcehandle m_uidaccel m_haccel bool c mule list ctrl on child notify uint message wparam w param lparam l param lresult p result if message wm drawitem catch the prepaint and copy struct if message wm notify nmhdr l param code nm customdraw lpnmlvcustomdraw l param nmcd dw draw stage cdds itemprepaint m bcustomdraw c list ctrl on child notify message w param l param p result if m bcustomdraw m lvcd lpnmlvcustomdraw l param return m bcustomdraw return c list ctrl on child notify message w param l param p result assert p result null no return value expected unused p result unused in release builds draw item lpdrawitemstruct l param return true cmulelistctrl onchildnotify wparam lparam presult wm_drawitem wm_notify lparam nm_customdraw lparam dwdrawstage cdds_itemprepaint m_bcustomdraw clistctrl onchildnotify wparam lparam presult m_bcustomdraw m_lvcd lparam m_bcustomdraw clistctrl onchildnotify wparam lparam presult presult presult drawitem lparam bool c mule list ctrl pre translate message msg p msg if p msg message wm syskeydown p msg w param vk return get async key state vk menu 0 post message wm command mpg altenter 0 return true if m haccel null if p msg message wm keyfirst p msg message wm keylast if we want to handle the vk return key we have to do that via accelerators if translate accelerator m hwnd m haccel p msg return true catch the ctrl numpad plus key shortcut c mule list ctrl can not handle this if p msg message wm keydown p msg w param vk add get async key state vk control 0 return true return c list ctrl pre translate message p msg cmulelistctrl pretranslatemessage pmsg pmsg wm_syskeydown pmsg wparam vk_return getasynckeystate vk_menu postmessage wm_command mpg_altenter m_haccel pmsg wm_keyfirst pmsg wm_keylast vk_return translateaccelerator m_hwnd m_haccel pmsg numpad_plus_key cmulelistctrl pmsg wm_keydown pmsg wparam vk_add getasynckeystate vk_control clistctrl pretranslatemessage pmsg void c mule list ctrl on key down uint n char uint n rep cnt uint n flags if n char a get async key state vk control 0 ctrl a select all items lv item the item the item mask lvif state the item i item 1 the item i sub item 0 the item state lvis selected the item state mask 2 set item state 1 the item else if n char vk delete post message wm command mpg delete 0 else if n char vk f2 post message wm command mpg f2 0 else if n char c get key state vk control 0x8000 ctrl c copy keycombo send message wm command mp copyselected if n char v get key state vk control 0x8000 ctrl v paste keycombo send message wm command mp paste else if m bgeneralpurposefind if n char f get key state vk control 0x8000 ctrl f search item on find start else if n char vk f3 if get key state vk shift 0x8000 shift f3 search previous on find prev else f3 search next on find next return c list ctrl on key down n char n rep cnt n flags cmulelistctrl onkeydown nchar nrepcnt nflags nchar getasynckeystate vk_control lv_item theitem theitem lvif_state theitem iitem theitem isubitem theitem lvis_selected theitem statemask setitemstate theitem nchar vk_delete postmessage wm_command mpg_delete nchar vk_f2 postmessage wm_command mpg_f2 nchar getkeystate vk_control sendmessage wm_command mp_copyselected nchar getkeystate vk_control sendmessage wm_command mp_paste m_bgeneralpurposefind nchar getkeystate vk_control onfindstart nchar vk_f3 getkeystate vk_shift onfindprev onfindnext clistctrl onkeydown nchar nrepcnt nflags void c mule list ctrl draw item lpdrawitemstruct lp draw item struct set up our flicker free drawing c rect rc item lp draw item struct rc item cdc odc cdc from handle lp draw item struct hdc colorref cr olddc bk color odc set bk color m crwindow c memdc pdc odc rc item c font p old font pdc select object get font int i offset pdc get text extent t 1 cx 2 int i item lp draw item struct itemid c image list p image list c header ctrl p header ctrl get header ctrl gets the item image and state info lv item lvi lvi mask lvif image lvif state lvi i item i item lvi i sub item 0 lvi state mask lvis drophilited lvis focused lvis selected lvis glow get item lvi see if the item be highlighted bool b highlight lvi state lvis drophilited lvi state lvis selected bool b ctrl focused get focus this get style lvs showselalways bool b glowing lvi state lvis glow colorref cr old text color if m bcustomdraw if b highlight cr old text color pdc set text color g blowcolordesktop m crhighlighttext m lvcd clr text else cr old text color pdc set text color m lvcd clr text else if b highlight cr old text color pdc set text color m crhighlighttext else cr old text color pdc set text color m crwindowtext if m crwindowtextbk clr none def window proc wm erasebkgnd wparam pdc m hdc 0 get rectangles for drawing c rect rc bounds rc label rc icon get item rect i item rc bounds lvir bounds get item rect i item rc label lvir label get item rect i item rc icon lvir icon c rect rc col rc bounds the label c string s label get item text i item 0 labels are offset by a certain amount this offset is related to the width of a space character c rect rc highlight c rect rc wnd should i check get extended style lvs ex fullrowselect rc highlight top rc bounds top rc highlight bottom rc bounds bottom rc highlight left rc bounds left 1 rc highlight right rc bounds right 1 colorref cr old bck color draw the background color if b highlight if b ctrl focused pdc fill rect rc highlight c brush m crhighlight cr old bck color pdc set bk color m crhighlight else if b glowing pdc fill rect rc highlight c brush m crglow cr old bck color pdc set bk color m crglow else pdc fill rect rc highlight c brush m crnohighlight cr old bck color pdc set bk color m crnohighlight else if b glowing pdc fill rect rc highlight c brush m crglow cr old bck color pdc set bk color m crglow else if m crwindowtextbk clr none pdc fill rect rc highlight c brush m crwindow was already done with wm erasebkgnd cr old bck color pdc set bk color m crwindow update column rc col right rc col left get column width 0 draw state icon if lvi state lvis stateimagemask int n image lvi state lvis stateimagemask 12 1 p image list get image list lvsil state if p image list colorref cr old p image list set bk color clr none p image list draw pdc n image rc col top left ild normal p image list set bk color cr old draw the item s icon p image list get image list lvsil small if p image list colorref cr old p image list set bk color clr none p image list draw pdc lvi i image rc icon top left ild normal p image list set bk color cr old int i old bk mode m crwindowtextbk clr none pdc set bk mode transparent opaque draw item label column 0 rc label left i offset 2 rc label right i offset pdc draw text s label 1 rc label mlc dt text dt left dt noclip draw labels for remaining columns lv column lvc lvc mask lvcf fmt lvcf width rc bounds right rc highlight right rc bounds right rc highlight right rc bounds right int i count p header ctrl get item count for int i current 1 i current i count i current int i column p header ctrl order to index i current don t draw column 0 again if i column 0 continue get column i column lvc don t draw anything with 0 width if lvc cx 0 continue rc col left rc col right rc col right lvc cx s label get item text i item i column if s label get length 0 continue get the text justification uint n justify dt left switch lvc fmt lvcfmt justifymask case lvcfmt right n justify dt right break case lvcfmt center n justify dt center break default break rc label rc col rc label left i offset rc label right i offset pdc draw text s label 1 rc label mlc dt text n justify draw focus rectangle if item has focus if lvi state lvis focused b ctrl focused lvi state lvis selected if b ctrl focused lvi state lvis selected pdc frame rect rc highlight c brush m crnofocusline else pdc frame rect rc highlight c brush m crfocusline pdc flush if m crwindowtextbk clr none pdc set bk mode i old bk mode pdc select object p old font pdc set text color cr old text color pdc set bk color cr old bck color odc set bk color cr olddc bk color cmulelistctrl drawitem lpdrawitemstruct crect rcitem lpdrawitemstruct rcitem fromhandle lpdrawitemstruct crolddcbkcolor setbkcolor m_crwindow cmemdc rcitem cfont poldfont selectobject getfont ioffset gettextextent _t iitem lpdrawitemstruct cimagelist pimagelist cheaderctrl pheaderctrl getheaderctrl lv_item lvif_image lvif_state iitem iitem isubitem statemask lvis_drophilited lvis_focused lvis_selected lvis_glow getitem bhighlight lvis_drophilited lvis_selected bctrlfocused getfocus getstyle lvs_showselalways bglowing lvis_glow croldtextcolor m_bcustomdraw bhighlight croldtextcolor settextcolor g_blowcolordesktop m_crhighlighttext m_lvcd clrtext croldtextcolor settextcolor m_lvcd clrtext bhighlight croldtextcolor settextcolor m_crhighlighttext croldtextcolor settextcolor m_crwindowtext m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd m_hdc crect rcbounds rclabel rcicon getitemrect iitem rcbounds lvir_bounds getitemrect iitem rclabel lvir_label getitemrect iitem rcicon lvir_icon crect rccol rcbounds cstring slabel getitemtext iitem crect rchighlight crect rcwnd getextendedstyle lvs_ex_fullrowselect rchighlight rcbounds rchighlight rcbounds rchighlight rcbounds rchighlight rcbounds croldbckcolor bhighlight bctrlfocused fillrect rchighlight cbrush m_crhighlight croldbckcolor setbkcolor m_crhighlight bglowing fillrect rchighlight cbrush m_crglow croldbckcolor setbkcolor m_crglow fillrect rchighlight cbrush m_crnohighlight croldbckcolor setbkcolor m_crnohighlight bglowing fillrect rchighlight cbrush m_crglow croldbckcolor setbkcolor m_crglow m_crwindowtextbk clr_none fillrect rchighlight cbrush m_crwindow wm_erasebkgnd croldbckcolor setbkcolor m_crwindow rccol rccol getcolumnwidth lvis_stateimagemask nimage lvis_stateimagemask pimagelist getimagelist lvsil_state pimagelist crold pimagelist setbkcolor clr_none pimagelist nimage rccol topleft ild_normal pimagelist setbkcolor crold pimagelist getimagelist lvsil_small pimagelist crold pimagelist setbkcolor clr_none pimagelist iimage rcicon topleft ild_normal pimagelist setbkcolor crold ioldbkmode m_crwindowtextbk clr_none setbkmode rclabel ioffset rclabel ioffset drawtext slabel rclabel mlc_dt_text dt_left dt_noclip lv_column lvcf_fmt lvcf_width rcbounds rchighlight rcbounds rchighlight rcbounds icount pheaderctrl getitemcount icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent icolumn getcolumn icolumn rccol rccol rccol slabel getitemtext iitem icolumn slabel getlength njustify dt_left lvcfmt_justifymask lvcfmt_right njustify dt_right lvcfmt_center njustify dt_center rclabel rccol rclabel ioffset rclabel ioffset drawtext slabel rclabel mlc_dt_text njustify lvis_focused bctrlfocused lvis_selected bctrlfocused lvis_selected framerect rchighlight cbrush m_crnofocusline framerect rchighlight cbrush m_crfocusline m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor setbkcolor croldbckcolor setbkcolor crolddcbkcolor bool c mule list ctrl on erase bkgnd cdc pdc if m crwindowtextbk clr none this creates a lot screen flickering return c list ctrl on erase bkgnd pdc int item count get item count if item count return c list ctrl on erase bkgnd pdc rect client rect rect item rect int top index get top index int max items get count per page int drawn items item count max items item count max items c rect rc clip draw top portion get client rect client rect rc clip client rect get item rect top index item rect lvir bounds client rect bottom item rect top if m crwindowtextbk clr none pdc fill solid rect client rect get bk color else rc clip top item rect top draw bottom portion if we have to if top index max items item count get client rect client rect get item rect top index drawn items 1 item rect lvir bounds client rect top item rect bottom rc clip bottom item rect bottom if m crwindowtextbk clr none pdc fill solid rect client rect get bk color draw right half if we need to if item rect right client rect right get client rect client rect client rect left item rect right rc clip right item rect right if m crwindowtextbk clr none pdc fill solid rect client rect get bk color if m crwindowtextbk clr none c rect rc clip box pdc get clip box rc clip box rc clip box subtract rect rc clip box rc clip if rc clip box is rect empty pdc exclude clip rect rc clip c list ctrl on erase bkgnd pdc invalidate rect rc clip false return true cmulelistctrl onerasebkgnd m_crwindowtextbk clr_none clistctrl onerasebkgnd itemcount getitemcount itemcount clistctrl onerasebkgnd clientrect itemrect topindex gettopindex maxitems getcountperpage drawnitems itemcount maxitems itemcount maxitems crect rcclip getclientrect clientrect rcclip clientrect getitemrect topindex itemrect lvir_bounds clientrect itemrect m_crwindowtextbk clr_none fillsolidrect clientrect getbkcolor rcclip itemrect topindex maxitems itemcount getclientrect clientrect getitemrect topindex drawnitems itemrect lvir_bounds clientrect itemrect rcclip itemrect m_crwindowtextbk clr_none fillsolidrect clientrect getbkcolor itemrect clientrect getclientrect clientrect clientrect itemrect rcclip itemrect m_crwindowtextbk clr_none fillsolidrect clientrect getbkcolor m_crwindowtextbk clr_none crect rcclipbox getclipbox rcclipbox rcclipbox subtractrect rcclipbox rcclip rcclipbox isrectempty excludecliprect rcclip clistctrl onerasebkgnd invalidaterect rcclip void c mule list ctrl on sys color change adjust colors c list ctrl on sys color change set colors redraw the up down sort arrow if it s there if m icurrentsortitem 0 set sort arrow m icurrentsortitem arrow type m atsortarrow cmulelistctrl onsyscolorchange clistctrl onsyscolorchange setcolors m_icurrentsortitem setsortarrow m_icurrentsortitem arrowtype m_atsortarrow int c mule list ctrl update location int i item int i item count get item count if i item i item count i item 0 return i item bool not last i item 1 i item count bool not first i item 0 dword ptr dwp item data get item data i item if dwp item data null return i item if not first int i new index i item 1 position pos m params find index i new index int i result m sortproc dwp item data get param at pos i new index m dwparamsort if i result 0 position pos prev pos int i dist i new index 2 while i dist 1 for int i 0 i i dist i m params get prev pos prev if m sortproc dwp item data get param at pos prev i new index i dist m dwparamsort 0 i new index i new index i dist pos pos prev else pos prev pos i dist 2 while i new index 0 m params get prev pos if m sortproc dwp item data get param at pos i new index m dwparamsort 0 break move item i item i new index 1 return i new index 1 if not last int i new index i item 1 position pos m params find index i new index int i result m sortproc dwp item data get param at pos i new index m dwparamsort if i result 0 position pos next pos int i dist get item count i new index 2 while i dist 1 for int i 0 i i dist i m params get next pos next if m sortproc dwp item data get param at pos next i new index i dist m dwparamsort 0 i new index i new index i dist pos pos next else pos next pos i dist 2 while i new index i item count m params get next pos if m sortproc dwp item data get param at pos i new index m dwparamsort 0 break move item i item i new index return i new index return i item cmulelistctrl updatelocation iitem iitemcount getitemcount iitem iitemcount iitem iitem notlast iitem iitemcount notfirst iitem dword_ptr dwpitemdata getitemdata iitem dwpitemdata iitem notfirst inewindex iitem m_params findindex inewindex iresult m_sortproc dwpitemdata getparamat inewindex m_dwparamsort iresult posprev idist inewindex idist idist m_params getprev posprev m_sortproc dwpitemdata getparamat posprev inewindex idist m_dwparamsort inewindex inewindex idist posprev posprev idist inewindex m_params getprev m_sortproc dwpitemdata getparamat inewindex m_dwparamsort moveitem iitem inewindex inewindex notlast inewindex iitem m_params findindex inewindex iresult m_sortproc dwpitemdata getparamat inewindex m_dwparamsort iresult posnext idist getitemcount inewindex idist idist m_params getnext posnext m_sortproc dwpitemdata getparamat posnext inewindex idist m_dwparamsort inewindex inewindex idist posnext posnext idist inewindex iitemcount m_params getnext m_sortproc dwpitemdata getparamat inewindex m_dwparamsort moveitem iitem inewindex inewindex iitem int c mule list ctrl move item int i old index int i new index move item in list returns index of new item if i new index i old index i new index save substrings c simple array void a sub items dword style get style if style lvs ownerdata 0 tchar sz text 256 lvitem lvi lvi mask lvif text lvif norecompute lvi i item i old index for int i 1 i m icolumnstracked i lvi i sub item i lvi cch text max arrsize sz text lvi psz text sz text void pstr sub item null if get item lvi if lvi psz text lpstr textcallback pstr sub item lpstr textcallback else pstr sub item new c string lvi psz text a sub items add pstr sub item copy item lvitem lvi tchar sz text 256 lvi mask lvif text lvif state lvif param lvif indent lvif image lvif norecompute lvi state mask uint 1 lvi i item i old index lvi i sub item 0 lvi psz text sz text lvi cch text max sizeof sz text sizeof sz text 0 lvi i indent 0 if get item lvi 0 return 1 lvi i item i new index do the move set redraw false set item data i old index 0 should do this to be safe delete item i old index i new index insert item lvi set redraw true restore substrings if style lvs ownerdata 0 for int i 1 i m icolumnstracked i lvitem lvi lvi i sub item i void pstr sub item a sub items i 1 if pstr sub item null if pstr sub item lpstr textcallback lvi psz text lpstr textcallback else lvi psz text lptstr lpctstr c string pstr sub item def window proc lvm setitemtext i new index lparam lvi if pstr sub item lpstr textcallback delete c string pstr sub item return i new index cmulelistctrl moveitem ioldindex inewindex inewindex ioldindex inewindex csimplearray asubitems getstyle lvs_ownerdata sztext lvif_text lvif_norecompute iitem ioldindex m_icolumnstracked isubitem cchtextmax sztext psztext sztext pstrsubitem getitem psztext lpstr_textcallback pstrsubitem lpstr_textcallback pstrsubitem cstring psztext asubitems pstrsubitem sztext lvif_text lvif_state lvif_param lvif_indent lvif_image lvif_norecompute statemask iitem ioldindex isubitem psztext sztext cchtextmax sztext sztext iindent getitem iitem inewindex setredraw setitemdata ioldindex deleteitem ioldindex inewindex insertitem setredraw lvs_ownerdata m_icolumnstracked isubitem pstrsubitem asubitems pstrsubitem pstrsubitem lpstr_textcallback psztext lpstr_textcallback psztext cstring pstrsubitem defwindowproc lvm_setitemtext inewindex pstrsubitem lpstr_textcallback cstring pstrsubitem inewindex void c mule list ctrl set colors lpctstr psz lv key m crwindow get sys color color window m crwindowtext get sys color color windowtext m crwindowtextbk m crwindow colorref cr highlight get sys color color highlight c string str bk image lpctstr psz skin profile the prefs get skin profile if psz skin profile null psz skin profile 0 t 0 c string str key if psz lv key null psz lv key 0 t 0 str key psz lv key else if is kind of runtime class c server list ctrl str key t servers lv else if is kind of runtime class c search list ctrl str key t search results lv else if is kind of runtime class c download list ctrl str key t downloads lv else if is kind of runtime class c upload list ctrl str key t uploads lv else if is kind of runtime class c queue list ctrl str key t queued lv else if is kind of runtime class c client list ctrl str key t clients lv else if is kind of runtime class c friend list ctrl str key t friends lv else if is kind of runtime class c shared files ctrl str key t shared files lv else if is kind of runtime class c kad contact list ctrl str key t kad contacts lv else if is kind of runtime class c kad search list ctrl str key t kad actions lv else get window text str key if str key is empty str key t def lv if the app load skin color alt str key t bk t def lv bk m crwindow m crwindowtextbk m crwindow the app load skin color alt str key t fg t def lv fg m crwindowtext the app load skin color alt str key t hl t def lv hl cr highlight tchar sz color max path get private profile string t colors str key t bk img t sz color arrsize sz color psz skin profile if sz color 0 t 0 get private profile string t colors t def lv bk img t sz color arrsize sz color psz skin profile if sz color 0 t 0 str bk image sz color set bk color m crwindow set text bk color m crwindowtextbk set text color m crwindowtext lvbkimage lvimg 0 lvimg ul flags lvbkif source none set bk image lvimg if str bk image is empty expand any optional available environment strings tchar sz exp skin res max path if expand environment strings str bk image sz exp skin res arrsize sz exp skin res 0 str bk image sz exp skin res create absolute path to icon resource file tchar sz full res path max path if path is relative str bk image tchar sz skin res folder max path tcsncpy sz skin res folder psz skin profile arrsize sz skin res folder sz skin res folder arrsize sz skin res folder 1 t 0 path remove file spec sz skin res folder tmakepath sz full res path null sz skin res folder str bk image null else tcsncpy sz full res path str bk image arrsize sz full res path sz full res path arrsize sz full res path 1 t 0 c string str url t file str url sz full res path if set bk image const cast lptstr lpctstr str url false 0 0 if set bk image const cast lptstr lpctstr str url false 100 0 m crwindowtextbk clr none set text bk color m crwindowtextbk m crfocusline cr highlight if g blowcolordesktop m crnohighlight cr highlight m crnofocusline cr highlight m crhighlight cr highlight m crhighlighttext get sys color color highlighttext m crglow cr highlight else m crnohighlight mlc rgbblend cr highlight m crwindow 8 m crnofocusline mlc rgbblend cr highlight m crwindow 2 m crhighlight mlc rgbblend cr highlight m crwindow 4 m crhighlighttext m crwindowtext m crglow mlc rgbblend cr highlight m crwindow 3 cmulelistctrl setcolors pszlvkey m_crwindow getsyscolor color_window m_crwindowtext getsyscolor color_windowtext m_crwindowtextbk m_crwindow crhighlight getsyscolor color_highlight cstring strbkimage pszskinprofile theprefs getskinprofile pszskinprofile pszskinprofile _t cstring strkey pszlvkey pszlvkey _t strkey pszlvkey iskindof runtime_class cserverlistctrl strkey _t serverslv iskindof runtime_class csearchlistctrl strkey _t searchresultslv iskindof runtime_class cdownloadlistctrl strkey _t downloadslv iskindof runtime_class cuploadlistctrl strkey _t uploadslv iskindof runtime_class cqueuelistctrl strkey _t queuedlv iskindof runtime_class cclientlistctrl strkey _t clientslv iskindof runtime_class cfriendlistctrl strkey _t friendslv iskindof runtime_class csharedfilesctrl strkey _t sharedfileslv iskindof runtime_class ckadcontactlistctrl strkey _t kadcontactslv iskindof runtime_class ckadsearchlistctrl strkey _t kadactionslv getwindowtext strkey strkey isempty strkey _t deflv theapp loadskincoloralt strkey _t _t deflvbk m_crwindow m_crwindowtextbk m_crwindow theapp loadskincoloralt strkey _t _t deflvfg m_crwindowtext theapp loadskincoloralt strkey _t _t deflvhl crhighlight szcolor max_path getprivateprofilestring _t strkey _t bkimg _t szcolor szcolor pszskinprofile szcolor _t getprivateprofilestring _t _t deflvbkimg _t szcolor szcolor pszskinprofile szcolor _t strbkimage szcolor setbkcolor m_crwindow settextbkcolor m_crwindowtextbk settextcolor m_crwindowtext ulflags lvbkif_source_none setbkimage strbkimage isempty szexpskinres max_path expandenvironmentstrings strbkimage szexpskinres szexpskinres strbkimage szexpskinres szfullrespath max_path pathisrelative strbkimage szskinresfolder max_path _tcsncpy szskinresfolder pszskinprofile szskinresfolder szskinresfolder szskinresfolder _t pathremovefilespec szskinresfolder _tmakepath szfullrespath szskinresfolder strbkimage _tcsncpy szfullrespath strbkimage szfullrespath szfullrespath szfullrespath _t cstring strurl _t strurl szfullrespath setbkimage const_cast strurl setbkimage const_cast strurl m_crwindowtextbk clr_none settextbkcolor m_crwindowtextbk m_crfocusline crhighlight g_blowcolordesktop m_crnohighlight crhighlight m_crnofocusline crhighlight m_crhighlight crhighlight m_crhighlighttext getsyscolor color_highlighttext m_crglow crhighlight m_crnohighlight mlc_rgbblend crhighlight m_crwindow m_crnofocusline mlc_rgbblend crhighlight m_crwindow m_crhighlight mlc_rgbblend crhighlight m_crwindow m_crhighlighttext m_crwindowtext m_crglow mlc_rgbblend crhighlight m_crwindow void c mule list ctrl on find start if get item count 0 message beep mb ok return c list view search dlg dlg dlg m plistview this dlg m strfindtext m strfindtext dlg m bcansearchinallcolumns m bcansearchinallcolumns dlg m isearchcolumn m ifindcolumn if dlg do modal idok dlg m strfindtext is empty return m strfindtext dlg m strfindtext m ifindcolumn dlg m isearchcolumn do find next true b show error cmulelistctrl onfindstart getitemcount messagebeep mb_ok clistviewsearchdlg m_plistview m_strfindtext m_strfindtext m_bcansearchinallcolumns m_bcansearchinallcolumns m_isearchcolumn m_ifindcolumn domodal m_strfindtext isempty m_strfindtext m_strfindtext m_ifindcolumn m_isearchcolumn dofindnext bshowerror void c mule list ctrl on find next if get item count 0 message beep mb ok return do find next false b show error cmulelistctrl onfindnext getitemcount messagebeep mb_ok dofindnext bshowerror void c mule list ctrl on find prev if get item count 0 message beep mb ok return int i start item get next item 1 lvni selected lvni focused if i start item 1 i start item 0 else i start item i start item m ifinddirection 1 1 do find i start item m ifinddirection false b show error cmulelistctrl onfindprev getitemcount messagebeep mb_ok istartitem getnextitem lvni_selected lvni_focused istartitem istartitem istartitem istartitem m_ifinddirection dofind istartitem m_ifinddirection bshowerror int c mule list ctrl index to order c header ctrl p header int i index int i count p header get item count int pi array new int i count header getorderarray p header m hwnd i count pi array for int i 0 i i count i if pi array i i index delete pi array return i delete pi array return 1 cmulelistctrl indextoorder cheaderctrl pheader iindex icount pheader getitemcount piarray icount header_getorderarray pheader m_hwnd icount piarray icount piarray iindex piarray piarray c object c list ctrl item walk get next selectable item assert m plistctrl null if m plistctrl null return null int i item count m plistctrl get item count if i item count 2 position pos m plistctrl get first selected item position if pos int i item m plistctrl get next selected item pos if i item 1 i item count m plistctrl set item state i item 0 lvis selected lvis focused i item m plistctrl set item state i item lvis selected lvis focused lvis selected lvis focused m plistctrl set selection mark i item m plistctrl ensure visible i item false return static downcast c object c object m plistctrl get item data i item return null cobject clistctrlitemwalk getnextselectableitem m_plistctrl m_plistctrl iitemcount m_plistctrl getitemcount iitemcount m_plistctrl getfirstselecteditemposition iitem m_plistctrl getnextselecteditem iitem iitemcount m_plistctrl setitemstate iitem lvis_selected lvis_focused iitem m_plistctrl setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused m_plistctrl setselectionmark iitem m_plistctrl ensurevisible iitem static_downcast cobject cobject m_plistctrl getitemdata iitem c object c list ctrl item walk get prev selectable item assert m plistctrl null if m plistctrl null return null int i item count m plistctrl get item count if i item count 2 position pos m plistctrl get first selected item position if pos int i item m plistctrl get next selected item pos if i item 1 0 m plistctrl set item state i item 0 lvis selected lvis focused i item m plistctrl set item state i item lvis selected lvis focused lvis selected lvis focused m plistctrl set selection mark i item m plistctrl ensure visible i item false return static downcast c object c object m plistctrl get item data i item return null cobject clistctrlitemwalk getprevselectableitem m_plistctrl m_plistctrl iitemcount m_plistctrl getitemcount iitemcount m_plistctrl getfirstselecteditemposition iitem m_plistctrl getnextselecteditem iitem m_plistctrl setitemstate iitem lvis_selected lvis_focused iitem m_plistctrl setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused m_plistctrl setselectionmark iitem m_plistctrl ensurevisible iitem static_downcast cobject cobject m_plistctrl getitemdata iitem c list ctrl item walk this m tooltip new c tool tip ctrlx set general purpose find true false clistctrlitemwalk m_tooltip ctooltipctrlx setgeneralpurposefind c upload list ctrl c upload list ctrl delete m tooltip cuploadlistctrl cuploadlistctrl m_tooltip void c upload list ctrl init set name t upload list ctrl c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 set image list il dummy image list lvsil small assert get style lvs shareimagelists 0 il dummy image list detach set extended style lvs ex fullrowselect lvs ex infotip c tool tip ctrl tooltip get tool tips if tooltip m tooltip subclass window tooltip m hwnd tooltip modify style 0 tts noprefix tooltip set delay time ttdt autopop 20000 tooltip set delay time ttdt initial the prefs get tool tip delay 1000 insert column 0 get res string ids ql username lvcfmt left 150 0 insert column 1 get res string ids file lvcfmt left 275 1 insert column 2 get res string ids dl speed lvcfmt left 60 2 insert column 3 get res string ids dl transf lvcfmt left 65 3 insert column 4 get res string ids waited lvcfmt left 60 4 insert column 5 get res string ids uploadtime lvcfmt left 60 5 insert column 6 get res string ids status lvcfmt left 110 6 insert column 7 get res string ids upstatus lvcfmt left 100 7 set all icons localize load settings barry use preferred sort order from preferences set sort arrow sort items sort proc get sort item get sort ascending 0 100 cuploadlistctrl setname _t uploadlistctrl cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask setimagelist ildummyimagelist lvsil_small getstyle lvs_shareimagelists ildummyimagelist setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip ctooltipctrl gettooltips m_tooltip subclasswindow m_hwnd modifystyle tts_noprefix setdelaytime ttdt_autopop setdelaytime ttdt_initial theprefs gettooltipdelay insertcolumn getresstring ids_ql_username lvcfmt_left insertcolumn getresstring ids_file lvcfmt_left insertcolumn getresstring ids_dl_speed lvcfmt_left insertcolumn getresstring ids_dl_transf lvcfmt_left insertcolumn getresstring ids_waited lvcfmt_left insertcolumn getresstring ids_uploadtime lvcfmt_left insertcolumn getresstring ids_status lvcfmt_left insertcolumn getresstring ids_upstatus lvcfmt_left setallicons loadsettings setsortarrow sortitems sortproc getsortitem getsortascending void c upload list ctrl add client const c up down client client if the app emuledlg is running return int i item count get item count int i item insert item lvif text lvif param i item count lpstr textcallback 0 0 0 lparam client update i item the app emuledlg transferwnd update list count c transfer wnd wnd2 uploading i item count 1 cuploadlistctrl addclient cupdownclient theapp isrunning iitemcount getitemcount iitem insertitem lvif_text lvif_param iitemcount lpstr_textcallback iitem theapp updatelistcount ctransferwnd wnd2uploading iitemcount void c upload list ctrl remove client const c up down client client if the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam client int result find item find if result 1 delete item result the app emuledlg transferwnd update list count c transfer wnd wnd2 uploading cuploadlistctrl removeclient cupdownclient theapp isrunning lvfi_param lparam finditem deleteitem theapp updatelistcount ctransferwnd wnd2uploading void c upload list ctrl refresh client const c up down client client there is some type of timing issue here if you click on item in the queue or upload and leave the focus on it when you exit the cient it breaks on line 854 of emule dlg cpp i added this is running check to this function and the draw item method and this seems to keep it from crashing this is not the fix but a patch until someone points out what is going wrong also it will still assert in debug mode if the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam client int result find item find if result 1 update result cuploadlistctrl refreshclient cupdownclient emuledlg isrunning drawitem theapp isrunning lvfi_param lparam finditem void c upload list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res str res get res string ids ql username hdi psz text const cast lptstr lpctstr str res p header ctrl set item 0 hdi str res get res string ids file hdi psz text const cast lptstr lpctstr str res p header ctrl set item 1 hdi str res get res string ids dl speed hdi psz text const cast lptstr lpctstr str res p header ctrl set item 2 hdi str res get res string ids dl transf hdi psz text const cast lptstr lpctstr str res p header ctrl set item 3 hdi str res get res string ids waited hdi psz text const cast lptstr lpctstr str res p header ctrl set item 4 hdi str res get res string ids uploadtime hdi psz text const cast lptstr lpctstr str res p header ctrl set item 5 hdi str res get res string ids status hdi psz text const cast lptstr lpctstr str res p header ctrl set item 6 hdi str res get res string ids upstatus hdi psz text const cast lptstr lpctstr str res p header ctrl set item 7 hdi cuploadlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres strres getresstring ids_ql_username psztext const_cast strres pheaderctrl setitem strres getresstring ids_file psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_speed psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_transf psztext const_cast strres pheaderctrl setitem strres getresstring ids_waited psztext const_cast strres pheaderctrl setitem strres getresstring ids_uploadtime psztext const_cast strres pheaderctrl setitem strres getresstring ids_status psztext const_cast strres pheaderctrl setitem strres getresstring ids_upstatus psztext const_cast strres pheaderctrl setitem void c upload list ctrl show selected user details point point get cursor pos point c point p point screen to client p int it hit test p if it 1 return set item state 1 0 lvis selected set item state it lvis selected lvis focused lvis selected lvis focused set selection mark it display selection mark correctly c up down client client c up down client get item data get selection mark if client c client detail dialog dialog client this dialog do modal cuploadlistctrl showselecteduserdetails getcursorpos cpoint screentoclient hittest setitemstate lvis_selected setitemstate lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark cupdownclient cupdownclient getitemdata getselectionmark cclientdetaildialog domodal void c upload list ctrl set all icons imagelist delete image list imagelist create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 imagelist set bk color clr none imagelist add c temp icon loader t cliente donkey imagelist add c temp icon loader t client compatible imagelist add c temp icon loader t cliente donkey plus imagelist add c temp icon loader t client compatible plus imagelist add c temp icon loader t friend imagelist add c temp icon loader t clientml donkey imagelist add c temp icon loader t clientml donkey plus imagelist add c temp icon loader t cliente donkey hybrid imagelist add c temp icon loader t cliente donkey hybrid plus imagelist add c temp icon loader t client shareaza imagelist add c temp icon loader t client shareaza plus imagelist add c temp icon loader t clienta mule imagelist add c temp icon loader t clienta mule plus imagelist add c temp icon loader t clientl phant imagelist add c temp icon loader t clientl phant plus imagelist set overlay image imagelist add c temp icon loader t client secure ovl 1 cuploadlistctrl setallicons deleteimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t clientedonkey ctempiconloader _t clientcompatible ctempiconloader _t clientedonkeyplus ctempiconloader _t clientcompatibleplus ctempiconloader _t ctempiconloader _t clientmldonkey ctempiconloader _t clientmldonkeyplus ctempiconloader _t clientedonkeyhybrid ctempiconloader _t clientedonkeyhybridplus ctempiconloader _t clientshareaza ctempiconloader _t clientshareazaplus ctempiconloader _t clientamule ctempiconloader _t clientamuleplus ctempiconloader _t clientlphant ctempiconloader _t clientlphantplus setoverlayimage ctempiconloader _t clientsecureovl int c upload list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort const c up down client item1 c up down client l param1 const c up down client item2 c up down client l param2 int i result 0 switch l param sort case 0 if item1 get user name item2 get user name i result compare locale string no case item1 get user name item2 get user name else if item1 get user name i result 1 else i result 1 break case 100 if item1 get user name item2 get user name i result compare locale string no case item2 get user name item1 get user name else if item2 get user name i result 1 else i result 1 break case 1 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result compare locale string no case file1 get file name file2 get file name else if file1 null i result 1 else i result 1 break case 101 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result compare locale string no case file2 get file name file1 get file name else if file1 null i result 1 else i result 1 break case 2 i result compare unsigned item1 get datarate item2 get datarate break case 102 i result compare unsigned item2 get datarate item1 get datarate break case 3 i result compare unsigned item1 get session up item2 get session up if i result 0 the prefs m bextcontrols i result compare unsigned item1 get queue session payload up item2 get queue session payload up break case 103 i result compare unsigned item2 get session up item1 get session up if i result 0 the prefs m bextcontrols i result compare unsigned item2 get queue session payload up item1 get queue session payload up break case 4 i result item1 get wait time item2 get wait time break case 104 i result item2 get wait time item1 get wait time break case 5 i result item1 get up start time delay item2 get up start time delay break case 105 i result item2 get up start time delay item1 get up start time delay break case 6 i result item1 get upload state item2 get upload state break case 106 i result item2 get upload state item1 get upload state break case 7 i result item1 get up part count item2 get up part count break case 107 i result item2 get up part count item1 get up part count break default i result 0 break int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if i result 0 dw next sort the app emuledlg transferwnd uploadlistctrl get next sort order l param sort 1 i result sort proc l param1 l param2 dw next sort return i result cuploadlistctrl sortproc lparam1 lparam2 lparamsort cupdownclient cupdownclient lparam1 cupdownclient cupdownclient lparam2 iresult lparamsort getusername getusername iresult comparelocalestringnocase getusername getusername getusername iresult iresult getusername getusername iresult comparelocalestringnocase getusername getusername getusername iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult comparelocalestringnocase getfilename getfilename iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult comparelocalestringnocase getfilename getfilename iresult iresult iresult compareunsigned getdatarate getdatarate iresult compareunsigned getdatarate getdatarate iresult compareunsigned getsessionup getsessionup iresult theprefs m_bextcontrols iresult compareunsigned getqueuesessionpayloadup getqueuesessionpayloadup iresult compareunsigned getsessionup getsessionup iresult theprefs m_bextcontrols iresult compareunsigned getqueuesessionpayloadup getqueuesessionpayloadup iresult getwaittime getwaittime iresult getwaittime getwaittime iresult getupstarttimedelay getupstarttimedelay iresult getupstarttimedelay getupstarttimedelay iresult getuploadstate getuploadstate iresult getuploadstate getuploadstate iresult getuppartcount getuppartcount iresult getuppartcount getuppartcount iresult dwnextsort iresult dwnextsort theapp getnextsortorder lparamsort iresult sortproc lparam1 lparam2 dwnextsort iresult bool c upload list ctrl on command wparam w param lparam l param w param loword w param switch w param case mp find on find start return true int i sel get next item 1 lvis selected lvis focused if i sel 1 c up down client client c up down client get item data i sel switch w param case mp showlist client request shared file list break case mp message the app emuledlg chatwnd start session client break case mp addfriend if the app friendlist add friend client update i sel break case mp detail case mpg altenter case ida enter c client detail dialog dialog client this dialog do modal break case mp boot if client get kad port kademlia c kademlia bootstrap ntohl client getip client get kad port break return true cuploadlistctrl oncommand wparam lparam wparam wparam wparam mp_find onfindstart isel getnextitem lvis_selected lvis_focused isel cupdownclient cupdownclient getitemdata isel wparam mp_showlist requestsharedfilelist mp_message theapp startsession mp_addfriend theapp addfriend isel mp_detail mpg_altenter ida_enter cclientdetaildialog domodal mp_boot getkadport ckademlia getkadport void c upload list ctrl draw item lpdrawitemstruct lp draw item struct if the app emuledlg is running return if lp draw item struct item data return cdc odc cdc from handle lp draw item struct hdc bool b ctrl focused get focus this get style lvs showselalways if lp draw item struct item state ods selected if b ctrl focused odc set bk color m crhighlight else odc set bk color m crnohighlight else odc set bk color get bk color const c up down client client c up down client lp draw item struct item data c memdc dc odc lp draw item struct rc item c font p old font dc select object get font c rect cur rec lp draw item struct rc item colorref cr old text color dc set text color lp draw item struct item state ods selected m crhighlighttext m crwindowtext if client get slot number the app uploadqueue get active uploads count dc set text color get sys color color graytext int i old bk mode if m crwindowtextbk clr none def window proc wm erasebkgnd wparam hdc dc 0 i old bk mode dc set bk mode transparent else i old bk mode opaque c known file file the app sharedfiles get file byid client get upload fileid c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count cur rec right cur rec left 8 cur rec left 4 c string sbuffer for int i current 0 i current i count i current int i column p header ctrl order to index i current if is column hidden i column cur rec right get column width i column switch i column case 0 uint8 image if client is friend image 4 else if client get client soft so edonkeyhybrid if client credits get score ratio client getip 1 image 8 else image 7 else if client get client soft so mldonkey if client credits get score ratio client getip 1 image 6 else image 5 else if client get client soft so shareaza if client credits get score ratio client getip 1 image 10 else image 9 else if client get client soft so amule if client credits get score ratio client getip 1 image 12 else image 11 else if client get client soft so lphant if client credits get score ratio client getip 1 image 14 else image 13 else if client ext protocol available if client credits get score ratio client getip 1 image 3 else image 1 else if client credits get score ratio client getip 1 image 2 else image 0 point point cur rec left cur rec top 1 imagelist draw dc image point ild normal client credits client credits get current ident state client getip is identified indextooverlaymask 1 0 sbuffer client get user name cur rec left 20 dc draw text sbuffer sbuffer get length cur rec dlc dt text cur rec left 20 break case 1 if file sbuffer file get file name else sbuffer t break case 2 sbuffer cast itox bytes client get datarate false true break case 3 note if you change add remove anything which is displayed here update also the sorting part if the prefs m bextcontrols sbuffer format t s s cast itox bytes client get session up false false cast itox bytes client get queue session payload up false false else sbuffer cast itox bytes client get session up false false break case 4 if client has lowid sbuffer format t s s cast seconds tohm client get wait time 1000 get res string ids idlow else sbuffer cast seconds tohm client get wait time 1000 break case 5 sbuffer cast seconds tohm client get up start time delay 1000 break case 6 sbuffer client get upload state display string break case 7 cur rec bottom cur rec top client draw up status bar dc cur rec false the prefs use flat bar cur rec bottom cur rec top break if i column 7 i column 0 dc draw text sbuffer sbuffer get length cur rec dlc dt text cur rec left get column width i column draw rectangle around selected item s if lp draw item struct item state ods selected rect outline rec lp draw item struct rc item outline rec top outline rec bottom dc frame rect outline rec c brush get bk color outline rec top outline rec bottom outline rec left outline rec right if b ctrl focused dc frame rect outline rec c brush m crfocusline else dc frame rect outline rec c brush m crnofocusline if m crwindowtextbk clr none dc set bk mode i old bk mode dc select object p old font dc set text color cr old text color cuploadlistctrl drawitem lpdrawitemstruct theapp isrunning lpdrawitemstruct itemdata fromhandle lpdrawitemstruct bctrlfocused getfocus getstyle lvs_showselalways lpdrawitemstruct itemstate ods_selected bctrlfocused setbkcolor m_crhighlight setbkcolor m_crnohighlight setbkcolor getbkcolor cupdownclient cupdownclient lpdrawitemstruct itemdata cmemdc lpdrawitemstruct rcitem cfont poldfont selectobject getfont crect cur_rec lpdrawitemstruct rcitem croldtextcolor settextcolor lpdrawitemstruct itemstate ods_selected m_crhighlighttext m_crwindowtext getslotnumber theapp getactiveuploadscount settextcolor getsyscolor color_graytext ioldbkmode m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd ioldbkmode setbkmode ioldbkmode cknownfile theapp getfilebyid getuploadfileid cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount cur_rec cur_rec cur_rec cstring icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent iscolumnhidden icolumn cur_rec getcolumnwidth icolumn icolumn isfriend getclientsoft so_edonkeyhybrid getscoreratio getclientsoft so_mldonkey getscoreratio getclientsoft so_shareaza getscoreratio getclientsoft so_amule getscoreratio getclientsoft so_lphant getscoreratio extprotocolavailable getscoreratio getscoreratio cur_rec cur_rec ild_normal getcurrentidentstate is_identified getusername cur_rec drawtext getlength cur_rec dlc_dt_text cur_rec getfilename _t castitoxbytes getdatarate theprefs m_bextcontrols _t castitoxbytes getsessionup castitoxbytes getqueuesessionpayloadup castitoxbytes getsessionup haslowid _t castsecondstohm getwaittime getresstring ids_idlow castsecondstohm getwaittime castsecondstohm getupstarttimedelay getuploadstatedisplaystring cur_rec cur_rec drawupstatusbar cur_rec theprefs useflatbar cur_rec cur_rec icolumn icolumn drawtext getlength cur_rec dlc_dt_text cur_rec getcolumnwidth icolumn lpdrawitemstruct itemstate ods_selected outline_rec lpdrawitemstruct rcitem outline_rec outline_rec framerect outline_rec cbrush getbkcolor outline_rec outline_rec outline_rec outline_rec bctrlfocused framerect outline_rec cbrush m_crfocusline framerect outline_rec cbrush m_crnofocusline m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor void c upload list ctrl on sys color change c mule list ctrl on sys color change set all icons cuploadlistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons void c upload list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr if it s a second click on the same column then reverse the sort order otherwise sort the new column in ascending order barry store sort order in preferences determine ascending based on whether already sorted on this column bool sort ascending get sort item pnm list view i sub item true get sort ascending sort table update sort history pnm list view i sub item sort ascending 0 100 set sort arrow pnm list view i sub item sort ascending sort items sort proc pnm list view i sub item sort ascending 0 100 p result 0 cuploadlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview sortascending getsortitem pnmlistview isubitem getsortascending updatesorthistory pnmlistview isubitem sortascending setsortarrow pnmlistview isubitem sortascending sortitems sortproc pnmlistview isubitem sortascending presult void c upload list ctrl on context menu c wnd p wnd c point point int i sel get next item 1 lvis selected lvis focused const c up down client client i sel 1 c up down client get item data i sel null c title menu client menu client menu create popup menu client menu add menu title get res string ids clients true client menu append menu mf string client mf enabled mf grayed mp detail get res string ids showdetails t clientdetails client menu set default item mp detail client menu append menu mf string client client is ed2k client client is friend mf enabled mf grayed mp addfriend get res string ids addfriend t addfriend client menu append menu mf string client client is ed2k client mf enabled mf grayed mp message get res string ids send msg t sendmessage client menu append menu mf string client client is ed2k client client get view shared files support mf enabled mf grayed mp showlist get res string ids viewfiles t viewfiles if kademlia c kademlia is running kademlia c kademlia is connected client menu append menu mf string client client is ed2k client client get kad port 0 mf enabled mf grayed mp boot get res string ids bootstrap client menu append menu mf string get item count 0 mf enabled mf grayed mp find get res string ids find t search get popup menu pos this point client menu track popup menu tpm leftalign tpm rightbutton point x point y this cuploadlistctrl oncontextmenu cwnd pwnd cpoint isel getnextitem lvis_selected lvis_focused cupdownclient isel cupdownclient getitemdata isel ctitlemenu clientmenu clientmenu createpopupmenu clientmenu addmenutitle getresstring ids_clients clientmenu appendmenu mf_string mf_enabled mf_grayed mp_detail getresstring ids_showdetails _t clientmenu setdefaultitem mp_detail clientmenu appendmenu mf_string ised2kclient isfriend mf_enabled mf_grayed mp_addfriend getresstring ids_addfriend _t clientmenu appendmenu mf_string ised2kclient mf_enabled mf_grayed mp_message getresstring ids_send_msg _t clientmenu appendmenu mf_string ised2kclient getviewsharedfilessupport mf_enabled mf_grayed mp_showlist getresstring ids_viewfiles _t ckademlia isrunning ckademlia isconnected clientmenu appendmenu mf_string ised2kclient getkadport mf_enabled mf_grayed mp_boot getresstring ids_bootstrap clientmenu appendmenu mf_string getitemcount mf_enabled mf_grayed mp_find getresstring ids_find _t getpopupmenupos clientmenu trackpopupmenu tpm_leftalign tpm_rightbutton void c upload list ctrl onnm dblclk nmhdr pnmhdr lresult p result int i sel get next item 1 lvis selected lvis focused if i sel 1 c up down client client c up down client get item data i sel if client c client detail dialog dialog client this dialog do modal p result 0 cuploadlistctrl onnmdblclk presult isel getnextitem lvis_selected lvis_focused isel cupdownclient cupdownclient getitemdata isel cclientdetaildialog domodal presult void c upload list ctrl on get disp info nmhdr pnmhdr lresult p result nmlvdispinfo p disp info reinterpret cast nmlvdispinfo pnmhdr if the app emuledlg is running although we have an owner drawn listview control we store the text for the primary item in the listview to be capable of quick searching those items via the keyboard because our listview items may change their contents we do this via a text callback function the listview control will send us the lvn dispinfo notification if it needs to know the contents of the primary item but the listview control sends this notification all the time even if we do not search for an item at least this notification is only sent for the visible items and not for all items in the list though because this function is invoked very often no not put any time consuming code here in if p disp info item mask lvif text const c up down client p client reinterpret cast c up down client p disp info item l param if p client null switch p disp info item i sub item case 0 if p client get user name p disp info item cch text max 0 tcsncpy p disp info item psz text p client get user name p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break default shouldn t happen p disp info item psz text 0 t 0 break p result 0 cuploadlistctrl ongetdispinfo presult pdispinfo reinterpret_cast theapp isrunning lvn_dispinfo pdispinfo lvif_text cupdownclient pclient reinterpret_cast cupdownclient pdispinfo lparam pclient pdispinfo isubitem pclient getusername pdispinfo cchtextmax _tcsncpy pdispinfo psztext pclient getusername pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t pdispinfo psztext _t presult void c upload list ctrl on lvn get info tip nmhdr pnmhdr lresult p result lpnmlvgetinfotip p get info tip reinterpret cast lpnmlvgetinfotip pnmhdr if p get info tip i sub item 0 lvhittestinfo hti 0 get cursor pos hti pt screen to client hti pt if sub item hit test hti 1 hti i item p get info tip i item hti i sub item 0 don show the default label tip for the main item if the mouse is not over the main item if p get info tip dw flags lvgit unfolded 0 p get info tip cch text max 0 p get info tip psz text 0 0 p get info tip psz text 0 0 return const c up down client client c up down client get item data p get info tip i item if client p get info tip psz text p get info tip cch text max 0 c string info c known file file the app sharedfiles get file byid client get upload fileid build info text and display it info format get res string ids userinfo client get user name if file info get res string ids sf requested t c string file get file name t n c string stat stat format get res string ids filestats session get res string ids filestats total file statistic get accepts file statistic get requests cast itox bytes file statistic get transferred false false file statistic get all time accepts file statistic get all time requests cast itox bytes file statistic get all time transferred false false info stat else info get res string ids req unknownfile tcsncpy p get info tip psz text info p get info tip cch text max p get info tip psz text p get info tip cch text max 1 t 0 p result 0 cuploadlistctrl onlvngetinfotip presult pgetinfotip reinterpret_cast pgetinfotip isubitem getcursorpos screentoclient subitemhittest iitem pgetinfotip iitem isubitem pgetinfotip dwflags lvgit_unfolded pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip psztext cupdownclient cupdownclient getitemdata pgetinfotip iitem pgetinfotip psztext pgetinfotip cchtextmax cstring cknownfile theapp getfilebyid getuploadfileid getresstring ids_userinfo getusername getresstring ids_sf_requested _t cstring getfilename _t cstring getresstring ids_filestats_session getresstring ids_filestats_total getaccepts getrequests castitoxbytes gettransferred getalltimeaccepts getalltimerequests castitoxbytes getalltimetransferred getresstring ids_req_unknownfile _tcsncpy pgetinfotip psztext pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip cchtextmax _t presult c download list list ctrl item walk this m tooltip new c tool tip ctrlx set general purpose find true false cdownloadlistlistctrlitemwalk m_tooltip ctooltipctrlx setgeneralpurposefind c download list ctrl c download list ctrl if m priomenu verify m priomenu destroy menu if m sourcesmenu verify m sourcesmenu destroy menu if m filemenu verify m filemenu destroy menu while m listitems empty false delete m listitems begin second second ctrlitem struct m listitems erase m listitems begin delete m tooltip cdownloadlistctrl cdownloadlistctrl m_priomenu m_priomenu destroymenu m_sourcesmenu m_sourcesmenu destroymenu m_filemenu m_filemenu destroymenu m_listitems m_listitems ctrlitem_struct m_listitems m_listitems m_tooltip void c download list ctrl update item void toupdate if the app emuledlg is running return retrieve all entries matching the source std pair list items const iterator list items const iterator range it m listitems equal range toupdate for list items const iterator it range it first it range it second it ctrlitem struct update item it second find entry in c list ctrl and update object lvfindinfo find find flags lvfi param find l param lparam update item int result find item find if result 1 update item dw updated 0 update result cdownloadlistctrl updateitem theapp isrunning listitems const_iterator listitems const_iterator rangeit m_listitems equal_range listitems const_iterator rangeit rangeit ctrlitem_struct updateitem clistctrl lvfi_param lparam updateitem finditem updateitem dwupdated void c download list ctrl init set name t download list ctrl c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 set image list il dummy image list lvsil small assert get style lvs shareimagelists 0 il dummy image list detach set style modify style lvs singlesel 0 c tool tip ctrl tooltip get tool tips if tooltip m tooltip subclass window tooltip tooltip modify style 0 tts noprefix tooltip set delay time ttdt autopop 20000 tooltip set delay time ttdt initial the prefs get tool tip delay 1000 insert column 0 get res string ids dl filename lvcfmt left 260 insert column 1 get res string ids dl size lvcfmt left 60 insert column 2 get res string ids dl transf lvcfmt left 65 insert column 3 get res string ids dl transfcompl lvcfmt left 65 insert column 4 get res string ids dl speed lvcfmt left 65 insert column 5 get res string ids dl progress lvcfmt left 170 insert column 6 get res string ids dl sources lvcfmt left 50 insert column 7 get res string ids priority lvcfmt left 55 insert column 8 get res string ids status lvcfmt left 70 insert column 9 get res string ids dl remains lvcfmt left 110 c string lsctitle get res string ids lastseencompl lsctitle remove t insert column 10 lsctitle lvcfmt left 220 lsctitle get res string ids fd lastchange lsctitle remove t insert column 11 lsctitle lvcfmt left 220 insert column 12 get res string ids cat lvcfmt left 100 set all icons localize load settings cur tab 0 if the prefs get show active downloads bold c font p font get font logfont lf font 0 p font get log font lf font lf font lf weight fw bold m fontbold create font indirect lf font barry use preferred sort order from preferences m bremainsort the prefs transferlist remain sort style uint8 adder 0 if get sort item 9 m bremainsort set sort arrow else set sort arrow get sort item get sort ascending arrow double up arrow double down adder 81 sort items sort proc get sort item get sort ascending 0 100 adder cdownloadlistctrl setname _t downloadlistctrl cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask setimagelist ildummyimagelist lvsil_small getstyle lvs_shareimagelists ildummyimagelist setstyle modifystyle lvs_singlesel ctooltipctrl gettooltips m_tooltip subclasswindow modifystyle tts_noprefix setdelaytime ttdt_autopop setdelaytime ttdt_initial theprefs gettooltipdelay insertcolumn getresstring ids_dl_filename lvcfmt_left insertcolumn getresstring ids_dl_size lvcfmt_left insertcolumn getresstring ids_dl_transf lvcfmt_left insertcolumn getresstring ids_dl_transfcompl lvcfmt_left insertcolumn getresstring ids_dl_speed lvcfmt_left insertcolumn getresstring ids_dl_progress lvcfmt_left insertcolumn getresstring ids_dl_sources lvcfmt_left insertcolumn getresstring ids_priority lvcfmt_left insertcolumn getresstring ids_status lvcfmt_left insertcolumn getresstring ids_dl_remains lvcfmt_left cstring getresstring ids_lastseencompl _t insertcolumn lvcfmt_left getresstring ids_fd_lastchange _t insertcolumn lvcfmt_left insertcolumn getresstring ids_cat lvcfmt_left setallicons loadsettings curtab theprefs getshowactivedownloadsbold cfont pfont getfont lffont pfont getlogfont lffont lffont lfweight fw_bold m_fontbold createfontindirect lffont m_bremainsort theprefs transferlistremainsortstyle getsortitem m_bremainsort setsortarrow setsortarrow getsortitem getsortascending arrowdoubleup arrowdoubledown sortitems sortproc getsortitem getsortascending void c download list ctrl add file c part file toadd create new item ctrlitem struct newitem new ctrlitem struct int itemnr get item count newitem owner null newitem type file type newitem value toadd newitem parent null newitem dw updated 0 the same file shall be added only once assert m listitems find toadd m listitems end m listitems insert list items pair toadd newitem if toadd check show item in given cat cur tab insert item lvif param lvif text itemnr lpstr textcallback 0 0 0 lparam newitem show files count cdownloadlistctrl addfile cpartfile ctrlitem_struct ctrlitem_struct getitemcount file_type dwupdated m_listitems m_listitems m_listitems listitemspair checkshowitemingivencat curtab insertitem lvif_param lvif_text lpstr_textcallback showfilescount void c download list ctrl add source c part file owner c up down client source bool notavailable create new item ctrlitem struct newitem new ctrlitem struct newitem owner owner newitem type notavailable unavailable source available source newitem value source newitem dw updated 0 update cross link to the owner list items const iterator owner it m listitems find owner assert owner it m listitems end ctrlitem struct owner item owner it second assert owner item value owner newitem parent owner item the same source could be added a few time but only one time per file update the other instances of this source bool b found false std pair list items const iterator list items const iterator range it m listitems equal range source for list items const iterator it range it first it range it second it ctrlitem struct cur item it second check if this source has been already added to this file to be sure if cur item owner owner update this instance with its new setting cur item type newitem type cur item dw updated 0 b found true else if notavailable false the state available is exclusive cur item type unavailable source cur item dw updated 0 if b found true delete newitem return m listitems insert list items pair source newitem if owner srcarevisible find parent from the c list ctrl to add source lvfindinfo find find flags lvfi param find l param lparam owner item int result find item find if result 1 insert item lvif param lvif text result 1 lpstr textcallback 0 0 0 lparam newitem cdownloadlistctrl addsource cpartfile cupdownclient ctrlitem_struct ctrlitem_struct unavailable_source available_source dwupdated listitems const_iterator ownerit m_listitems ownerit m_listitems ctrlitem_struct owneritem ownerit owneritem owneritem bfound listitems const_iterator listitems const_iterator rangeit m_listitems equal_range listitems const_iterator rangeit rangeit ctrlitem_struct cur_item cur_item cur_item cur_item dwupdated bfound cur_item unavailable_source cur_item dwupdated bfound m_listitems listitemspair clistctrl lvfi_param lparam owneritem finditem insertitem lvif_param lvif_text lpstr_textcallback void c download list ctrl remove source c up down client source c part file owner if the app emuledlg is running return retrieve all entries matching the source std pair list items iterator list items iterator range it m listitems equal range source for list items iterator it range it first it range it second ctrlitem struct del item it second if owner null owner del item owner remove it from the m listitems it m listitems erase it remove it from the c list ctrl lvfindinfo find find flags lvfi param find l param lparam del item int result find item find if result 1 delete item result finally it could be delete delete del item else it cdownloadlistctrl removesource cupdownclient cpartfile theapp isrunning listitems listitems rangeit m_listitems equal_range listitems rangeit rangeit ctrlitem_struct delitem delitem m_listitems m_listitems clistctrl lvfi_param lparam delitem finditem deleteitem delitem bool c download list ctrl remove file const c part file toremove bool b result false if the app emuledlg is running return b result retrieve all entries matching the file or linked to the file remark the asked another files clients must be removed from here assert toremove null for list items iterator it m listitems begin it m listitems end ctrlitem struct del item it second if del item owner toremove del item value void toremove remove it from the m listitems it m listitems erase it remove it from the c list ctrl lvfindinfo find find flags lvfi param find l param lparam del item int result find item find if result 1 delete item result finally it could be delete delete del item b result true else it show files count return b result cdownloadlistctrl removefile cpartfile bresult theapp isrunning bresult listitems m_listitems m_listitems ctrlitem_struct delitem delitem delitem m_listitems m_listitems clistctrl lvfi_param lparam delitem finditem deleteitem delitem bresult showfilescount bresult void c download list ctrl clear completed int incat if incat 2 incat cur tab search for completed file s for list items iterator it m listitems begin it m listitems end ctrlitem struct cur item it second it already point to the next iterator if cur item type file type c part file file reinterpret cast c part file cur item value if file is part file false file check show item in given cat incat incat 1 if remove file file it m listitems begin if the prefs show cat tab infos the app emuledlg transferwnd update cat tab titles cdownloadlistctrl clearcompleted curtab listitems m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item ispartfile checkshowitemingivencat removefile m_listitems theprefs showcattabinfos theapp updatecattabtitles void c download list ctrl clear completed const c part file p file if p file is part file for list items iterator it m listitems begin it m listitems end ctrlitem struct cur item it second it if cur item type file type const c part file p cur file reinterpret cast c part file cur item value if p cur file p file remove file p cur file return cdownloadlistctrl clearcompleted cpartfile pfile pfile ispartfile listitems m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile pcurfile reinterpret_cast cpartfile cur_item pcurfile pfile removefile pcurfile void c download list ctrl set style if the prefs is double click enabled set extended style lvs ex fullrowselect lvs ex infotip else set extended style lvs ex oneclickactivate lvs ex fullrowselect lvs ex infotip cdownloadlistctrl setstyle theprefs isdoubleclickenabled setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip setextendedstyle lvs_ex_oneclickactivate lvs_ex_fullrowselect lvs_ex_infotip void c download list ctrl create menues if m priomenu verify m priomenu destroy menu if m sourcesmenu verify m sourcesmenu destroy menu if m filemenu verify m filemenu destroy menu m filemenu create popup menu m filemenu add menu title get res string ids downloadmenutitle true add download priority sub menu m priomenu create menu m priomenu add menu title null true m priomenu append menu mf string mp priolow get res string ids priolow m priomenu append menu mf string mp prionormal get res string ids prionormal m priomenu append menu mf string mp priohigh get res string ids priohigh m priomenu append menu mf string mp prioauto get res string ids prioauto m filemenu append menu mf string mf popup uint ptr m priomenu m hmenu get res string ids priority t get res string ids download t t filepriority add file commands m filemenu append menu mf string mp pause get res string ids dl pause t pause m filemenu append menu mf string mp stop get res string ids dl stop t stop m filemenu append menu mf string mp resume get res string ids dl resume t resume m filemenu append menu mf string mp cancel get res string ids main btn cancel t delete m filemenu append menu mf separator m filemenu append menu mf string mp open get res string ids dl open t openfile if the prefs is ext controls enabled the prefs get preview prio m filemenu append menu mf string mp try to get preview parts get res string ids dl try to get preview parts m filemenu append menu mf string mp preview get res string ids dl preview t preview m filemenu append menu mf string mp metinfo get res string ids dl info t fileinfo m filemenu append menu mf string mp viewfilecomments get res string ids cmt showall t filecomments m filemenu append menu mf separator m filemenu append menu mf string mp clearcompleted get res string ids dl clear t clearcomplete add extended user mode source handling sub menu if the prefs is ext controls enabled m sourcesmenu create menu m sourcesmenu append menu mf string mp addsource get res string ids addsrcmanually m sourcesmenu append menu mf string mp setsourcelimit get res string ids setpfslimit m filemenu append menu mf string mf popup uint ptr m sourcesmenu m hmenu get res string ids a4af m filemenu append menu mf separator add copy paste commands if the prefs get show copy ed2k link cmd m filemenu append menu mf string mp geted2klink get res string ids dl link1 t ed2klink else m filemenu append menu mf string mp showed2klink get res string ids dl showed2klink t ed2klink m filemenu append menu mf string mp paste get res string ids sw directdownload t pastelink m filemenu append menu mf separator search commands m filemenu append menu mf string mp find get res string ids find t search m filemenu append menu mf string mp searchrelated get res string ids searchrelated t kad file search web services and categories will be added on the fly cdownloadlistctrl createmenues m_priomenu m_priomenu destroymenu m_sourcesmenu m_sourcesmenu destroymenu m_filemenu m_filemenu destroymenu m_filemenu createpopupmenu m_filemenu addmenutitle getresstring ids_downloadmenutitle m_priomenu createmenu m_priomenu addmenutitle m_priomenu appendmenu mf_string mp_priolow getresstring ids_priolow m_priomenu appendmenu mf_string mp_prionormal getresstring ids_prionormal m_priomenu appendmenu mf_string mp_priohigh getresstring ids_priohigh m_priomenu appendmenu mf_string mp_prioauto getresstring ids_prioauto m_filemenu appendmenu mf_string mf_popup uint_ptr m_priomenu m_hmenu getresstring ids_priority _t getresstring ids_download _t _t m_filemenu appendmenu mf_string mp_pause getresstring ids_dl_pause _t m_filemenu appendmenu mf_string mp_stop getresstring ids_dl_stop _t m_filemenu appendmenu mf_string mp_resume getresstring ids_dl_resume _t m_filemenu appendmenu mf_string mp_cancel getresstring ids_main_btn_cancel _t m_filemenu appendmenu mf_separator m_filemenu appendmenu mf_string mp_open getresstring ids_dl_open _t theprefs isextcontrolsenabled theprefs getpreviewprio m_filemenu appendmenu mf_string mp_try_to_get_preview_parts getresstring ids_dl_try_to_get_preview_parts m_filemenu appendmenu mf_string mp_preview getresstring ids_dl_preview _t m_filemenu appendmenu mf_string mp_metinfo getresstring ids_dl_info _t m_filemenu appendmenu mf_string mp_viewfilecomments getresstring ids_cmt_showall _t m_filemenu appendmenu mf_separator m_filemenu appendmenu mf_string mp_clearcompleted getresstring ids_dl_clear _t theprefs isextcontrolsenabled m_sourcesmenu createmenu m_sourcesmenu appendmenu mf_string mp_addsource getresstring ids_addsrcmanually m_sourcesmenu appendmenu mf_string mp_setsourcelimit getresstring ids_setpfslimit m_filemenu appendmenu mf_string mf_popup uint_ptr m_sourcesmenu m_hmenu getresstring ids_a4af m_filemenu appendmenu mf_separator theprefs getshowcopyed2klinkcmd m_filemenu appendmenu mf_string mp_geted2klink getresstring ids_dl_link1 _t m_filemenu appendmenu mf_string mp_showed2klink getresstring ids_dl_showed2klink _t m_filemenu appendmenu mf_string mp_paste getresstring ids_sw_directdownload _t m_filemenu appendmenu mf_separator m_filemenu appendmenu mf_string mp_find getresstring ids_find _t m_filemenu appendmenu mf_string mp_searchrelated getresstring ids_searchrelated _t kadfilesearch void c download list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res str res get res string ids dl filename hdi psz text const cast lptstr lpctstr str res p header ctrl set item 0 hdi str res get res string ids dl size hdi psz text const cast lptstr lpctstr str res p header ctrl set item 1 hdi str res get res string ids dl transf hdi psz text const cast lptstr lpctstr str res p header ctrl set item 2 hdi str res get res string ids dl transfcompl hdi psz text const cast lptstr lpctstr str res p header ctrl set item 3 hdi str res get res string ids dl speed hdi psz text const cast lptstr lpctstr str res p header ctrl set item 4 hdi str res get res string ids dl progress hdi psz text const cast lptstr lpctstr str res p header ctrl set item 5 hdi str res get res string ids dl sources hdi psz text const cast lptstr lpctstr str res p header ctrl set item 6 hdi str res get res string ids priority hdi psz text const cast lptstr lpctstr str res p header ctrl set item 7 hdi str res get res string ids status hdi psz text const cast lptstr lpctstr str res p header ctrl set item 8 hdi str res get res string ids dl remains hdi psz text const cast lptstr lpctstr str res p header ctrl set item 9 hdi str res get res string ids lastseencompl str res remove t hdi psz text const cast lptstr lpctstr str res p header ctrl set item 10 hdi str res get res string ids fd lastchange str res remove t hdi psz text const cast lptstr lpctstr str res p header ctrl set item 11 hdi str res get res string ids cat hdi psz text const cast lptstr lpctstr str res p header ctrl set item 12 hdi create menues show files count cdownloadlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres strres getresstring ids_dl_filename psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_size psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_transf psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_transfcompl psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_speed psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_progress psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_sources psztext const_cast strres pheaderctrl setitem strres getresstring ids_priority psztext const_cast strres pheaderctrl setitem strres getresstring ids_status psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_remains psztext const_cast strres pheaderctrl setitem strres getresstring ids_lastseencompl strres _t psztext const_cast strres pheaderctrl setitem strres getresstring ids_fd_lastchange strres _t psztext const_cast strres pheaderctrl setitem strres getresstring ids_cat psztext const_cast strres pheaderctrl setitem createmenues showfilescount void c download list ctrl show files count the app emuledlg transferwnd update files count get files count in cur cat cdownloadlistctrl showfilescount theapp updatefilescount getfilescountincurcat void c download list ctrl change category int newsel set redraw false remove all displayed files with a different cat and show the correct ones for list items const iterator it m listitems begin it m listitems end it const ctrlitem struct cur item it second if cur item type file type c part file file reinterpret cast c part file cur item value if file check show item in given cat newsel hide file file else show file file set redraw true cur tab newsel show files count cdownloadlistctrl changecategory setredraw listitems const_iterator m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item checkshowitemingivencat hidefile showfile setredraw curtab showfilescount c string c download list ctrl get text list c string out for list items iterator it m listitems begin it m listitems end it const ctrlitem struct cur item it second if cur item type file type const c part file file reinterpret cast c part file cur item value c string temp temp format t n s t 1f i i s file get file name file get percent completed file get transferring src count file get source count file get partfile status out temp return out cstring cdownloadlistctrl gettextlist cstring listitems m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item cstring _t getfilename getpercentcompleted gettransferringsrccount getsourcecount getpartfilestatus void c download list ctrl show selected file details point point get cursor pos point c point pt point screen to client pt int it hit test pt if it 1 return set item state 1 0 lvis selected set item state it lvis selected lvis focused lvis selected lvis focused set selection mark it display selection mark correctly ctrlitem struct content ctrlitem struct get item data get selection mark if content type file type c part file file c part file content value if the prefs show rating indicator file has comment file has rating pt x file item margin x the app get small sytem icon size cx pt x file item margin x the app get small sytem icon size cx rating icon width show file dialog idd commentlst else show file dialog 0 else show client dialog c up down client content value cdownloadlistctrl showselectedfiledetails getcursorpos cpoint screentoclient hittest setitemstate lvis_selected setitemstate lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark ctrlitem_struct ctrlitem_struct getitemdata getselectionmark file_type cpartfile cpartfile theprefs showratingindicator hascomment hasrating file_item_margin_x theapp getsmallsytemiconsize file_item_margin_x theapp getsmallsytemiconsize rating_icon_width showfiledialog idd_commentlst showfiledialog showclientdialog cupdownclient void c download list ctrl hide file c part file tohide hide sources tohide retrieve all entries matching the source std pair list items const iterator list items const iterator range it m listitems equal range tohide for list items const iterator it range it first it range it second it ctrlitem struct update item it second find entry in c list ctrl and update object lvfindinfo find find flags lvfi param find l param lparam update item int result find item find if result 1 delete item result return cdownloadlistctrl hidefile cpartfile hidesources listitems const_iterator listitems const_iterator rangeit m_listitems equal_range listitems const_iterator rangeit rangeit ctrlitem_struct updateitem clistctrl lvfi_param lparam updateitem finditem deleteitem void c download list ctrl show file c part file toshow retrieve all entries matching the source std pair list items const iterator list items const iterator range it m listitems equal range toshow list items const iterator it range it first if it range it second ctrlitem struct update item it second check if entry is already in the list lvfindinfo find find flags lvfi param find l param lparam update item int result find item find if result 1 insert item lvif param lvif text get item count lpstr textcallback 0 0 0 lparam update item cdownloadlistctrl showfile cpartfile listitems const_iterator listitems const_iterator rangeit m_listitems equal_range listitems const_iterator rangeit rangeit ctrlitem_struct updateitem lvfi_param lparam updateitem finditem insertitem lvif_param lvif_text getitemcount lpstr_textcallback updateitem void c download list ctrl expand collapse item int i item int i action bool b collapse source if i item 1 return ctrlitem struct content ctrlitem struct get item data i item to collapse expand files when one of its source is selected if b collapse source content parent null content content parent lvfindinfo find find flags lvfi param find l param lparam content i item find item find if i item 1 return if content content type file type return c part file partfile reinterpret cast c part file content value if partfile return if partfile can open file partfile open file return check if the source branch is disable if partfile srcarevisible if i action collapse only set redraw false go throught the whole list to find out the sources for this file remark don t use get source count unavailable source for list items const iterator it m listitems begin it m listitems end it const ctrlitem struct cur item it second if cur item owner partfile partfile srcarevisible true insert item lvif param lvif text i item 1 lpstr textcallback 0 0 0 lparam cur item set redraw true else if i action expand collapse i action collapse only if get item state i item lvis selected lvis focused lvis selected lvis focused set item state i item lvis selected lvis focused lvis selected lvis focused set selection mark i item hide sources partfile cdownloadlistctrl expandcollapseitem iitem iaction bcollapsesource iitem ctrlitem_struct ctrlitem_struct getitemdata iitem bcollapsesource lvfi_param lparam iitem finditem iitem file_type cpartfile reinterpret_cast cpartfile canopenfile openfile iaction collapse_only setredraw getsourcecount unavailable_source listitems const_iterator m_listitems m_listitems ctrlitem_struct cur_item cur_item insertitem lvif_param lvif_text iitem lpstr_textcallback cur_item setredraw iaction expand_collapse iaction collapse_only getitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark iitem hidesources void c download list ctrl hide sources c part file to collapse set redraw false int pre 0 int post 0 for int i 0 i get item count i ctrlitem struct item ctrlitem struct get item data i if item owner to collapse pre item dw updated 0 item status delete object delete item i post if pre post 0 to collapse srcarevisible false set redraw true cdownloadlistctrl hidesources cpartfile tocollapse setredraw getitemcount ctrlitem_struct ctrlitem_struct getitemdata tocollapse dwupdated deleteobject deleteitem tocollapse setredraw void c download list ctrl get displayed files c array c part file c part file list for list items iterator it m listitems begin it m listitems end ctrlitem struct cur item it second it already point to the next iterator if cur item type file type c part file file reinterpret cast c part file cur item value list add file cdownloadlistctrl getdisplayedfiles carray cpartfile cpartfile listitems m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item void c download list ctrl move completedfiles cat uint8 from uint8 to int mycat for list items iterator it m listitems begin it m listitems end ctrlitem struct cur item it second it already point to the next iterator if cur item type file type c part file file reinterpret cast c part file cur item value if file is part file mycat file get category if mycat min from to mycat max from to if mycat from file set category to else if from to file set category mycat 1 else file set category mycat 1 cdownloadlistctrl movecompletedfilescat listitems m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item ispartfile getcategory setcategory setcategory setcategory int c download list ctrl get complete downloads int cat int total total 0 int count 0 for list items const iterator it m listitems begin it m listitems end it const ctrlitem struct cur item it second if cur item type file type const c part file file reinterpret cast c part file cur item value if file check show item in given cat cat cat 1 total if file get status ps complete count return count cdownloadlistctrl getcompletedownloads listitems const_iterator m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item checkshowitemingivencat getstatus ps_complete void c download list ctrl update current category view change category cur tab cdownloadlistctrl updatecurrentcategoryview changecategory curtab void c download list ctrl update current category view c part file thisfile list items const iterator it m listitems find thisfile if it m listitems end const ctrlitem struct cur item it second if cur item type file type c part file file reinterpret cast c part file cur item value if file check show item in given cat cur tab hide file file else show file file cdownloadlistctrl updatecurrentcategoryview cpartfile listitems const_iterator m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile reinterpret_cast cpartfile cur_item checkshowitemingivencat curtab hidefile showfile void c download list ctrl show file dialog uint u invoke page c simple array c part file a files position pos get first selected item position while pos null int i item get next selected item pos if i item 1 const ctrlitem struct p ctrl item ctrlitem struct get item data i item if p ctrl item type file type a files add c part file p ctrl item value if a files get size 0 c download list list ctrl item walk set item type file type c file detail dialog dialog a files u invoke page this dialog do modal cdownloadlistctrl showfiledialog uinvokepage csimplearray cpartfile afiles getfirstselecteditemposition iitem getnextselecteditem iitem ctrlitem_struct pctrlitem ctrlitem_struct getitemdata iitem pctrlitem file_type afiles cpartfile pctrlitem afiles getsize cdownloadlistlistctrlitemwalk setitemtype file_type cfiledetaildialog afiles uinvokepage domodal void c download list ctrl show client dialog c up down client p client c download list list ctrl item walk set item type available source just set to something file type c client detail dialog dialog p client this dialog do modal cdownloadlistctrl showclientdialog cupdownclient pclient cdownloadlistlistctrlitemwalk setitemtype available_source file_type cclientdetaildialog pclient domodal void c download list ctrl set all icons m imagelist delete image list m imagelist create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 m imagelist set bk color clr none m imagelist add c temp icon loader t src downloading m imagelist add c temp icon loader t src on queue m imagelist add c temp icon loader t src connecting m imagelist add c temp icon loader t srcnnpqf m imagelist add c temp icon loader t src unknown m imagelist add c temp icon loader t client compatible m imagelist add c temp icon loader t friend m imagelist add c temp icon loader t cliente donkey m imagelist add c temp icon loader t clientml donkey m imagelist add c temp icon loader t cliente donkey hybrid m imagelist add c temp icon loader t client shareaza m imagelist add c temp icon loader t server m imagelist add c temp icon loader t clienta mule m imagelist add c temp icon loader t clientl phant m imagelist add c temp icon loader t rating notrated m imagelist add c temp icon loader t rating fake m imagelist add c temp icon loader t rating poor m imagelist add c temp icon loader t rating fair m imagelist add c temp icon loader t rating good m imagelist add c temp icon loader t rating excellent m imagelist set overlay image m imagelist add c temp icon loader t client secure ovl 1 cdownloadlistctrl setallicons m_imagelist deleteimagelist m_imagelist theapp m_idfltimagelistcolorflags ilc_mask m_imagelist setbkcolor clr_none m_imagelist ctempiconloader _t srcdownloading m_imagelist ctempiconloader _t srconqueue m_imagelist ctempiconloader _t srcconnecting m_imagelist ctempiconloader _t m_imagelist ctempiconloader _t srcunknown m_imagelist ctempiconloader _t clientcompatible m_imagelist ctempiconloader _t m_imagelist ctempiconloader _t clientedonkey m_imagelist ctempiconloader _t clientmldonkey m_imagelist ctempiconloader _t clientedonkeyhybrid m_imagelist ctempiconloader _t clientshareaza m_imagelist ctempiconloader _t m_imagelist ctempiconloader _t clientamule m_imagelist ctempiconloader _t clientlphant m_imagelist ctempiconloader _t rating_notrated m_imagelist ctempiconloader _t rating_fake m_imagelist ctempiconloader _t rating_poor m_imagelist ctempiconloader _t rating_fair m_imagelist ctempiconloader _t rating_good m_imagelist ctempiconloader _t rating_excellent m_imagelist setoverlayimage m_imagelist ctempiconloader _t clientsecureovl void c download list ctrl draw file item cdc dc int n column lpcrect lp rect ctrlitem struct lp ctrl item if lp rect left lp rect right c string buffer const c part file lp part file c part file lp ctrl item value switch n column case 0 file name c rect rc draw lp rect int i image the app get file type system image idx lp part file get file name if the app get system image list null imagelist draw the app get system image list i image dc get safe hdc rc draw left rc draw top ild normal ild transparent rc draw left the app get small sytem icon size cx if the prefs show rating indicator lp part file has comment lp part file has rating m imagelist draw dc lp part file user rating 14 rc draw top left ild normal rc draw left rating icon width rc draw left 3 dc draw text lp part file get file name lp part file get file name get length rc draw dlc dt text break case 1 size buffer cast itox bytes lp part file get file size false false dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 2 transferred buffer cast itox bytes lp part file get transferred false false dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 3 transferred complete buffer cast itox bytes lp part file get completed size false false dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 4 speed if lp part file get transferring src count buffer format t s cast itox bytes lp part file get datarate false true dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 5 progress c rect rc draw lp rect rc draw bottom rc draw top added int i width rc draw width int i height rc draw height if lp ctrl item status hbitmap null verify lp ctrl item status create bitmap 1 1 1 8 null cdc cdc status hgdiobj h old bitmap cdc status create compatibledc dc int cx lp ctrl item status get bitmap dimension cx dword dw ticks get tick count if lp ctrl item dw updated dlc barupdate dw ticks cx i width lp ctrl item dw updated lp ctrl item status delete object lp ctrl item status create compatible bitmap dc i width i height lp ctrl item status set bitmap dimension i width i height h old bitmap cdc status select object lp ctrl item status rect rec status rec status left 0 rec status top 0 rec status bottom i height rec status right i width lp part file draw status bar cdc status rec status the prefs use flat bar lp ctrl item dw updated dw ticks rand 128 else h old bitmap cdc status select object lp ctrl item status dc bit blt rc draw left rc draw top i width i height cdc status 0 0 srccopy cdc status select object h old bitmap added end if the prefs get use dwl percentage hoax 69 begin display percent in progress bar colorref oldclr dc set text color rgb 255 255 255 int io mode dc set bk mode transparent buffer format t 1f lp part file get percent completed dc draw text buffer buffer get length rc draw dlc dt text dt left dt center dc set bk mode io mode dc set text color oldclr hoax 69 end break case 6 sources uint sc lp part file get source count uint ncsc lp part file get not current sources count zz download manager if lp part file get status ps paused sc 0 lp part file get status ps complete buffer format t i sc ncsc if ncsc 0 buffer append format t i sc if the prefs is ext controls enabled lp part file get srca4af count 0 buffer append format t i lp part file get srca4af count if lp part file get transferring src count 0 buffer append format t i lp part file get transferring src count else buffer t zz download manager if the prefs is ext controls enabled lp part file get private max sources 0 buffer append format t i lp part file get private max sources dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 7 prio switch lp part file get down priority case pr low if lp part file is auto down priority dc draw text get res string ids prioautolow get res string ids prioautolow get length const cast lprect lp rect dlc dt text else dc draw text get res string ids priolow get res string ids priolow get length const cast lprect lp rect dlc dt text break case pr normal if lp part file is auto down priority dc draw text get res string ids prioautonormal get res string ids prioautonormal get length const cast lprect lp rect dlc dt text else dc draw text get res string ids prionormal get res string ids prionormal get length const cast lprect lp rect dlc dt text break case pr high if lp part file is auto down priority dc draw text get res string ids prioautohigh get res string ids prioautohigh get length const cast lprect lp rect dlc dt text else dc draw text get res string ids priohigh get res string ids priohigh get length const cast lprect lp rect dlc dt text break break case 8 9 21 02 buffer lp part file get partfile status dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 9 remaining time size if lp part file get status ps completing lp part file get status ps complete time time t rest time if the prefs use simple time remaining computation rest time lp part file get time remaining else rest time lp part file get time remaining simple buffer format t s s cast seconds tohm rest time cast itox bytes lp part file get file size lp part file get completed size false false dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 10 last seen complete c string tempbuffer if lp part file m ncompletesourcescountlo 0 tempbuffer format t u lp part file m ncompletesourcescounthi else if lp part file m ncompletesourcescountlo lp part file m ncompletesourcescounthi tempbuffer format t u lp part file m ncompletesourcescountlo else tempbuffer format t u u lp part file m ncompletesourcescountlo lp part file m ncompletesourcescounthi if lp part file lastseencomplete null buffer format t s s get res string ids never tempbuffer else buffer format t s s lp part file lastseencomplete format the prefs get date time format tempbuffer dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 11 last receive if is column hidden 11 if lp part file get file date null lp part file get completed size uint64 0 buffer lp part file getc file date format the prefs get date time format else buffer format t s get res string ids never dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 12 cat if is column hidden 12 buffer lp part file get category 0 the prefs get category lp part file get category title t dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break cdownloadlistctrl drawfileitem ncolumn lprect ctrlitem_struct lpctrlitem lprect lprect cstring cpartfile lppartfile cpartfile lpctrlitem ncolumn crect rcdraw lprect iimage theapp getfiletypesystemimageidx lppartfile getfilename theapp getsystemimagelist imagelist_draw theapp getsystemimagelist iimage getsafehdc rcdraw rcdraw ild_normal ild_transparent rcdraw theapp getsmallsytemiconsize theprefs showratingindicator lppartfile hascomment lppartfile hasrating m_imagelist lppartfile userrating rcdraw topleft ild_normal rcdraw rating_icon_width rcdraw drawtext lppartfile getfilename lppartfile getfilename getlength rcdraw dlc_dt_text castitoxbytes lppartfile getfilesize drawtext getlength const_cast lprect dlc_dt_text dt_right castitoxbytes lppartfile gettransferred drawtext getlength const_cast lprect dlc_dt_text dt_right castitoxbytes lppartfile getcompletedsize drawtext getlength const_cast lprect dlc_dt_text dt_right lppartfile gettransferringsrccount _t castitoxbytes lppartfile getdatarate drawtext getlength const_cast lprect dlc_dt_text dt_right crect rcdraw lprect rcdraw rcdraw iwidth rcdraw iheight rcdraw lpctrlitem lpctrlitem createbitmap cdcstatus holdbitmap cdcstatus createcompatibledc lpctrlitem getbitmapdimension dwticks gettickcount lpctrlitem dwupdated dlc_barupdate dwticks iwidth lpctrlitem dwupdated lpctrlitem deleteobject lpctrlitem createcompatiblebitmap iwidth iheight lpctrlitem setbitmapdimension iwidth iheight holdbitmap cdcstatus selectobject lpctrlitem rec_status rec_status rec_status rec_status iheight rec_status iwidth lppartfile drawstatusbar cdcstatus rec_status theprefs useflatbar lpctrlitem dwupdated dwticks holdbitmap cdcstatus selectobject lpctrlitem bitblt rcdraw rcdraw iwidth iheight cdcstatus cdcstatus selectobject holdbitmap theprefs getusedwlpercentage hoax_69 settextcolor iomode setbkmode _t lppartfile getpercentcompleted drawtext getlength rcdraw dlc_dt_text dt_left dt_center setbkmode iomode settextcolor hoax_69 lppartfile getsourcecount lppartfile getnotcurrentsourcescount downloadmanager lppartfile getstatus ps_paused lppartfile getstatus ps_complete _t appendformat _t theprefs isextcontrolsenabled lppartfile getsrca4afcount appendformat _t lppartfile getsrca4afcount lppartfile gettransferringsrccount appendformat _t lppartfile gettransferringsrccount _t downloadmanager theprefs isextcontrolsenabled lppartfile getprivatemaxsources appendformat _t lppartfile getprivatemaxsources drawtext getlength const_cast lprect dlc_dt_text dt_right lppartfile getdownpriority pr_low lppartfile isautodownpriority drawtext getresstring ids_prioautolow getresstring ids_prioautolow getlength const_cast lprect dlc_dt_text drawtext getresstring ids_priolow getresstring ids_priolow getlength const_cast lprect dlc_dt_text pr_normal lppartfile isautodownpriority drawtext getresstring ids_prioautonormal getresstring ids_prioautonormal getlength const_cast lprect dlc_dt_text drawtext getresstring ids_prionormal getresstring ids_prionormal getlength const_cast lprect dlc_dt_text pr_high lppartfile isautodownpriority drawtext getresstring ids_prioautohigh getresstring ids_prioautohigh getlength const_cast lprect dlc_dt_text drawtext getresstring ids_priohigh getresstring ids_priohigh getlength const_cast lprect dlc_dt_text lppartfile getpartfilestatus drawtext getlength const_cast lprect dlc_dt_text lppartfile getstatus ps_completing lppartfile getstatus ps_complete time_t resttime theprefs usesimpletimeremainingcomputation resttime lppartfile gettimeremaining resttime lppartfile gettimeremainingsimple _t castsecondstohm resttime castitoxbytes lppartfile getfilesize lppartfile getcompletedsize drawtext getlength const_cast lprect dlc_dt_text cstring lppartfile m_ncompletesourcescountlo _t lppartfile m_ncompletesourcescounthi lppartfile m_ncompletesourcescountlo lppartfile m_ncompletesourcescounthi _t lppartfile m_ncompletesourcescountlo _t lppartfile m_ncompletesourcescountlo lppartfile m_ncompletesourcescounthi lppartfile _t getresstring ids_never _t lppartfile theprefs getdatetimeformat drawtext getlength const_cast lprect dlc_dt_text iscolumnhidden lppartfile getfiledate lppartfile getcompletedsize lppartfile getcfiledate theprefs getdatetimeformat _t getresstring ids_never drawtext getlength const_cast lprect dlc_dt_text iscolumnhidden lppartfile getcategory theprefs getcategory lppartfile getcategory _t drawtext getlength const_cast lprect dlc_dt_text void c download list ctrl draw source item cdc dc int n column lpcrect lp rect ctrlitem struct lp ctrl item if lp rect left lp rect right c string buffer c up down client lp up down client c up down client lp ctrl item value switch n column case 0 icon name status rect cur rec lp rect point point cur rec left cur rec top 1 if lp ctrl item type available source switch lp up down client get download state case ds connecting m imagelist draw dc 2 point ild normal break case ds connected m imagelist draw dc 2 point ild normal break case ds waitcallbackkad case ds waitcallback m imagelist draw dc 2 point ild normal break case ds onqueue if lp up down client is remote queue full m imagelist draw dc 3 point ild normal else m imagelist draw dc 1 point ild normal break case ds downloading m imagelist draw dc 0 point ild normal break case ds reqhashset m imagelist draw dc 0 point ild normal break case ds noneededparts m imagelist draw dc 3 point ild normal break case ds error m imagelist draw dc 3 point ild normal break case ds toomanyconns case ds toomanyconnskad m imagelist draw dc 2 point ild normal break default m imagelist draw dc 4 point ild normal else m imagelist draw dc 3 point ild normal cur rec left 20 uint u ovl img lp up down client credits lp up down client credits get current ident state lp up down client getip is identified indextooverlaymask 1 0 point point2 cur rec left cur rec top 1 if lp up down client is friend m imagelist draw dc 6 point2 ild normal u ovl img else if lp up down client get client soft so edonkeyhybrid m imagelist draw dc 9 point2 ild normal u ovl img else if lp up down client get client soft so mldonkey m imagelist draw dc 8 point2 ild normal u ovl img else if lp up down client get client soft so shareaza m imagelist draw dc 10 point2 ild normal u ovl img else if lp up down client get client soft so url m imagelist draw dc 11 point2 ild normal u ovl img else if lp up down client get client soft so amule m imagelist draw dc 12 point2 ild normal u ovl img else if lp up down client get client soft so lphant m imagelist draw dc 13 point2 ild normal u ovl img else if lp up down client ext protocol available m imagelist draw dc 5 point2 ild normal u ovl img else m imagelist draw dc 7 point2 ild normal u ovl img cur rec left 20 if lp up down client get user name buffer t else buffer lp up down client get user name dc draw text buffer buffer get length cur rec dlc dt text break case 1 size switch lp up down client get source from case sf server buffer t ed2k server break case sf kademlia buffer get res string ids kademlia break case sf source exchange buffer get res string ids se break case sf passive buffer get res string ids passive break case sf link buffer get res string ids sw link break dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 2 transferred case 3 completed transferred column show transferred data completed column if transferred column is hidden show the amount of transferred data in completed column this is plain wrong at least when receiving compressed data but users seem to got used to it if n column 2 is column hidden 2 if lp ctrl item type available source lp up down client get transferred down buffer cast itox bytes lp up down client get transferred down false false dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 4 speed if lp ctrl item type available source lp up down client get download datarate if lp up down client get download datarate buffer format t s cast itox bytes lp up down client get download datarate false true dc draw text buffer buffer get length const cast lprect lp rect dlc dt text dt right break case 5 file info c rect rc draw lp rect rc draw bottom rc draw top int i width rc draw width int i height rc draw height if lp ctrl item status hbitmap null verify lp ctrl item status create bitmap 1 1 1 8 null cdc cdc status hgdiobj h old bitmap cdc status create compatibledc dc int cx lp ctrl item status get bitmap dimension cx dword dw ticks get tick count if lp ctrl item dw updated dlc barupdate dw ticks cx i width lp ctrl item dw updated lp ctrl item status delete object lp ctrl item status create compatible bitmap dc i width i height lp ctrl item status set bitmap dimension i width i height h old bitmap cdc status select object lp ctrl item status rect rec status rec status left 0 rec status top 0 rec status bottom i height rec status right i width lp up down client draw status bar cdc status rec status lp ctrl item type unavailable source the prefs use flat bar lp ctrl item dw updated dw ticks rand 128 else h old bitmap cdc status select object lp ctrl item status dc bit blt rc draw left rc draw top i width i height cdc status 0 0 srccopy cdc status select object h old bitmap break case 6 sources buffer lp up down client get client soft ver if buffer is empty buffer get res string ids unknown c rect rc lp rect dc draw text buffer buffer get length rc dlc dt text break case 7 prio if lp up down client get download state ds onqueue if lp up down client is remote queue full buffer get res string ids queuefull dc draw text buffer buffer get length const cast lprect lp rect dlc dt text else if lp up down client get remote queue rank buffer format t qr u lp up down client get remote queue rank dc draw text buffer buffer get length const cast lprect lp rect dlc dt text else dc draw text buffer buffer get length const cast lprect lp rect dlc dt text else dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 8 status if lp ctrl item type available source buffer lp up down client get download state display string else buffer get res string ids asked4anotherfile zz download manager if the prefs is ext controls enabled if lp up down client is in no needed list lp ctrl item owner buffer t get res string ids noneededparts t else if lp up down client get download state ds downloading buffer t get res string ids transferring t else if lp up down client is swap suspended lp up down client get request file buffer t get res string ids sourceswapblocked t if lp up down client lp up down client get request file lp up down client get request file get file name buffer append format t s lp up down client get request file get file name if the prefs is ext controls enabled lp up down client m otherrequests list is empty buffer append t zz download manager dc draw text buffer buffer get length const cast lprect lp rect dlc dt text break case 9 remaining time size break case 10 last seen complete break case 11 last received break case 12 category break cdownloadlistctrl drawsourceitem ncolumn lprect ctrlitem_struct lpctrlitem lprect lprect cstring cupdownclient lpupdownclient cupdownclient lpctrlitem ncolumn cur_rec lprect cur_rec cur_rec lpctrlitem available_source lpupdownclient getdownloadstate ds_connecting m_imagelist ild_normal ds_connected m_imagelist ild_normal ds_waitcallbackkad ds_waitcallback m_imagelist ild_normal ds_onqueue lpupdownclient isremotequeuefull m_imagelist ild_normal m_imagelist ild_normal ds_downloading m_imagelist ild_normal ds_reqhashset m_imagelist ild_normal ds_noneededparts m_imagelist ild_normal ds_error m_imagelist ild_normal ds_toomanyconns ds_toomanyconnskad m_imagelist ild_normal m_imagelist ild_normal m_imagelist ild_normal cur_rec uovlimg lpupdownclient lpupdownclient getcurrentidentstate lpupdownclient is_identified cur_rec cur_rec lpupdownclient isfriend m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_edonkeyhybrid m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_mldonkey m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_shareaza m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_url m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_amule m_imagelist ild_normal uovlimg lpupdownclient getclientsoft so_lphant m_imagelist ild_normal uovlimg lpupdownclient extprotocolavailable m_imagelist ild_normal uovlimg m_imagelist ild_normal uovlimg cur_rec lpupdownclient getusername _t lpupdownclient getusername drawtext getlength cur_rec dlc_dt_text lpupdownclient getsourcefrom sf_server _t sf_kademlia getresstring ids_kademlia sf_source_exchange getresstring ids_se sf_passive getresstring ids_passive sf_link getresstring ids_sw_link drawtext getlength const_cast lprect dlc_dt_text ncolumn iscolumnhidden lpctrlitem available_source lpupdownclient gettransferreddown castitoxbytes lpupdownclient gettransferreddown drawtext getlength const_cast lprect dlc_dt_text dt_right lpctrlitem available_source lpupdownclient getdownloaddatarate lpupdownclient getdownloaddatarate _t castitoxbytes lpupdownclient getdownloaddatarate drawtext getlength const_cast lprect dlc_dt_text dt_right crect rcdraw lprect rcdraw rcdraw iwidth rcdraw iheight rcdraw lpctrlitem lpctrlitem createbitmap cdcstatus holdbitmap cdcstatus createcompatibledc lpctrlitem getbitmapdimension dwticks gettickcount lpctrlitem dwupdated dlc_barupdate dwticks iwidth lpctrlitem dwupdated lpctrlitem deleteobject lpctrlitem createcompatiblebitmap iwidth iheight lpctrlitem setbitmapdimension iwidth iheight holdbitmap cdcstatus selectobject lpctrlitem rec_status rec_status rec_status rec_status iheight rec_status iwidth lpupdownclient drawstatusbar cdcstatus rec_status lpctrlitem unavailable_source theprefs useflatbar lpctrlitem dwupdated dwticks holdbitmap cdcstatus selectobject lpctrlitem bitblt rcdraw rcdraw iwidth iheight cdcstatus cdcstatus selectobject holdbitmap lpupdownclient getclientsoftver isempty getresstring ids_unknown crect lprect drawtext getlength dlc_dt_text lpupdownclient getdownloadstate ds_onqueue lpupdownclient isremotequeuefull getresstring ids_queuefull drawtext getlength const_cast lprect dlc_dt_text lpupdownclient getremotequeuerank _t lpupdownclient getremotequeuerank drawtext getlength const_cast lprect dlc_dt_text drawtext getlength const_cast lprect dlc_dt_text drawtext getlength const_cast lprect dlc_dt_text lpctrlitem available_source lpupdownclient getdownloadstatedisplaystring getresstring ids_asked4anotherfile downloadmanager theprefs isextcontrolsenabled lpupdownclient isinnoneededlist lpctrlitem _t getresstring ids_noneededparts _t lpupdownclient getdownloadstate ds_downloading _t getresstring ids_transferring _t lpupdownclient isswapsuspended lpupdownclient getrequestfile _t getresstring ids_sourceswapblocked _t lpupdownclient lpupdownclient getrequestfile lpupdownclient getrequestfile getfilename appendformat _t lpupdownclient getrequestfile getfilename theprefs isextcontrolsenabled lpupdownclient m_otherrequests_list isempty _t downloadmanager drawtext getlength const_cast lprect dlc_dt_text int c download list ctrl get files count in cur cat int i count 0 for list items const iterator it m listitems begin it m listitems end it ctrlitem struct cur item it second if cur item type file type c part file file c part file cur item value if file check show item in given cat cur tab i count return i count cdownloadlistctrl getfilescountincurcat icount listitems const_iterator m_listitems m_listitems ctrlitem_struct cur_item cur_item file_type cpartfile cpartfile cur_item checkshowitemingivencat curtab icount icount int c download list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort ctrlitem struct item1 ctrlitem struct l param1 ctrlitem struct item2 ctrlitem struct l param2 int dw org sort l param sort int sort mod 1 if l param sort 100 sort mod 1 l param sort 100 int comp if item1 type file type item2 type file type if item1 value item2 parent value return 1 comp compare c part file item1 value c part file item2 parent value l param sort else if item2 type file type item1 type file type if item1 parent value item2 value return 1 comp compare c part file item1 parent value c part file item2 value l param sort else if item1 type file type c part file file1 c part file item1 value c part file file2 c part file item2 value comp compare file1 file2 l param sort else if item1 parent value item2 parent value comp compare c part file item1 parent value c part file item2 parent value l param sort return sort mod comp if item1 type item2 type return item1 type item2 type c up down client client1 c up down client item1 value c up down client client2 c up down client item2 value comp compare client1 client2 l param sort int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if comp 0 dw next sort the app emuledlg transferwnd downloadlistctrl get next sort order dw org sort 1 return sort proc l param1 l param2 dw next sort else return sort mod comp cdownloadlistctrl sortproc lparam1 lparam2 lparamsort ctrlitem_struct ctrlitem_struct lparam1 ctrlitem_struct ctrlitem_struct lparam2 dworgsort lparamsort sortmod lparamsort sortmod lparamsort file_type file_type cpartfile cpartfile lparamsort file_type file_type cpartfile cpartfile lparamsort file_type cpartfile cpartfile cpartfile cpartfile lparamsort cpartfile cpartfile lparamsort sortmod cupdownclient cupdownclient cupdownclient cupdownclient lparamsort dwnextsort dwnextsort theapp getnextsortorder dworgsort sortproc lparam1 lparam2 dwnextsort sortmod int c download list ctrl compare const c part file file1 const c part file file2 lparam l param sort int comp 0 switch l param sort case 0 filename asc comp compare locale string no case file1 get file name file2 get file name break case 1 size asc comp compare unsigned64 file1 get file size file2 get file size break case 2 transferred asc comp compare unsigned64 file1 get transferred file2 get transferred break case 3 completed asc comp compare unsigned64 file1 get completed size file2 get completed size break case 4 speed asc comp compare unsigned file1 get datarate file2 get datarate break case 5 progress asc comp compare float file1 get percent completed file2 get percent completed break case 6 sources asc comp compare unsigned file1 get source count file2 get source count break case 7 priority asc comp compare unsigned file1 get down priority file2 get down priority break case 8 status asc comp compare unsigned file1 get partfile status rang file2 get partfile status rang break case 9 remaining time asc make ascending sort so we can have the smaller remaining time on the top instead of unknowns so we can see which files are about to finish better time t f1 file1 get time remaining time t f2 file2 get time remaining same do nothing if f1 f2 comp 0 break if descending put first on top as it is unknown if ascending put first on bottom as it is unknown if f1 1 comp 1 break if descending put second on top as it is unknown if ascending put second on bottom as it is unknown if f2 1 comp 1 break if descending put first on top as it is bigger if ascending put first on bottom as it is bigger comp compare unsigned f1 f2 break case 90 remaining size asc comp compare unsigned64 file1 get file size file1 get completed size file2 get file size file2 get completed size break case 10 last seen complete asc if file1 lastseencomplete file2 lastseencomplete comp 1 else if file1 lastseencomplete file2 lastseencomplete comp 1 else comp 0 break case 11 last received time asc if file1 get file date file2 get file date comp 1 else if file1 get file date file2 get file date comp 1 else comp 0 break case 12 todo get category should be a const function and get res string should not be called comp compare locale string no case const cast c part file file1 get category 0 the prefs get category const cast c part file file1 get category title get res string ids all const cast c part file file2 get category 0 the prefs get category const cast c part file file2 get category title get res string ids all break default comp 0 return comp cdownloadlistctrl cpartfile cpartfile lparamsort lparamsort comparelocalestringnocase getfilename getfilename compareunsigned64 getfilesize getfilesize compareunsigned64 gettransferred gettransferred compareunsigned64 getcompletedsize getcompletedsize compareunsigned getdatarate getdatarate comparefloat getpercentcompleted getpercentcompleted compareunsigned getsourcecount getsourcecount compareunsigned getdownpriority getdownpriority compareunsigned getpartfilestatusrang getpartfilestatusrang time_t gettimeremaining time_t gettimeremaining compareunsigned compareunsigned64 getfilesize getcompletedsize getfilesize getcompletedsize getfiledate getfiledate getfiledate getfiledate getcategory getresstring comparelocalestringnocase const_cast cpartfile getcategory theprefs getcategory const_cast cpartfile getcategory getresstring ids_all const_cast cpartfile getcategory theprefs getcategory const_cast cpartfile getcategory getresstring ids_all int c download list ctrl compare const c up down client client1 const c up down client client2 lparam l param sort switch l param sort case 0 name asc if client1 get user name client2 get user name return 0 else if client1 get user name place clients with no usernames at bottom return 1 else if client2 get user name place clients with no usernames at bottom return 1 return compare locale string no case client1 get user name client2 get user name case 1 size but we use status asc return client1 get source from client2 get source from case 2 transferred asc case 3 completed asc return compare unsigned client1 get transferred down client2 get transferred down case 4 speed asc return compare unsigned client1 get download datarate client2 get download datarate case 5 progress asc return compare unsigned client1 get available part count client2 get available part count case 6 if client1 get client soft client2 get client soft return compare unsigned client2 get version client1 get version return compare unsigned client1 get client soft client2 get client soft case 7 qr asc if client1 get download state ds downloading if client2 get download state ds downloading return 0 else return 1 else if client2 get download state ds downloading return 1 if client1 get remote queue rank 0 client1 get download state ds onqueue client1 is remote queue full true return 1 if client2 get remote queue rank 0 client2 get download state ds onqueue client2 is remote queue full true return 1 if client1 get remote queue rank 0 return 1 if client2 get remote queue rank 0 return 1 return compare unsigned client1 get remote queue rank client2 get remote queue rank case 8 if client1 get download state client2 get download state if client1 is remote queue full client2 is remote queue full return 0 else if client1 is remote queue full return 1 else if client2 is remote queue full return 1 return client1 get download state client2 get download state default return 0 cdownloadlistctrl cupdownclient cupdownclient lparamsort lparamsort getusername getusername getusername getusername comparelocalestringnocase getusername getusername getsourcefrom getsourcefrom compareunsigned gettransferreddown gettransferreddown compareunsigned getdownloaddatarate getdownloaddatarate compareunsigned getavailablepartcount getavailablepartcount getclientsoft getclientsoft compareunsigned getversion getversion compareunsigned getclientsoft getclientsoft getdownloadstate ds_downloading getdownloadstate ds_downloading getdownloadstate ds_downloading getremotequeuerank getdownloadstate ds_onqueue isremotequeuefull getremotequeuerank getdownloadstate ds_onqueue isremotequeuefull getremotequeuerank getremotequeuerank compareunsigned getremotequeuerank getremotequeuerank getdownloadstate getdownloadstate isremotequeuefull isremotequeuefull isremotequeuefull isremotequeuefull getdownloadstate getdownloadstate bool c download list ctrl on command wparam w param lparam l param w param loword w param switch w param case mp paste if the app is ed2k file link in clipboard the app paste clipboard cur tab return true case mp find on find start return true int i sel get next item 1 lvis selected lvis focused if i sel 1 i sel get next item 1 lvis selected if i sel 1 const ctrlitem struct content ctrlitem struct get item data i sel if content type file type for multiple selections uint selected count 0 c typed ptr list c ptr list c part file selected list position pos get first selected item position while pos null int index get next selected item pos if index 1 if const ctrlitem struct get item data index type file type selected count selected list add tail c part file const ctrlitem struct get item data index value c part file file c part file content value switch w param case mpg delete keyboard del will continue to remove completed files from the screen while cancel will now also be available for complete files case mp cancel if selected count 0 set redraw false c string file list bool validdelete false bool removecompl false for pos selected list get head position pos 0 c part file cur file selected list get next pos if cur file get status ps completing cur file get status ps complete w param mp cancel validdelete true if selected count 50 file list append t n c string cur file get file name else if cur file get status ps complete removecompl true c string quest if selected count 1 quest get res string ids q canceldl2 else quest get res string ids q canceldl if removecompl validdelete validdelete afx message box quest file list mb defbutton2 mb iconquestion mb yesno idyes bool b removed items false while selected list is empty hide sources selected list get head switch selected list get head get status case ps waitingforhash case ps hashing case ps completing selected list remove head b removed items true break case ps complete if w param mp cancel bool delsucc false if path file exists selected list get head get file path delsucc true else delete if the prefs get remove to bin delsucc delete file selected list get head get file path else delete to recycle bin tchar todel max path 1 memset todel 0 sizeof todel tcsncpy todel selected list get head get file path arrsize todel 2 shfileopstruct fp 0 fp w func fo delete fp hwnd the app emuledlg m hwnd fp p from todel fp f flags fof allowundo fof noconfirmation fof silent fof noerrorui delsucc sh file operation fp 0 if delsucc the app sharedfiles remove file selected list get head else c string str error str error format get res string ids err delfile t r n r n s selected list get head get file path get error message get last error afx message box str error remove file selected list get head selected list remove head b removed items true break case ps paused selected list get head delete file selected list remove head b removed items true break default if selected list get head get category the app downloadqueue start next file if prefs selected list get head get category selected list get head delete file selected list remove head b removed items true if b removed items auto select item the app emuledlg transferwnd update cat tab titles set redraw true break case mp priohigh set redraw false while selected list is empty c part file partfile selected list get head partfile set auto down priority false partfile set down priority pr high selected list remove head set redraw true break case mp priolow set redraw false while selected list is empty c part file partfile selected list get head partfile set auto down priority false partfile set down priority pr low selected list remove head set redraw true break case mp prionormal set redraw false while selected list is empty c part file partfile selected list get head partfile set auto down priority false partfile set down priority pr normal selected list remove head set redraw true break case mp prioauto set redraw false while selected list is empty c part file partfile selected list get head partfile set auto down priority true partfile set down priority pr high selected list remove head set redraw true break case mp pause set redraw false while selected list is empty c part file partfile selected list get head if partfile can pause file partfile pause file selected list remove head set redraw true break case mp resume set redraw false while selected list is empty c part file partfile selected list get head if partfile can resume file if partfile get status ps insufficient partfile resume file insufficient else partfile resume file selected list remove head set redraw true break case mp stop set redraw false while selected list is empty c part file partfile selected list get head if partfile can stop file hide sources partfile partfile stop file selected list remove head set redraw true the app emuledlg transferwnd update cat tab titles break case mp clearcompleted set redraw false clear completed set redraw true break case mpg f2 if get async key state vk control 0 selected count 1 when ctrl is pressed filename cleanup if idyes afx message box get res string ids manual filenamecleanup mb yesno while selected list is empty c part file partfile selected list get head if partfile is part file partfile set file name cleanup filename partfile get file name selected list remove head else if file get status ps complete file get status ps completing input box inputbox c string title get res string ids rename title remove t inputbox set labels title get res string ids dl filename file get file name inputbox set edit filename mode if inputbox do modal idok inputbox get input is empty is valid ed2k string inputbox get input file set file name inputbox get input true file update displayed info file save part file else message beep mb ok break case mp metinfo case mpg altenter show file dialog 0 break case mp copyselected case mp geted2klink c string str while selected list is empty if str is empty str t r n str createed2k link selected list get head selected list remove head the app copy text to clipboard str break case mp searchrelated if selected count 1 break the app emuledlg searchwnd search related files file the app emuledlg set active dialog the app emuledlg searchwnd break case mp open case ida enter if selected count 1 break if file can open file file open file break case mp try to get preview parts if selected count 1 break file set preview prio file get preview prio break case mp preview if selected count 1 break file preview file break case mp viewfilecomments show file dialog idd commentlst break case mp showed2klink show file dialog idd ed2klink break case mp setsourcelimit c string temp temp format t u file get private max sources input box inputbox c string title get res string ids setpfslimit inputbox set labels title get res string ids setpfslimitexplained temp if inputbox do modal idok temp inputbox get input int newlimit tstoi temp while selected list is empty c part file partfile selected list get head partfile set private max sources newlimit selected list remove head partfile update displayed info true break case mp addsource if selected count 1 break c add source dlg as as set file file as do modal break cdownloadlistctrl oncommand wparam lparam wparam wparam wparam mp_paste theapp ised2kfilelinkinclipboard theapp pasteclipboard curtab mp_find onfindstart isel getnextitem lvis_selected lvis_focused isel isel getnextitem lvis_selected isel ctrlitem_struct ctrlitem_struct getitemdata isel file_type selectedcount ctypedptrlist cptrlist cpartfile selectedlist getfirstselecteditemposition getnextselecteditem ctrlitem_struct getitemdata file_type selectedcount selectedlist addtail cpartfile ctrlitem_struct getitemdata cpartfile cpartfile wparam mpg_delete mp_cancel selectedcount setredraw cstring filelist selectedlist getheadposition cpartfile cur_file selectedlist getnext cur_file getstatus ps_completing cur_file getstatus ps_complete wparam mp_cancel selectedcount filelist _t cstring cur_file getfilename cur_file getstatus ps_complete cstring selectedcount getresstring ids_q_canceldl2 getresstring ids_q_canceldl afxmessagebox filelist mb_defbutton2 mb_iconquestion mb_yesno bremoveditems selectedlist isempty hidesources selectedlist gethead selectedlist gethead getstatus ps_waitingforhash ps_hashing ps_completing selectedlist removehead bremoveditems ps_complete wparam mp_cancel pathfileexists selectedlist gethead getfilepath theprefs getremovetobin deletefile selectedlist gethead getfilepath max_path _tcsncpy selectedlist gethead getfilepath wfunc fo_delete theapp m_hwnd pfrom fflags fof_allowundo fof_noconfirmation fof_silent fof_noerrorui shfileoperation theapp removefile selectedlist gethead cstring strerror strerror getresstring ids_err_delfile _t selectedlist gethead getfilepath geterrormessage getlasterror afxmessagebox strerror removefile selectedlist gethead selectedlist removehead bremoveditems ps_paused selectedlist gethead deletefile selectedlist removehead bremoveditems selectedlist gethead getcategory theapp startnextfileifprefs selectedlist gethead getcategory selectedlist gethead deletefile selectedlist removehead bremoveditems bremoveditems autoselectitem theapp updatecattabtitles setredraw mp_priohigh setredraw selectedlist isempty cpartfile selectedlist gethead setautodownpriority setdownpriority pr_high selectedlist removehead setredraw mp_priolow setredraw selectedlist isempty cpartfile selectedlist gethead setautodownpriority setdownpriority pr_low selectedlist removehead setredraw mp_prionormal setredraw selectedlist isempty cpartfile selectedlist gethead setautodownpriority setdownpriority pr_normal selectedlist removehead setredraw mp_prioauto setredraw selectedlist isempty cpartfile selectedlist gethead setautodownpriority setdownpriority pr_high selectedlist removehead setredraw mp_pause setredraw selectedlist isempty cpartfile selectedlist gethead canpausefile pausefile selectedlist removehead setredraw mp_resume setredraw selectedlist isempty cpartfile selectedlist gethead canresumefile getstatus ps_insufficient resumefileinsufficient resumefile selectedlist removehead setredraw mp_stop setredraw selectedlist isempty cpartfile selectedlist gethead canstopfile hidesources stopfile selectedlist removehead setredraw theapp updatecattabtitles mp_clearcompleted setredraw clearcompleted setredraw mpg_f2 getasynckeystate vk_control selectedcount afxmessagebox getresstring ids_manual_filenamecleanup mb_yesno selectedlist isempty cpartfile selectedlist gethead ispartfile setfilename cleanupfilename getfilename selectedlist removehead getstatus ps_complete getstatus ps_completing inputbox cstring getresstring ids_rename _t setlabels getresstring ids_dl_filename getfilename seteditfilenamemode domodal getinput isempty isvalided2kstring getinput setfilename getinput updatedisplayedinfo savepartfile messagebeep mb_ok mp_metinfo mpg_altenter showfiledialog mp_copyselected mp_geted2klink cstring selectedlist isempty isempty _t createed2klink selectedlist gethead selectedlist removehead theapp copytexttoclipboard mp_searchrelated selectedcount theapp searchrelatedfiles theapp setactivedialog theapp mp_open ida_enter selectedcount canopenfile openfile mp_try_to_get_preview_parts selectedcount setpreviewprio getpreviewprio mp_preview selectedcount previewfile mp_viewfilecomments showfiledialog idd_commentlst mp_showed2klink showfiledialog idd_ed2klink mp_setsourcelimit cstring _t getprivatemaxsources inputbox cstring getresstring ids_setpfslimit setlabels getresstring ids_setpfslimitexplained domodal getinput _tstoi selectedlist isempty cpartfile selectedlist gethead setprivatemaxsources selectedlist removehead updatedisplayedinfo mp_addsource selectedcount caddsourcedlg setfile domodal void c download list ctrl draw item lpdrawitemstruct lp draw item struct if the app emuledlg is running return if lp draw item struct item data return cdc odc cdc from handle lp draw item struct hdc bool b ctrl focused get focus this get style lvs showselalways if lp draw item struct item state ods selected if b ctrl focused odc set bk color m crhighlight else odc set bk color m crnohighlight else odc set bk color get bk color ctrlitem struct content ctrlitem struct lp draw item struct item data c memdc dc odc lp draw item struct rc item c font p old font if m fontbold m hobject if content type file type if const c part file content value get transferring src count p old font dc select object m fontbold else p old font dc select object get font else if content type unavailable source content type available source if const c up down client content value get download state ds downloading p old font dc select object m fontbold else p old font dc select object get font else p old font dc select object get font else p old font dc select object get font c rect cur rec lp draw item struct rc item colorref cr old text color dc set text color lp draw item struct item state ods selected m crhighlighttext m crwindowtext int i old bk mode if m crwindowtextbk clr none def window proc wm erasebkgnd wparam hdc dc 0 i old bk mode dc set bk mode transparent else i old bk mode opaque bool not last lp draw item struct itemid 1 uint get item count bool not first lp draw item struct itemid 0 int tree start 0 int tree end 0 offset was 4 now it s the standard 2 spaces int i tree offset dc get text extent t 1 cx 2 c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count cur rec right cur rec left cur rec right file item margin x cur rec left file item margin x if content type file type if g blowcolordesktop lp draw item struct item state ods selected 0 dword dw cat color the prefs get cat color const c part file content value get category if dw cat color 0 dc set text color dw cat color for int i current 0 i current i count i current int i column p header ctrl order to index i current int cx c list ctrl get column width i column if i column 5 int i next left cur rec left cx set up tree vars cur rec left cur rec right i tree offset cur rec right cur rec left min 8 cx tree start cur rec left 1 tree end cur rec right normal column stuff cur rec left cur rec right 1 cur rec right tree start cx i tree offset draw file item dc 5 cur rec content cur rec left i next left else cur rec right cx draw file item dc i column cur rec content cur rec left cx else if content type unavailable source content type available source for int i current 0 i current i count i current int i column p header ctrl order to index i current int cx c list ctrl get column width i column if i column 5 int i next left cur rec left cx set up tree vars cur rec left cur rec right i tree offset cur rec right cur rec left min 8 cx tree start cur rec left 1 tree end cur rec right normal column stuff cur rec left cur rec right 1 cur rec right tree start cx i tree offset draw source item dc 5 cur rec content cur rec left i next left else cur rec right cx draw source item dc i column cur rec content cur rec left cx draw rectangle around selected item s if content type file type lp draw item struct item state ods selected rect outline rec lp draw item struct rc item outline rec top outline rec bottom dc frame rect outline rec c brush get bk color outline rec top outline rec bottom outline rec left outline rec right if not first get item state lp draw item struct itemid 1 lvis selected ctrlitem struct prev ctrlitem struct this get item data lp draw item struct itemid 1 if prev type file type outline rec top if not last get item state lp draw item struct itemid 1 lvis selected ctrlitem struct next ctrlitem struct this get item data lp draw item struct itemid 1 if next type file type outline rec bottom if b ctrl focused dc frame rect outline rec c brush m crfocusline else dc frame rect outline rec c brush m crnofocusline draw focus rectangle around non highlightable items when they have the focus else if lp draw item struct item state ods focus ods focus get focus this rect focus rec focus rec top lp draw item struct rc item top focus rec bottom lp draw item struct rc item bottom focus rec left lp draw item struct rc item left 1 focus rec right lp draw item struct rc item right 1 dc frame rect focus rec c brush m crnofocusline draw tree last so it draws over selected and focus looks better if tree start tree end set new bounds rect tree rect tree rect top lp draw item struct rc item top tree rect bottom lp draw item struct rc item bottom tree rect left tree start tree rect right tree end dc set bounds rect tree rect dcb disable gather some information bool has next not last ctrlitem struct this get item data lp draw item struct itemid 1 type file type bool is open root has next content type file type bool is child content type file type bool is expandable is child c part file content value get source count 0 might as well calculate these now int tree center tree start 3 int middle cur rec top cur rec bottom 1 2 set up a new pen for drawing the tree c pen pn oldpn pn create pen ps solid 1 m crwindowtext oldpn dc select object pn if is child draw the line to the status bar dc move to tree end middle dc line to tree start 3 middle draw the line to the child node if has next dc move to tree center middle dc line to tree center cur rec bottom 1 else if is open root draw circle rect circle rec colorref cr bk dc get bk color circle rec top middle 2 circle rec bottom middle 3 circle rec left tree center 2 circle rec right tree center 3 dc frame rect circle rec c brush m crwindowtext dc set pixelv circle rec left circle rec top cr bk dc set pixelv circle rec right 1 circle rec top cr bk dc set pixelv circle rec left circle rec bottom 1 cr bk dc set pixelv circle rec right 1 circle rec bottom 1 cr bk draw the line to the child node if has next dc move to tree center middle 3 dc line to tree center cur rec bottom 1 else if is expandable draw a sign dc move to tree center middle 2 dc line to tree center middle 3 dc move to tree center 2 middle dc line to tree center 3 middle draw the line back up to parent node if not first is child dc move to tree center middle dc line to tree center cur rec top 1 put the old pen back dc select object oldpn pn delete object put the original objects back if m crwindowtextbk clr none dc set bk mode i old bk mode dc select object p old font dc set text color cr old text color cdownloadlistctrl drawitem lpdrawitemstruct theapp isrunning lpdrawitemstruct itemdata fromhandle lpdrawitemstruct bctrlfocused getfocus getstyle lvs_showselalways lpdrawitemstruct itemstate ods_selected bctrlfocused setbkcolor m_crhighlight setbkcolor m_crnohighlight setbkcolor getbkcolor ctrlitem_struct ctrlitem_struct lpdrawitemstruct itemdata cmemdc lpdrawitemstruct rcitem cfont poldfont m_fontbold m_hobject file_type cpartfile gettransferringsrccount poldfont selectobject m_fontbold poldfont selectobject getfont unavailable_source available_source cupdownclient getdownloadstate ds_downloading poldfont selectobject m_fontbold poldfont selectobject getfont poldfont selectobject getfont poldfont selectobject getfont crect cur_rec lpdrawitemstruct rcitem croldtextcolor settextcolor lpdrawitemstruct itemstate ods_selected m_crhighlighttext m_crwindowtext ioldbkmode m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd ioldbkmode setbkmode ioldbkmode notlast lpdrawitemstruct getitemcount notfirst lpdrawitemstruct tree_start tree_end itreeoffset gettextextent _t cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount cur_rec cur_rec cur_rec file_item_margin_x cur_rec file_item_margin_x file_type g_blowcolordesktop lpdrawitemstruct itemstate ods_selected dwcatcolor theprefs getcatcolor cpartfile getcategory dwcatcolor settextcolor dwcatcolor icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent clistctrl getcolumnwidth icolumn icolumn inextleft cur_rec cur_rec cur_rec itreeoffset cur_rec cur_rec tree_start cur_rec tree_end cur_rec cur_rec cur_rec cur_rec tree_start itreeoffset drawfileitem cur_rec cur_rec inextleft cur_rec drawfileitem icolumn cur_rec cur_rec unavailable_source available_source icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent clistctrl getcolumnwidth icolumn icolumn inextleft cur_rec cur_rec cur_rec itreeoffset cur_rec cur_rec tree_start cur_rec tree_end cur_rec cur_rec cur_rec cur_rec tree_start itreeoffset drawsourceitem cur_rec cur_rec inextleft cur_rec drawsourceitem icolumn cur_rec cur_rec file_type lpdrawitemstruct itemstate ods_selected outline_rec lpdrawitemstruct rcitem outline_rec outline_rec framerect outline_rec cbrush getbkcolor outline_rec outline_rec outline_rec outline_rec notfirst getitemstate lpdrawitemstruct lvis_selected ctrlitem_struct ctrlitem_struct getitemdata lpdrawitemstruct file_type outline_rec notlast getitemstate lpdrawitemstruct lvis_selected ctrlitem_struct ctrlitem_struct getitemdata lpdrawitemstruct file_type outline_rec bctrlfocused framerect outline_rec cbrush m_crfocusline framerect outline_rec cbrush m_crnofocusline lpdrawitemstruct itemstate ods_focus ods_focus getfocus focus_rec focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem framerect focus_rec cbrush m_crnofocusline tree_start tree_end tree_rect tree_rect lpdrawitemstruct rcitem tree_rect lpdrawitemstruct rcitem tree_rect tree_start tree_rect tree_end setboundsrect tree_rect dcb_disable hasnext notlast ctrlitem_struct getitemdata lpdrawitemstruct file_type isopenroot hasnext file_type ischild file_type isexpandable ischild cpartfile getsourcecount treecenter tree_start cur_rec cur_rec cpen createpen ps_solid m_crwindowtext selectobject ischild moveto tree_end lineto tree_start hasnext moveto treecenter lineto treecenter cur_rec isopenroot circle_rec crbk getbkcolor circle_rec circle_rec circle_rec treecenter circle_rec treecenter framerect circle_rec cbrush m_crwindowtext setpixelv circle_rec circle_rec crbk setpixelv circle_rec circle_rec crbk setpixelv circle_rec circle_rec crbk setpixelv circle_rec circle_rec crbk hasnext moveto treecenter lineto treecenter cur_rec isexpandable moveto treecenter lineto treecenter moveto treecenter lineto treecenter notfirst ischild moveto treecenter lineto treecenter cur_rec selectobject deleteobject m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor void c download list ctrl on sys color change c mule list ctrl on sys color change set all icons create menues cdownloadlistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons createmenues void c download list ctrl on item activate nmhdr pnmhdr lresult p result lpnmitemactivate pnmia reinterpret cast lpnmitemactivate pnmhdr if the prefs is double click enabled pnmia i sub item 0 expand collapse item pnmia i item expand collapse p result 0 cdownloadlistctrl onitemactivate presult reinterpret_cast theprefs isdoubleclickenabled isubitem expandcollapseitem iitem expand_collapse presult void c download list ctrl on context menu c wnd p wnd c point point int i sel get next item 1 lvis selected if i sel 1 const ctrlitem struct content ctrlitem struct get item data i sel if content type file type get merged settings bool b first item true int i selected items 0 int i files not done 0 int i files to pause 0 int i files to stop 0 int i files to resume 0 int i files to open 0 int i files get preview parts 0 int i files preview type 0 int i files to preview 0 int i files to cancel 0 uint u prio menu item 0 const c part file file1 null position pos get first selected item position while pos const ctrlitem struct p item data ctrlitem struct get item data get next selected item pos if p item data type file type continue const c part file p file c part file p item data value if b first item file1 p file i selected items bool b file done p file get status ps complete p file get status ps completing i files to cancel p file get status ps completing 1 0 i files not done b file done 1 0 i files to stop p file can stop file 1 0 i files to pause p file can pause file 1 0 i files to resume p file can resume file 1 0 i files to open p file can open file 1 0 i files get preview parts p file get preview prio 1 0 i files preview type p file is previewable file type 1 0 i files to preview p file is ready for preview 1 0 uint u cur prio menu item 0 if p file is auto down priority u cur prio menu item mp prioauto else if p file get down priority pr high u cur prio menu item mp priohigh else if p file get down priority pr normal u cur prio menu item mp prionormal else if p file get down priority pr low u cur prio menu item mp priolow else assert 0 if b first item u prio menu item u cur prio menu item else if u prio menu item u cur prio menu item u prio menu item 0 b first item false m filemenu enable menu item uint ptr m priomenu m hmenu i files not done 0 mf enabled mf grayed m priomenu check menu radio item mp priolow mp prioauto u prio menu item 0 enable commands if there is at least one item which can be used for the action m filemenu enable menu item mp cancel i files to cancel 0 mf enabled mf grayed m filemenu enable menu item mp stop i files to stop 0 mf enabled mf grayed m filemenu enable menu item mp pause i files to pause 0 mf enabled mf grayed m filemenu enable menu item mp resume i files to resume 0 mf enabled mf grayed bool b open enabled i selected items 1 i files to open 1 m filemenu enable menu item mp open b open enabled mf enabled mf grayed if the prefs is ext controls enabled the prefs get preview prio m filemenu enable menu item mp try to get preview parts i selected items 1 i files preview type 1 i files to preview 0 i files not done 1 mf enabled mf grayed m filemenu check menu item mp try to get preview parts i selected items 1 i files get preview parts 1 mf checked mf unchecked m filemenu enable menu item mp preview i selected items 1 i files to preview 1 mf enabled mf grayed c menu preview menu preview menu create menu int i preview menu entries the preview apps get all menu entries preview menu i selected items 1 file1 null if i preview menu entries m filemenu insert menu mp metinfo mf popup i selected items 1 mf enabled mf grayed uint ptr preview menu m hmenu get res string ids dl preview bool b details enabled i selected items 0 m filemenu enable menu item mp metinfo b details enabled mf enabled mf grayed if the prefs is double click enabled b open enabled m filemenu set default item mp open else if the prefs is double click enabled b details enabled m filemenu set default item mp metinfo else m filemenu set default item uint 1 m filemenu enable menu item mp viewfilecomments i selected items 1 i files not done 1 mf enabled mf grayed int total m filemenu enable menu item mp clearcompleted get complete downloads cur tab total 0 mf enabled mf grayed if m sourcesmenu the prefs is ext controls enabled m filemenu enable menu item uint ptr m sourcesmenu m hmenu mf enabled m sourcesmenu enable menu item mp addsource i selected items 1 i files to stop 1 mf enabled mf grayed m sourcesmenu enable menu item mp setsourcelimit i files not done i selected items mf enabled mf grayed m filemenu enable menu item the prefs get show copy ed2k link cmd mp geted2klink mp showed2klink i selected items 0 mf enabled mf grayed m filemenu enable menu item mp paste the app is ed2k file link in clipboard mf enabled mf grayed m filemenu enable menu item mp find get item count 0 mf enabled mf grayed m filemenu enable menu item mp searchrelated i selected items 1 the app emuledlg searchwnd can search related files mf enabled mf grayed c title menu web menu web menu create menu web menu add menu title null true int i web menu entries the web services get file menu entries web menu uint flag i web menu entries 0 i selected items 1 mf grayed mf enabled m filemenu append menu mf popup flag uint ptr web menu m hmenu get res string ids webservices t web create cat submenue c menu cats menu cats menu create menu flag the prefs get cat count 1 mf grayed mf enabled c string label if the prefs get cat count 1 for int i 0 i the prefs get cat count i if i 0 label the prefs get category i title label replace t t cats menu append menu mf string mp assigncat i i 0 get res string ids cat unassign label m filemenu append menu mf popup flag uint ptr cats menu m hmenu get res string ids tocat t category get popup menu pos this point m filemenu track popup menu tpm leftalign tpm rightbutton point x point y this verify m filemenu remove menu m filemenu get menu item count 1 mf byposition verify m filemenu remove menu m filemenu get menu item count 1 mf byposition if i preview menu entries verify m filemenu remove menu uint preview menu m hmenu mf bycommand verify web menu destroy menu verify cats menu destroy menu verify preview menu destroy menu else const c up down client client c up down client content value c title menu client menu client menu create popup menu client menu add menu title get res string ids clients true client menu append menu mf string mp detail get res string ids showdetails t clientdetails client menu set default item mp detail client menu append menu mf string client client is ed2k client client is friend mf enabled mf grayed mp addfriend get res string ids addfriend t addfriend client menu append menu mf string client client is ed2k client mf enabled mf grayed mp message get res string ids send msg t sendmessage client menu append menu mf string client client is ed2k client client get view shared files support mf enabled mf grayed mp showlist get res string ids viewfiles t viewfiles if kademlia c kademlia is running kademlia c kademlia is connected client menu append menu mf string client client is ed2k client client get kad port 0 mf enabled mf grayed mp boot get res string ids bootstrap client menu append menu mf string get item count 0 mf enabled mf grayed mp find get res string ids find t search c menu a4af menu a4af menu create menu if the prefs is ext controls enabled zz download manager if content type unavailable source a4af menu append menu mf string mp a4af check this now get res string ids a4af check this now zz download manager if a4af menu get menu item count 0 client menu append menu mf string mf popup uint ptr a4af menu m hmenu get res string ids a4af get popup menu pos this point client menu track popup menu tpm leftalign tpm rightbutton point x point y this verify a4af menu destroy menu verify client menu destroy menu else nothing selected int total m filemenu enable menu item uint ptr m priomenu m hmenu mf grayed m filemenu enable menu item mp cancel mf grayed m filemenu enable menu item mp pause mf grayed m filemenu enable menu item mp stop mf grayed m filemenu enable menu item mp resume mf grayed m filemenu enable menu item mp open mf grayed if the prefs is ext controls enabled the prefs get preview prio m filemenu enable menu item mp try to get preview parts mf grayed m filemenu check menu item mp try to get preview parts mf unchecked m filemenu enable menu item mp preview mf grayed m filemenu enable menu item mp metinfo mf grayed m filemenu enable menu item mp viewfilecomments mf grayed m filemenu enable menu item mp clearcompleted get complete downloads cur tab total 0 mf enabled mf grayed m filemenu enable menu item the prefs get show copy ed2k link cmd mp geted2klink mp showed2klink mf grayed m filemenu enable menu item mp paste the app is ed2k file link in clipboard mf enabled mf grayed m filemenu set default item uint 1 if m sourcesmenu m filemenu enable menu item uint ptr m sourcesmenu m hmenu mf grayed m filemenu enable menu item mp searchrelated mf grayed m filemenu enable menu item mp f cdownloadlistctrl oncontextmenu cwnd pwnd cpoint isel getnextitem lvis_selected isel ctrlitem_struct ctrlitem_struct getitemdata isel file_type bfirstitem iselecteditems ifilesnotdone ifilestopause ifilestostop ifilestoresume ifilestoopen ifilesgetpreviewparts ifilespreviewtype ifilestopreview ifilestocancel upriomenuitem cpartfile getfirstselecteditemposition ctrlitem_struct pitemdata ctrlitem_struct getitemdata getnextselecteditem pitemdata file_type cpartfile pfile cpartfile pitemdata bfirstitem pfile iselecteditems bfiledone pfile getstatus ps_complete pfile getstatus ps_completing ifilestocancel pfile getstatus ps_completing ifilesnotdone bfiledone ifilestostop pfile canstopfile ifilestopause pfile canpausefile ifilestoresume pfile canresumefile ifilestoopen pfile canopenfile ifilesgetpreviewparts pfile getpreviewprio ifilespreviewtype pfile ispreviewablefiletype ifilestopreview pfile isreadyforpreview ucurpriomenuitem pfile isautodownpriority ucurpriomenuitem mp_prioauto pfile getdownpriority pr_high ucurpriomenuitem mp_priohigh pfile getdownpriority pr_normal ucurpriomenuitem mp_prionormal pfile getdownpriority pr_low ucurpriomenuitem mp_priolow bfirstitem upriomenuitem ucurpriomenuitem upriomenuitem ucurpriomenuitem upriomenuitem bfirstitem m_filemenu enablemenuitem uint_ptr m_priomenu m_hmenu ifilesnotdone mf_enabled mf_grayed m_priomenu checkmenuradioitem mp_priolow mp_prioauto upriomenuitem m_filemenu enablemenuitem mp_cancel ifilestocancel mf_enabled mf_grayed m_filemenu enablemenuitem mp_stop ifilestostop mf_enabled mf_grayed m_filemenu enablemenuitem mp_pause ifilestopause mf_enabled mf_grayed m_filemenu enablemenuitem mp_resume ifilestoresume mf_enabled mf_grayed bopenenabled iselecteditems ifilestoopen m_filemenu enablemenuitem mp_open bopenenabled mf_enabled mf_grayed theprefs isextcontrolsenabled theprefs getpreviewprio m_filemenu enablemenuitem mp_try_to_get_preview_parts iselecteditems ifilespreviewtype ifilestopreview ifilesnotdone mf_enabled mf_grayed m_filemenu checkmenuitem mp_try_to_get_preview_parts iselecteditems ifilesgetpreviewparts mf_checked mf_unchecked m_filemenu enablemenuitem mp_preview iselecteditems ifilestopreview mf_enabled mf_grayed cmenu previewmenu previewmenu createmenu ipreviewmenuentries thepreviewapps getallmenuentries previewmenu iselecteditems ipreviewmenuentries m_filemenu insertmenu mp_metinfo mf_popup iselecteditems mf_enabled mf_grayed uint_ptr previewmenu m_hmenu getresstring ids_dl_preview bdetailsenabled iselecteditems m_filemenu enablemenuitem mp_metinfo bdetailsenabled mf_enabled mf_grayed theprefs isdoubleclickenabled bopenenabled m_filemenu setdefaultitem mp_open theprefs isdoubleclickenabled bdetailsenabled m_filemenu setdefaultitem mp_metinfo m_filemenu setdefaultitem m_filemenu enablemenuitem mp_viewfilecomments iselecteditems ifilesnotdone mf_enabled mf_grayed m_filemenu enablemenuitem mp_clearcompleted getcompletedownloads curtab mf_enabled mf_grayed m_sourcesmenu theprefs isextcontrolsenabled m_filemenu enablemenuitem uint_ptr m_sourcesmenu m_hmenu mf_enabled m_sourcesmenu enablemenuitem mp_addsource iselecteditems ifilestostop mf_enabled mf_grayed m_sourcesmenu enablemenuitem mp_setsourcelimit ifilesnotdone iselecteditems mf_enabled mf_grayed m_filemenu enablemenuitem theprefs getshowcopyed2klinkcmd mp_geted2klink mp_showed2klink iselecteditems mf_enabled mf_grayed m_filemenu enablemenuitem mp_paste theapp ised2kfilelinkinclipboard mf_enabled mf_grayed m_filemenu enablemenuitem mp_find getitemcount mf_enabled mf_grayed m_filemenu enablemenuitem mp_searchrelated iselecteditems theapp cansearchrelatedfiles mf_enabled mf_grayed ctitlemenu webmenu webmenu createmenu webmenu addmenutitle iwebmenuentries thewebservices getfilemenuentries webmenu iwebmenuentries iselecteditems mf_grayed mf_enabled m_filemenu appendmenu mf_popup uint_ptr webmenu m_hmenu getresstring ids_webservices _t cmenu catsmenu catsmenu createmenu theprefs getcatcount mf_grayed mf_enabled cstring theprefs getcatcount theprefs getcatcount theprefs getcategory _t _t catsmenu appendmenu mf_string mp_assigncat getresstring ids_cat_unassign m_filemenu appendmenu mf_popup uint_ptr catsmenu m_hmenu getresstring ids_tocat _t getpopupmenupos m_filemenu trackpopupmenu tpm_leftalign tpm_rightbutton m_filemenu removemenu m_filemenu getmenuitemcount mf_byposition m_filemenu removemenu m_filemenu getmenuitemcount mf_byposition ipreviewmenuentries m_filemenu removemenu previewmenu m_hmenu mf_bycommand webmenu destroymenu catsmenu destroymenu previewmenu destroymenu cupdownclient cupdownclient ctitlemenu clientmenu clientmenu createpopupmenu clientmenu addmenutitle getresstring ids_clients clientmenu appendmenu mf_string mp_detail getresstring ids_showdetails _t clientmenu setdefaultitem mp_detail clientmenu appendmenu mf_string ised2kclient isfriend mf_enabled mf_grayed mp_addfriend getresstring ids_addfriend _t clientmenu appendmenu mf_string ised2kclient mf_enabled mf_grayed mp_message getresstring ids_send_msg _t clientmenu appendmenu mf_string ised2kclient getviewsharedfilessupport mf_enabled mf_grayed mp_showlist getresstring ids_viewfiles _t ckademlia isrunning ckademlia isconnected clientmenu appendmenu mf_string ised2kclient getkadport mf_enabled mf_grayed mp_boot getresstring ids_bootstrap clientmenu appendmenu mf_string getitemcount mf_enabled mf_grayed mp_find getresstring ids_find _t cmenu a4afmenu a4afmenu createmenu theprefs isextcontrolsenabled downloadmanager unavailable_source a4afmenu appendmenu mf_string mp_a4af_check_this_now getresstring ids_a4af_check_this_now downloadmanager a4afmenu getmenuitemcount clientmenu appendmenu mf_string mf_popup uint_ptr a4afmenu m_hmenu getresstring ids_a4af getpopupmenupos clientmenu trackpopupmenu tpm_leftalign tpm_rightbutton a4afmenu destroymenu clientmenu destroymenu m_filemenu enablemenuitem uint_ptr m_priomenu m_hmenu mf_grayed m_filemenu enablemenuitem mp_cancel mf_grayed m_filemenu enablemenuitem mp_pause mf_grayed m_filemenu enablemenuitem mp_stop mf_grayed m_filemenu enablemenuitem mp_resume mf_grayed m_filemenu enablemenuitem mp_open mf_grayed theprefs isextcontrolsenabled theprefs getpreviewprio m_filemenu enablemenuitem mp_try_to_get_preview_parts mf_grayed m_filemenu checkmenuitem mp_try_to_get_preview_parts mf_unchecked m_filemenu enablemenuitem mp_preview mf_grayed m_filemenu enablemenuitem mp_metinfo mf_grayed m_filemenu enablemenuitem mp_viewfilecomments mf_grayed m_filemenu enablemenuitem mp_clearcompleted getcompletedownloads curtab mf_enabled mf_grayed m_filemenu enablemenuitem theprefs getshowcopyed2klinkcmd mp_geted2klink mp_showed2klink mf_grayed m_filemenu enablemenuitem mp_paste theapp ised2kfilelinkinclipboard mf_enabled mf_grayed m_filemenu setdefaultitem m_sourcesmenu m_filemenu enablemenuitem uint_ptr m_sourcesmenu m_hmenu mf_grayed m_filemenu enablemenuitem mp_searchrelated mf_grayed m_filemenu enablemenuitem mp_f void c download list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr barry store sort order in preferences determine ascending based on whether already sorted on this column int sort item get sort item bool m oldsortascending get sort ascending if sort item 9 m bremainsort sort item pnm list view i sub item false m oldsortascending m bremainsort m bremainsort bool sort ascending sort item pnm list view i sub item true m oldsortascending item is column clicked sort item pnm list view i sub item update sort history sort item sort ascending 0 100 100 save new preferences the prefs transferlist remain sort style m bremainsort sort table uint8 adder 0 if sort item 9 m bremainsort set sort arrow sort item sort ascending else set sort arrow sort item sort ascending arrow double up arrow double down adder 81 sort items sort proc sort item sort ascending 0 100 adder p result 0 cdownloadlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview sortitem getsortitem m_oldsortascending getsortascending sortitem m_bremainsort sortitem pnmlistview isubitem m_oldsortascending m_bremainsort m_bremainsort sortascending sortitem pnmlistview isubitem m_oldsortascending sortitem pnmlistview isubitem updatesorthistory sortitem sortascending theprefs transferlistremainsortstyle m_bremainsort sortitem m_bremainsort setsortarrow sortitem sortascending setsortarrow sortitem sortascending arrowdoubleup arrowdoubledown sortitems sortproc sortitem sortascending presult void c download list ctrl on list modified nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr this works because true is equal to 1 and false equal to 0 bool not last pnm list view i item 1 get item count bool not first pnm list view i item 0 redraw items pnm list view i item not first pnm list view i item not last cdownloadlistctrl onlistmodified presult nm_listview pnmlistview nm_listview notlast pnmlistview iitem getitemcount notfirst pnmlistview iitem redrawitems pnmlistview iitem notfirst pnmlistview iitem notlast void c download list ctrl onnm dblclk downloadlist nmhdr pnmhdr lresult p result int i sel get selection mark if i sel 1 const ctrlitem struct content ctrlitem struct get item data i sel if content content value if content type file type if the prefs is double click enabled c point pt get cursor pos pt screen to client pt lvhittestinfo hit hit pt pt if hit test hit 0 hit flags lvht onitem lvhittestinfo subhit subhit pt pt if sub item hit test subhit 0 subhit i sub item 0 c part file file c part file content value if the prefs show rating indicator file has comment file has rating pt x file item margin x the app get small sytem icon size cx pt x file item margin x the app get small sytem icon size cx rating icon width show file dialog idd commentlst else if the prefs get preview on icon dbl clk pt x file item margin x pt x file item margin x the app get small sytem icon size cx if file is ready for preview file preview file else message beep mb ok else show file dialog 0 else show client dialog c up down client content value p result 0 cdownloadlistctrl onnmdblclkdownloadlist presult isel getselectionmark isel ctrlitem_struct ctrlitem_struct getitemdata isel file_type theprefs isdoubleclickenabled cpoint getcursorpos screentoclient hittest lvht_onitem subitemhittest isubitem cpartfile cpartfile theprefs showratingindicator hascomment hasrating file_item_margin_x theapp getsmallsytemiconsize file_item_margin_x theapp getsmallsytemiconsize rating_icon_width showfiledialog idd_commentlst theprefs getpreviewonicondblclk file_item_margin_x file_item_margin_x theapp getsmallsytemiconsize isreadyforpreview previewfile messagebeep mb_ok showfiledialog showclientdialog cupdownclient presult void c download list ctrl on get disp info nmhdr pnmhdr lresult p result nmlvdispinfo p disp info nmlvdispinfo pnmhdr trace c download list ctrl on get disp info i item d i sub item d p disp info item i item p disp info item i sub item if p disp info item mask lvif text trace lvif text if p disp info item mask lvif image trace lvif image if p disp info item mask lvif state trace lvif state trace n although we have an owner drawn listview control we store the text for the primary item in the listview to be capable of quick searching those items via the keyboard because our listview items may change their contents we do this via a text callback function the listview control will send us the lvn dispinfo notification if it needs to know the contents of the primary item but the listview control sends this notification all the time even if we do not search for an item at least this notification is only sent for the visible items and not for all items in the list though because this function is invoked very often no not put any time consuming code here in if p disp info item mask lvif text const ctrlitem struct p item reinterpret cast ctrlitem struct p disp info item l param if p item null p item value null if p item type file type switch p disp info item i sub item case 0 if p disp info item cch text max 0 tcsncpy p disp info item psz text c part file p item value get file name p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break default shouldn t happen p disp info item psz text 0 t 0 break else if p item type unavailable source p item type available source switch p disp info item i sub item case 0 if c up down client p item value get user name null p disp info item cch text max 0 tcsncpy p disp info item psz text c up down client p item value get user name p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break default shouldn t happen p disp info item psz text 0 t 0 break else assert 0 p result 0 cdownloadlistctrl ongetdispinfo presult pdispinfo cdownloadlistctrl ongetdispinfo iitem isubitem pdispinfo iitem pdispinfo isubitem pdispinfo lvif_text lvif_text pdispinfo lvif_image lvif_image pdispinfo lvif_state lvif_state lvn_dispinfo pdispinfo lvif_text ctrlitem_struct pitem reinterpret_cast ctrlitem_struct pdispinfo lparam pitem pitem pitem file_type pdispinfo isubitem pdispinfo cchtextmax _tcsncpy pdispinfo psztext cpartfile pitem getfilename pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t pdispinfo psztext _t pitem unavailable_source pitem available_source pdispinfo isubitem cupdownclient pitem getusername pdispinfo cchtextmax _tcsncpy pdispinfo psztext cupdownclient pitem getusername pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t pdispinfo psztext _t presult void c download list ctrl on lvn get info tip nmhdr pnmhdr lresult p result lpnmlvgetinfotip p get info tip reinterpret cast lpnmlvgetinfotip pnmhdr if p get info tip i sub item 0 lvhittestinfo hti 0 get cursor pos hti pt screen to client hti pt if sub item hit test hti 1 hti i item p get info tip i item hti i sub item 0 don show the default label tip for the main item if the mouse is not over the main item if p get info tip dw flags lvgit unfolded 0 p get info tip cch text max 0 p get info tip psz text 0 0 p get info tip psz text 0 0 return const ctrlitem struct content ctrlitem struct get item data p get info tip i item if content p get info tip psz text p get info tip cch text max 0 c string info build info text and display it if content type 1 for downloading files const c part file partfile c part file content value info partfile get info summary else if content type 3 content type 2 for sources const c up down client client c up down client content value if client is ed2k client in addr server server s un s addr client get serverip info format get res string ids userinfo get res string ids server t s u n n get res string ids next reask t s client get user name client get user name t ipstr server client get server port cast seconds tohm client get time until reask client get request file 1000 if the prefs is ext controls enabled info append format t s cast seconds tohm client get time until reask content owner 1000 info t n info append format get res string ids sourceinfo client get asked count down client get available part count info t n if content type 2 info get res string ids clientsourcename client get client filename is empty client get client filename t if client get file comment is empty info t n get res string ids cmt read t client get file comment if client get file rating info t n get res string ids ql rating t get rate string client get file rating else client asked twice info get res string ids askedfaf if client get request file client get request file get file name info append format t s client get request file get file name if the prefs is ext controls enabled client m otherrequests list is empty c simple array const c string apstr file names position pos client m otherrequests list get head position while pos apstr file names add client m otherrequests list get next pos get file name sort apstr file names if content type 2 info t n info t n info get res string ids a4af files info t for int i 0 i apstr file names get size i const c string pstr file name apstr file names i if info get length i 0 2 0 pstr file name get length p get info tip cch text max static const tchar sz ellipses t n if info get length int arrsize sz ellipses 1 p get info tip cch text max info sz ellipses break if i 0 info t n info pstr file name else info format t url s n available parts u client get user name client get available part count tcsncpy p get info tip psz text info p get info tip cch text max p get info tip psz text p get info tip cch text max 1 t 0 p result 0 cdownloadlistctrl onlvngetinfotip presult pgetinfotip reinterpret_cast pgetinfotip isubitem getcursorpos screentoclient subitemhittest iitem pgetinfotip iitem isubitem pgetinfotip dwflags lvgit_unfolded pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip psztext ctrlitem_struct ctrlitem_struct getitemdata pgetinfotip iitem pgetinfotip psztext pgetinfotip cchtextmax cstring cpartfile cpartfile getinfosummary cupdownclient cupdownclient ised2kclient in_addr s_un s_addr getserverip getresstring ids_userinfo getresstring ids_server _t getresstring ids_next_reask _t getusername getusername _t getserverport castsecondstohm gettimeuntilreask getrequestfile theprefs isextcontrolsenabled appendformat _t castsecondstohm gettimeuntilreask _t appendformat getresstring ids_sourceinfo getaskedcountdown getavailablepartcount _t getresstring ids_clientsourcename getclientfilename isempty getclientfilename _t getfilecomment isempty _t getresstring ids_cmt_read _t getfilecomment getfilerating _t getresstring ids_ql_rating _t getratestring getfilerating getresstring ids_askedfaf getrequestfile getrequestfile getfilename appendformat _t getrequestfile getfilename theprefs isextcontrolsenabled m_otherrequests_list isempty csimplearray cstring apstrfilenames m_otherrequests_list getheadposition apstrfilenames m_otherrequests_list getnext getfilename apstrfilenames _t _t getresstring ids_a4af_files _t apstrfilenames getsize cstring pstrfilename apstrfilenames getlength pstrfilename getlength pgetinfotip cchtextmax szellipses _t getlength szellipses pgetinfotip cchtextmax szellipses _t pstrfilename _t navailable getusername getavailablepartcount _tcsncpy pgetinfotip psztext pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip cchtextmax _t presult c list ctrl item walk p list ctrl m pdownloadlistctrl p list ctrl m eitemtype item type 1 clistctrlitemwalk plistctrl m_pdownloadlistctrl plistctrl m_eitemtype itemtype c object c download list list ctrl item walk get next selectable item assert m pdownloadlistctrl null if m pdownloadlistctrl null return null assert m eitemtype item type 1 int i item count m pdownloadlistctrl get item count if i item count 2 position pos m pdownloadlistctrl get first selected item position if pos int i item m pdownloadlistctrl get next selected item pos int i cur sel item i item while i item 1 i item count i item const ctrlitem struct ctrl item ctrlitem struct m pdownloadlistctrl get item data i item if ctrl item type m eitemtype m eitemtype file type ctrl item type file type m pdownloadlistctrl set item state i cur sel item 0 lvis selected lvis focused m pdownloadlistctrl set item state i item lvis selected lvis focused lvis selected lvis focused m pdownloadlistctrl set selection mark i item m pdownloadlistctrl ensure visible i item false return static downcast c object c object ctrl item value return null cobject cdownloadlistlistctrlitemwalk getnextselectableitem m_pdownloadlistctrl m_pdownloadlistctrl m_eitemtype itemtype iitemcount m_pdownloadlistctrl getitemcount iitemcount m_pdownloadlistctrl getfirstselecteditemposition iitem m_pdownloadlistctrl getnextselecteditem icurselitem iitem iitem iitemcount iitem ctrlitem_struct ctrl_item ctrlitem_struct m_pdownloadlistctrl getitemdata iitem ctrl_item m_eitemtype m_eitemtype file_type ctrl_item file_type m_pdownloadlistctrl setitemstate icurselitem lvis_selected lvis_focused m_pdownloadlistctrl setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused m_pdownloadlistctrl setselectionmark iitem m_pdownloadlistctrl ensurevisible iitem static_downcast cobject cobject ctrl_item c object c download list list ctrl item walk get prev selectable item assert m pdownloadlistctrl null if m pdownloadlistctrl null return null assert m eitemtype item type 1 int i item count m pdownloadlistctrl get item count if i item count 2 position pos m pdownloadlistctrl get first selected item position if pos int i item m pdownloadlistctrl get next selected item pos int i cur sel item i item while i item 1 0 i item const ctrlitem struct ctrl item ctrlitem struct m pdownloadlistctrl get item data i item if ctrl item type m eitemtype m eitemtype file type ctrl item type file type m pdownloadlistctrl set item state i cur sel item 0 lvis selected lvis focused m pdownloadlistctrl set item state i item lvis selected lvis focused lvis selected lvis focused m pdownloadlistctrl set selection mark i item m pdownloadlistctrl ensure visible i item false return static downcast c object c object ctrl item value return null cobject cdownloadlistlistctrlitemwalk getprevselectableitem m_pdownloadlistctrl m_pdownloadlistctrl m_eitemtype itemtype iitemcount m_pdownloadlistctrl getitemcount iitemcount m_pdownloadlistctrl getfirstselecteditemposition iitem m_pdownloadlistctrl getnextselecteditem icurselitem iitem iitem iitem ctrlitem_struct ctrl_item ctrlitem_struct m_pdownloadlistctrl getitemdata iitem ctrl_item m_eitemtype m_eitemtype file_type ctrl_item file_type m_pdownloadlistctrl setitemstate icurselitem lvis_selected lvis_focused m_pdownloadlistctrl setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused m_pdownloadlistctrl setselectionmark iitem m_pdownloadlistctrl ensurevisible iitem static_downcast cobject cobject ctrl_item c list ctrl item walk this set general purpose find true false barry refresh the queue every 10 secs verify m htimer set timer null null 10000 queue update timer null if the prefs get verbose m htimer add debug log line true t failed to create queue list control timer s get error message get last error clistctrlitemwalk setgeneralpurposefind m_htimer settimer queueupdatetimer theprefs getverbose m_htimer adddebuglogline _t geterrormessage getlasterror c queue list ctrl c queue list ctrl if m htimer verify kill timer null m htimer cqueuelistctrl cqueuelistctrl m_htimer killtimer m_htimer void c queue list ctrl init set name t queue list ctrl c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 set image list il dummy image list lvsil small assert get style lvs shareimagelists 0 il dummy image list detach set extended style lvs ex fullrowselect insert column 0 get res string ids ql username lvcfmt left 150 0 insert column 1 get res string ids file lvcfmt left 275 1 insert column 2 get res string ids fileprio lvcfmt left 110 2 insert column 3 get res string ids ql rating lvcfmt left 60 3 insert column 4 get res string ids score lvcfmt left 60 4 insert column 5 get res string ids asked lvcfmt left 60 5 insert column 6 get res string ids lastseen lvcfmt left 110 6 insert column 7 get res string ids enterqueue lvcfmt left 110 7 insert column 8 get res string ids banned lvcfmt left 60 8 insert column 9 get res string ids upstatus lvcfmt left 100 9 set all icons localize load settings barry use preferred sort order from preferences set sort arrow sort items sort proc get sort item get sort ascending 0 100 cqueuelistctrl setname _t queuelistctrl cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask setimagelist ildummyimagelist lvsil_small getstyle lvs_shareimagelists ildummyimagelist setextendedstyle lvs_ex_fullrowselect insertcolumn getresstring ids_ql_username lvcfmt_left insertcolumn getresstring ids_file lvcfmt_left insertcolumn getresstring ids_fileprio lvcfmt_left insertcolumn getresstring ids_ql_rating lvcfmt_left insertcolumn getresstring ids_score lvcfmt_left insertcolumn getresstring ids_asked lvcfmt_left insertcolumn getresstring ids_lastseen lvcfmt_left insertcolumn getresstring ids_enterqueue lvcfmt_left insertcolumn getresstring ids_banned lvcfmt_left insertcolumn getresstring ids_upstatus lvcfmt_left setallicons loadsettings setsortarrow sortitems sortproc getsortitem getsortascending void c queue list ctrl add client const c up down client client bool resetclient if resetclient client client set wait start time client set asked count 1 if the app emuledlg is running return if the prefs is queue list disabled return int i item count get item count int i item insert item lvif text lvif param i item count lpstr textcallback 0 0 0 lparam client update i item the app emuledlg transferwnd update list count c transfer wnd wnd2 on queue i item count 1 cqueuelistctrl addclient cupdownclient setwaitstarttime setaskedcount theapp isrunning theprefs isqueuelistdisabled iitemcount getitemcount iitem insertitem lvif_text lvif_param iitemcount lpstr_textcallback iitem theapp updatelistcount ctransferwnd wnd2onqueue iitemcount void c queue list ctrl remove client const c up down client client if the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam client int result find item find if result 1 delete item result the app emuledlg transferwnd update list count c transfer wnd wnd2 on queue cqueuelistctrl removeclient cupdownclient theapp isrunning lvfi_param lparam finditem deleteitem theapp updatelistcount ctransferwnd wnd2onqueue void c queue list ctrl refresh client const c up down client client there is some type of timing issue here if you click on item in the queue or upload and leave the focus on it when you exit the cient it breaks on line 854 of emule dlg cpp i added this is running check to this function and the draw item method and this seems to keep it from crashing this is not the fix but a patch until someone points out what is going wrong also it will still assert in debug mode if the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam client int result find item find if result 1 update result cqueuelistctrl refreshclient cupdownclient emuledlg isrunning drawitem theapp isrunning lvfi_param lparam finditem void c queue list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text if p header ctrl get item count 0 c string str res str res get res string ids ql username hdi psz text const cast lptstr lpctstr str res p header ctrl set item 0 hdi str res get res string ids file hdi psz text const cast lptstr lpctstr str res p header ctrl set item 1 hdi str res get res string ids fileprio hdi psz text const cast lptstr lpctstr str res p header ctrl set item 2 hdi str res get res string ids ql rating hdi psz text const cast lptstr lpctstr str res p header ctrl set item 3 hdi str res get res string ids score hdi psz text const cast lptstr lpctstr str res p header ctrl set item 4 hdi str res get res string ids asked hdi psz text const cast lptstr lpctstr str res p header ctrl set item 5 hdi str res get res string ids lastseen hdi psz text const cast lptstr lpctstr str res p header ctrl set item 6 hdi str res get res string ids enterqueue hdi psz text const cast lptstr lpctstr str res p header ctrl set item 7 hdi str res get res string ids banned hdi psz text const cast lptstr lpctstr str res p header ctrl set item 8 hdi str res get res string ids upstatus hdi psz text const cast lptstr lpctstr str res p header ctrl set item 9 hdi cqueuelistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text pheaderctrl getitemcount cstring strres strres getresstring ids_ql_username psztext const_cast strres pheaderctrl setitem strres getresstring ids_file psztext const_cast strres pheaderctrl setitem strres getresstring ids_fileprio psztext const_cast strres pheaderctrl setitem strres getresstring ids_ql_rating psztext const_cast strres pheaderctrl setitem strres getresstring ids_score psztext const_cast strres pheaderctrl setitem strres getresstring ids_asked psztext const_cast strres pheaderctrl setitem strres getresstring ids_lastseen psztext const_cast strres pheaderctrl setitem strres getresstring ids_enterqueue psztext const_cast strres pheaderctrl setitem strres getresstring ids_banned psztext const_cast strres pheaderctrl setitem strres getresstring ids_upstatus psztext const_cast strres pheaderctrl setitem void c queue list ctrl show selected user details point point get cursor pos point c point p point screen to client p int it hit test p if it 1 return set item state 1 0 lvis selected set item state it lvis selected lvis focused lvis selected lvis focused set selection mark it display selection mark correctly c up down client client c up down client get item data get selection mark if client c client detail dialog dialog client this dialog do modal cqueuelistctrl showselecteduserdetails getcursorpos cpoint screentoclient hittest setitemstate lvis_selected setitemstate lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark cupdownclient cupdownclient getitemdata getselectionmark cclientdetaildialog domodal void c queue list ctrl show queue clients delete all items c up down client update the app uploadqueue get next client null while update add client update false update the app uploadqueue get next client update cqueuelistctrl showqueueclients deleteallitems cupdownclient theapp getnextclient addclient theapp getnextclient void c queue list ctrl set all icons imagelist delete image list imagelist create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 imagelist set bk color clr none imagelist add c temp icon loader t cliente donkey imagelist add c temp icon loader t client compatible imagelist add c temp icon loader t cliente donkey plus imagelist add c temp icon loader t client compatible plus imagelist add c temp icon loader t friend imagelist add c temp icon loader t clientml donkey imagelist add c temp icon loader t clientml donkey plus imagelist add c temp icon loader t cliente donkey hybrid imagelist add c temp icon loader t cliente donkey hybrid plus imagelist add c temp icon loader t client shareaza imagelist add c temp icon loader t client shareaza plus imagelist add c temp icon loader t clienta mule imagelist add c temp icon loader t clienta mule plus imagelist add c temp icon loader t clientl phant imagelist add c temp icon loader t clientl phant plus imagelist set overlay image imagelist add c temp icon loader t client secure ovl 1 cqueuelistctrl setallicons deleteimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t clientedonkey ctempiconloader _t clientcompatible ctempiconloader _t clientedonkeyplus ctempiconloader _t clientcompatibleplus ctempiconloader _t ctempiconloader _t clientmldonkey ctempiconloader _t clientmldonkeyplus ctempiconloader _t clientedonkeyhybrid ctempiconloader _t clientedonkeyhybridplus ctempiconloader _t clientshareaza ctempiconloader _t clientshareazaplus ctempiconloader _t clientamule ctempiconloader _t clientamuleplus ctempiconloader _t clientlphant ctempiconloader _t clientlphantplus setoverlayimage ctempiconloader _t clientsecureovl int c queue list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort const c up down client item1 c up down client l param1 const c up down client item2 c up down client l param2 int i result 0 switch l param sort case 0 if item1 get user name item2 get user name i result compare locale string no case item1 get user name item2 get user name else if item1 get user name i result 1 else i result 1 break case 100 if item2 get user name item1 get user name i result compare locale string no case item2 get user name item1 get user name else if item2 get user name i result 1 else i result 1 break case 1 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result compare locale string no case file1 get file name file2 get file name else if file1 null i result 1 else i result 1 break case 101 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result compare locale string no case file2 get file name file1 get file name else if file1 null i result 1 else i result 1 break case 2 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result file1 get up priority pr verylow 1 file1 get up priority file2 get up priority pr verylow 1 file2 get up priority else if file1 null i result 1 else i result 1 break case 102 c known file file1 the app sharedfiles get file byid item1 get upload fileid c known file file2 the app sharedfiles get file byid item2 get upload fileid if file1 null file2 null i result file2 get up priority pr verylow 1 file2 get up priority file1 get up priority pr verylow 1 file1 get up priority else if file1 null i result 1 else i result 1 break case 3 i result compare unsigned item1 get score false false true item2 get score false false true break case 103 i result compare unsigned item2 get score false false true item1 get score false false true break case 4 i result compare unsigned item1 get score false item2 get score false break case 104 i result compare unsigned item2 get score false item1 get score false break case 5 i result item1 get asked count item2 get asked count break case 105 i result item2 get asked count item1 get asked count break case 6 i result item1 get last up request item2 get last up request break case 106 i result item2 get last up request item1 get last up request break case 7 i result item1 get wait start time item2 get wait start time break case 107 i result item2 get wait start time item1 get wait start time break case 8 i result item1 is banned item2 is banned break case 108 i result item2 is banned item1 is banned break case 9 i result item1 get up part count item2 get up part count break case 109 i result item2 get up part count item1 get up part count break default i result 0 break int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if i result 0 dw next sort the app emuledlg transferwnd queuelistctrl get next sort order l param sort 1 i result sort proc l param1 l param2 dw next sort return i result cqueuelistctrl sortproc lparam1 lparam2 lparamsort cupdownclient cupdownclient lparam1 cupdownclient cupdownclient lparam2 iresult lparamsort getusername getusername iresult comparelocalestringnocase getusername getusername getusername iresult iresult getusername getusername iresult comparelocalestringnocase getusername getusername getusername iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult comparelocalestringnocase getfilename getfilename iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult comparelocalestringnocase getfilename getfilename iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult getuppriority pr_verylow getuppriority getuppriority pr_verylow getuppriority iresult iresult cknownfile theapp getfilebyid getuploadfileid cknownfile theapp getfilebyid getuploadfileid iresult getuppriority pr_verylow getuppriority getuppriority pr_verylow getuppriority iresult iresult iresult compareunsigned getscore getscore iresult compareunsigned getscore getscore iresult compareunsigned getscore getscore iresult compareunsigned getscore getscore iresult getaskedcount getaskedcount iresult getaskedcount getaskedcount iresult getlastuprequest getlastuprequest iresult getlastuprequest getlastuprequest iresult getwaitstarttime getwaitstarttime iresult getwaitstarttime getwaitstarttime iresult isbanned isbanned iresult isbanned isbanned iresult getuppartcount getuppartcount iresult getuppartcount getuppartcount iresult dwnextsort iresult dwnextsort theapp getnextsortorder lparamsort iresult sortproc lparam1 lparam2 dwnextsort iresult bool c queue list ctrl on command wparam w param lparam l param w param loword w param switch w param case mp find on find start return true int i sel get next item 1 lvis selected lvis focused if i sel 1 c up down client client c up down client get item data i sel switch w param case mp showlist client request shared file list break case mp message the app emuledlg chatwnd start session client break case mp addfriend if the app friendlist add friend client update i sel break case mp unban if client is banned client un ban update i sel break case mp detail case mpg altenter case ida enter c client detail dialog dialog client this dialog do modal break case mp boot if client get kad port kademlia c kademlia bootstrap ntohl client getip client get kad port break return true cqueuelistctrl oncommand wparam lparam wparam wparam wparam mp_find onfindstart isel getnextitem lvis_selected lvis_focused isel cupdownclient cupdownclient getitemdata isel wparam mp_showlist requestsharedfilelist mp_message theapp startsession mp_addfriend theapp addfriend isel mp_unban isbanned unban isel mp_detail mpg_altenter ida_enter cclientdetaildialog domodal mp_boot getkadport ckademlia getkadport void c queue list ctrl draw item lpdrawitemstruct lp draw item struct if the app emuledlg is running return if lp draw item struct item data return cdc odc cdc from handle lp draw item struct hdc bool b ctrl focused get focus this get style lvs showselalways if lp draw item struct item state ods selected if b ctrl focused odc set bk color m crhighlight else odc set bk color m crnohighlight else odc set bk color get bk color const c up down client client c up down client lp draw item struct item data c memdc dc odc lp draw item struct rc item c font p old font dc select object get font c rect cur rec lp draw item struct rc item colorref cr old text color dc set text color lp draw item struct item state ods selected m crhighlighttext m crwindowtext int i old bk mode if m crwindowtextbk clr none def window proc wm erasebkgnd wparam hdc dc 0 i old bk mode dc set bk mode transparent else i old bk mode opaque c known file file the app sharedfiles get file byid client get upload fileid c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count cur rec right cur rec left 8 cur rec left 4 c string sbuffer for int i current 0 i current i count i current int i column p header ctrl order to index i current if is column hidden i column cur rec right get column width i column switch i column case 0 uint8 image if client is friend image 4 else if client get client soft so edonkeyhybrid if client credits get score ratio client getip 1 image 8 else image 7 else if client get client soft so mldonkey if client credits get score ratio client getip 1 image 6 else image 5 else if client get client soft so shareaza if client credits get score ratio client getip 1 image 10 else image 9 else if client get client soft so amule if client credits get score ratio client getip 1 image 12 else image 11 else if client get client soft so lphant if client credits get score ratio client getip 1 image 14 else image 13 else if client ext protocol available if client credits get score ratio client getip 1 image 3 else image 1 else if client credits get score ratio client getip 1 image 2 else image 0 point point cur rec left cur rec top 1 imagelist draw dc image point ild normal client credits client credits get current ident state client getip is identified indextooverlaymask 1 0 sbuffer client get user name cur rec left 20 dc draw text sbuffer sbuffer get length cur rec dlc dt text cur rec left 20 break case 1 if file sbuffer file get file name else sbuffer t break case 2 if file switch file get up priority case pr verylow sbuffer get res string ids prioverylow break case pr low if file is auto up priority sbuffer get res string ids prioautolow else sbuffer get res string ids priolow break case pr normal if file is auto up priority sbuffer get res string ids prioautonormal else sbuffer get res string ids prionormal break case pr high if file is auto up priority sbuffer get res string ids prioautohigh else sbuffer get res string ids priohigh break case pr veryhigh sbuffer get res string ids priorelease break default sbuffer empty else sbuffer t break case 3 sbuffer format t i client get score false false true break case 4 if client has lowid if client m baddnextconnect sbuffer format t i client get score false else sbuffer format t i lowid client get score false else sbuffer format t i client get score false break case 5 sbuffer format t i client get asked count break case 6 sbuffer cast seconds tohm get tick count client get last up request 1000 break case 7 sbuffer cast seconds tohm get tick count client get wait start time 1000 break case 8 if client is banned sbuffer get res string ids yes else sbuffer get res string ids no break case 9 if client get up part count cur rec bottom cur rec top client draw up status bar dc cur rec false the prefs use flat bar cur rec bottom cur rec top break if i column 9 i column 0 dc draw text sbuffer sbuffer get length cur rec dlc dt text cur rec left get column width i column draw rectangle around selected item s if lp draw item struct item state ods selected rect outline rec lp draw item struct rc item outline rec top outline rec bottom dc frame rect outline rec c brush get bk color outline rec top outline rec bottom outline rec left outline rec right if b ctrl focused dc frame rect outline rec c brush m crfocusline else dc frame rect outline rec c brush m crnofocusline if m crwindowtextbk clr none dc set bk mode i old bk mode dc select object p old font dc set text color cr old text color cqueuelistctrl drawitem lpdrawitemstruct theapp isrunning lpdrawitemstruct itemdata fromhandle lpdrawitemstruct bctrlfocused getfocus getstyle lvs_showselalways lpdrawitemstruct itemstate ods_selected bctrlfocused setbkcolor m_crhighlight setbkcolor m_crnohighlight setbkcolor getbkcolor cupdownclient cupdownclient lpdrawitemstruct itemdata cmemdc lpdrawitemstruct rcitem cfont poldfont selectobject getfont crect cur_rec lpdrawitemstruct rcitem croldtextcolor settextcolor lpdrawitemstruct itemstate ods_selected m_crhighlighttext m_crwindowtext ioldbkmode m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd ioldbkmode setbkmode ioldbkmode cknownfile theapp getfilebyid getuploadfileid cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount cur_rec cur_rec cur_rec cstring icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent iscolumnhidden icolumn cur_rec getcolumnwidth icolumn icolumn isfriend getclientsoft so_edonkeyhybrid getscoreratio getclientsoft so_mldonkey getscoreratio getclientsoft so_shareaza getscoreratio getclientsoft so_amule getscoreratio getclientsoft so_lphant getscoreratio extprotocolavailable getscoreratio getscoreratio cur_rec cur_rec ild_normal getcurrentidentstate is_identified getusername cur_rec drawtext getlength cur_rec dlc_dt_text cur_rec getfilename _t getuppriority pr_verylow getresstring ids_prioverylow pr_low isautouppriority getresstring ids_prioautolow getresstring ids_priolow pr_normal isautouppriority getresstring ids_prioautonormal getresstring ids_prionormal pr_high isautouppriority getresstring ids_prioautohigh getresstring ids_priohigh pr_veryhigh getresstring ids_priorelease _t _t getscore haslowid m_baddnextconnect _t getscore _t getscore _t getscore _t getaskedcount castsecondstohm gettickcount getlastuprequest castsecondstohm gettickcount getwaitstarttime isbanned getresstring ids_yes getresstring ids_no getuppartcount cur_rec cur_rec drawupstatusbar cur_rec theprefs useflatbar cur_rec cur_rec icolumn icolumn drawtext getlength cur_rec dlc_dt_text cur_rec getcolumnwidth icolumn lpdrawitemstruct itemstate ods_selected outline_rec lpdrawitemstruct rcitem outline_rec outline_rec framerect outline_rec cbrush getbkcolor outline_rec outline_rec outline_rec outline_rec bctrlfocused framerect outline_rec cbrush m_crfocusline framerect outline_rec cbrush m_crnofocusline m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor void c queue list ctrl on sys color change c mule list ctrl on sys color change set all icons cqueuelistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons void c queue list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr barry store sort order in preferences determine ascending based on whether already sorted on this column bool sort ascending get sort item pnm list view i sub item true get sort ascending sort table update sort history pnm list view i sub item sort ascending 0 100 100 set sort arrow pnm list view i sub item sort ascending sort items sort proc pnm list view i sub item sort ascending 0 100 p result 0 cqueuelistctrl oncolumnclick presult nm_listview pnmlistview nm_listview sortascending getsortitem pnmlistview isubitem getsortascending updatesorthistory pnmlistview isubitem sortascending setsortarrow pnmlistview isubitem sortascending sortitems sortproc pnmlistview isubitem sortascending presult void c queue list ctrl on context menu c wnd p wnd c point point int i sel get next item 1 lvis selected lvis focused const c up down client client i sel 1 c up down client get item data i sel null c title menu client menu client menu create popup menu client menu add menu title get res string ids clients true client menu append menu mf string client mf enabled mf grayed mp detail get res string ids showdetails t clientdetails client menu set default item mp detail client menu append menu mf string client client is ed2k client client is friend mf enabled mf grayed mp addfriend get res string ids addfriend t addfriend client menu append menu mf string client client is ed2k client mf enabled mf grayed mp message get res string ids send msg t sendmessage client menu append menu mf string client client is ed2k client client get view shared files support mf enabled mf grayed mp showlist get res string ids viewfiles t viewfiles client menu append menu mf string client client is ed2k client client is banned mf enabled mf grayed mp unban get res string ids unban if kademlia c kademlia is running kademlia c kademlia is connected client menu append menu mf string client client is ed2k client client get kad port 0 mf enabled mf grayed mp boot get res string ids bootstrap client menu append menu mf string get item count 0 mf enabled mf grayed mp find get res string ids find t search get popup menu pos this point client menu track popup menu tpm leftalign tpm rightbutton point x point y this cqueuelistctrl oncontextmenu cwnd pwnd cpoint isel getnextitem lvis_selected lvis_focused cupdownclient isel cupdownclient getitemdata isel ctitlemenu clientmenu clientmenu createpopupmenu clientmenu addmenutitle getresstring ids_clients clientmenu appendmenu mf_string mf_enabled mf_grayed mp_detail getresstring ids_showdetails _t clientmenu setdefaultitem mp_detail clientmenu appendmenu mf_string ised2kclient isfriend mf_enabled mf_grayed mp_addfriend getresstring ids_addfriend _t clientmenu appendmenu mf_string ised2kclient mf_enabled mf_grayed mp_message getresstring ids_send_msg _t clientmenu appendmenu mf_string ised2kclient getviewsharedfilessupport mf_enabled mf_grayed mp_showlist getresstring ids_viewfiles _t clientmenu appendmenu mf_string ised2kclient isbanned mf_enabled mf_grayed mp_unban getresstring ids_unban ckademlia isrunning ckademlia isconnected clientmenu appendmenu mf_string ised2kclient getkadport mf_enabled mf_grayed mp_boot getresstring ids_bootstrap clientmenu appendmenu mf_string getitemcount mf_enabled mf_grayed mp_find getresstring ids_find _t getpopupmenupos clientmenu trackpopupmenu tpm_leftalign tpm_rightbutton void c queue list ctrl onnm dblclk nmhdr pnmhdr lresult p result int i sel get next item 1 lvis selected lvis focused if i sel 1 c up down client client c up down client get item data i sel if client c client detail dialog dialog client this dialog do modal p result 0 cqueuelistctrl onnmdblclk presult isel getnextitem lvis_selected lvis_focused isel cupdownclient cupdownclient getitemdata isel cclientdetaildialog domodal presult void c queue list ctrl on get disp info nmhdr pnmhdr lresult p result nmlvdispinfo p disp info reinterpret cast nmlvdispinfo pnmhdr if the app emuledlg is running although we have an owner drawn listview control we store the text for the primary item in the listview to be capable of quick searching those items via the keyboard because our listview items may change their contents we do this via a text callback function the listview control will send us the lvn dispinfo notification if it needs to know the contents of the primary item but the listview control sends this notification all the time even if we do not search for an item at least this notification is only sent for the visible items and not for all items in the list though because this function is invoked very often no not put any time consuming code here in if p disp info item mask lvif text const c up down client p client reinterpret cast c up down client p disp info item l param if p client null switch p disp info item i sub item case 0 if p client get user name null p disp info item cch text max 0 tcsncpy p disp info item psz text p client get user name p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break default shouldn t happen p disp info item psz text 0 t 0 break p result 0 cqueuelistctrl ongetdispinfo presult pdispinfo reinterpret_cast theapp isrunning lvn_dispinfo pdispinfo lvif_text cupdownclient pclient reinterpret_cast cupdownclient pdispinfo lparam pclient pdispinfo isubitem pclient getusername pdispinfo cchtextmax _tcsncpy pdispinfo psztext pclient getusername pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t pdispinfo psztext _t presult void callback c queue list ctrl queue update timer hwnd hwnd uint ui msg uint id event dword dw time note always handle all type of mfc exceptions in timer procs otherwise we ll get mem leaks try if the app emuledlg is running don t do anything if the app is shutting down can cause unhandled exceptions the prefs get update queue list the app emuledlg activewnd the app emuledlg transferwnd the app emuledlg transferwnd queuelistctrl is window visible return const c up down client update the app uploadqueue get next client null while update the app emuledlg transferwnd queuelistctrl refresh client update update the app uploadqueue get next client update catch dflt exceptions t c queue list ctrl queue update timer cqueuelistctrl queueupdatetimer uimsg idevent dwtime timerprocs theapp isrunning theprefs getupdatequeuelist theapp theapp theapp iswindowvisible cupdownclient theapp getnextclient theapp refreshclient theapp getnextclient catch_dflt_exceptions _t cqueuelistctrl queueupdatetimer c client version info c string strpc encoded version m nvermajor uint cvi ignored m nverminor uint cvi ignored m nverupdate uint cvi ignored m nverbuild uint cvi ignored m clienttypemajor so unknown m clienttypeminor so unknown int pos seperator strpc encoded version find 1 if pos seperator 1 strpc encoded version get length pos seperator 2 the app queue debug log line false t peer cache error bad version info in peer cache descriptor found s strpc encoded version return c string str client type strpc encoded version left pos seperator trim c string str version number strpc encoded version mid pos seperator 1 trim if str client type compare no case t e mule 0 m clienttypemajor so emule else if str client type compare no case t e donkey 0 m clienttypemajor so edonkeyhybrid can add more types here else the app queue debug log line false t peer cache warning unknown clienttype in descriptor file found m clienttypemajor so unknown int cur pos2 0 c string str number str version number tokenize t cur pos2 if str number is empty return else if str number t m nvermajor uint 1 else m nvermajor tstoi str number str number str version number tokenize t cur pos2 if str number is empty return else if str number t m nverminor uint 1 else m nverminor tstoi str number str number str version number tokenize t cur pos2 if str number is empty return else if str number t m nverupdate uint 1 else m nverupdate tstoi str number str number str version number tokenize t cur pos2 if str number is empty return else if str number t m nverbuild uint 1 else m nverbuild tstoi str number cclientversioninfo cstring strpcencodedversion m_nvermajor cvi_ignored m_nverminor cvi_ignored m_nverupdate cvi_ignored m_nverbuild cvi_ignored m_clienttypemajor so_unknown m_clienttypeminor so_unknown posseperator strpcencodedversion posseperator strpcencodedversion getlength posseperator theapp queuedebuglogline _t peercache peercache strpcencodedversion cstring strclienttype strpcencodedversion posseperator cstring strversionnumber strpcencodedversion posseperator strclienttype comparenocase _t emule m_clienttypemajor so_emule strclienttype comparenocase _t edonkey m_clienttypemajor so_edonkeyhybrid theapp queuedebuglogline _t peercache m_clienttypemajor so_unknown curpos2 cstring strnumber strversionnumber _t curpos2 strnumber isempty strnumber _t m_nvermajor m_nvermajor _tstoi strnumber strnumber strversionnumber _t curpos2 strnumber isempty strnumber _t m_nverminor m_nverminor _tstoi strnumber strnumber strversionnumber _t curpos2 strnumber isempty strnumber _t m_nverupdate m_nverupdate _tstoi strnumber strnumber strversionnumber _t curpos2 strnumber isempty strnumber _t m_nverbuild m_nverbuild _tstoi strnumber c client version info uint32 dw tag version info uint n client major uint n client maj version dw tag version info 17 0x7f uint n client min version dw tag version info 10 0x7f uint n client up version dw tag version info 7 0x07 c client version info n client maj version n client min version n client up version uint cvi ignored n client major so unknown cclientversioninfo dwtagversioninfo nclientmajor nclientmajversion dwtagversioninfo nclientminversion dwtagversioninfo nclientupversion dwtagversioninfo cclientversioninfo nclientmajversion nclientminversion nclientupversion cvi_ignored nclientmajor so_unknown c client version info uint32 n ver major uint32 n ver minor uint32 n ver update uint32 n ver build uint32 client type major uint32 client type minor so unknown m nvermajor n ver major m nverminor n ver minor m nverupdate n ver update m nverbuild n ver build m clienttypemajor client type major m clienttypeminor client type minor cclientversioninfo nvermajor nverminor nverupdate nverbuild clienttypemajor clienttypeminor so_unknown m_nvermajor nvermajor m_nverminor nverminor m_nverupdate nverupdate m_nverbuild nverbuild m_clienttypemajor clienttypemajor m_clienttypeminor clienttypeminor c client version info c client version info uint cvi ignored uint cvi ignored uint cvi ignored uint cvi ignored so unknown so unknown cclientversioninfo cclientversioninfo cvi_ignored cvi_ignored cvi_ignored cvi_ignored so_unknown so_unknown c client version info operator const c client version info cv m nvermajor cv m nvermajor m nverminor cv m nverminor m nverupdate cv m nverupdate m nverbuild cv m nverbuild m clienttypemajor cv m clienttypemajor m clienttypeminor cv m clienttypeminor return this cclientversioninfo cclientversioninfo m_nvermajor m_nvermajor m_nverminor m_nverminor m_nverupdate m_nverupdate m_nverbuild m_nverbuild m_clienttypemajor m_clienttypemajor m_clienttypeminor m_clienttypeminor explicit c msg box exception lpctstr psz msg uint u type mb iconwarning uint u helpid 0 m strmsg psz msg m utype u type m uhelpid u helpid cmsgboxexception pszmsg utype mb_iconwarning uhelpid m_strmsg pszmsg m_utype utype m_uhelpid uhelpid c client exception lpctstr psz msg bool b delete m strmsg psz msg m bdelete b delete cclientexception pszmsg bdelete m_strmsg pszmsg m_bdelete bdelete c log file c log file void m strfilepath m umaxfilesize uint 1 m ubyteswritten 0 m tstarted 0 m fp null m binopencall false assert unicode 0 m efileformat unicode clogfile clogfile m_strfilepath m_umaxfilesize m_ubyteswritten m_tstarted m_fp m_binopencall m_efileformat c log file c log file close clogfile clogfile bool c log file is open const return m fp null clogfile isopen m_fp const c string c log file get file path const return m strfilepath cstring clogfile getfilepath m_strfilepath bool c log file set file path lpctstr psz file path if is open return false m strfilepath psz file path return true clogfile setfilepath pszfilepath isopen m_strfilepath pszfilepath void c log file set max file size uint u max file size if u max file size 0 u max file size uint 1 else if u max file size 0x10000 u max file size 0x10000 m umaxfilesize u max file size clogfile setmaxfilesize umaxfilesize umaxfilesize umaxfilesize umaxfilesize umaxfilesize m_umaxfilesize umaxfilesize bool c log file set file format e log file format e file format if e file format unicode e file format utf8 assert 0 return false if m fp null return false can t change file format on the fly m efileformat e file format return true clogfile setfileformat elogfileformat efileformat efileformat efileformat m_fp m_efileformat efileformat bool c log file create lpctstr psz file path uint u max file size e log file format e file format close m strfilepath psz file path m umaxfilesize u max file size m efileformat e file format return open clogfile pszfilepath umaxfilesize elogfileformat efileformat m_strfilepath pszfilepath m_umaxfilesize umaxfilesize m_efileformat efileformat bool c log file open if m fp null return true m fp tfsopen m strfilepath t a b sh denywr if m fp null m tstarted time null m ubyteswritten filelength fileno m fp if m ubyteswritten 0 if m efileformat unicode write unicode byte order mark 0xfeff fputwc 0xfeff m fp else assert m efileformat utf8 could write utf 8 header else if m ubyteswritten sizeof word check for unicode byte order mark 0xfeff word wbom if fread wbom sizeof wbom 1 m fp 1 if wbom 0xfeff m efileformat unicode log file already in unicode format fseek m fp 0 seek end actually not needed because file is opened in append mode else if wbom 0xfeff m efileformat unicode log file already in utf 8 format fseek m fp 0 seek end actually not needed because file is opened in append mode else log file does not have the required format create a new one with the req format assert m efileformat unicode wbom 0xfeff m efileformat utf8 wbom 0xfeff assert m binopencall if m binopencall just for safety m binopencall true start new log file m binopencall false return m fp null clogfile m_fp m_fp _tfsopen m_strfilepath _t _sh_denywr m_fp m_tstarted m_ubyteswritten _filelength m_fp m_ubyteswritten m_efileformat m_fp m_efileformat m_ubyteswritten m_fp m_efileformat m_fp seek_end m_efileformat m_fp seek_end m_efileformat m_efileformat m_binopencall m_binopencall m_binopencall startnewlogfile m_binopencall m_fp bool c log file close if m fp null return true bool b result fclose m fp 0 m fp null m tstarted 0 m ubyteswritten 0 return b result clogfile m_fp bresult m_fp m_fp m_tstarted m_ubyteswritten bresult bool c log file log lpctstr psz msg int i len if m fp null return false size t u written if m efileformat unicode don t use fputs filelength gives poor performance size t u to write i len 1 tcslen psz msg size t i len sizeof tchar u written fwrite psz msg 1 u to write m fp else t unicode toutf8 2048 utf8 psz msg i len u written fwrite lpcstr utf8 1 utf8 get length m fp bool b result ferror m fp m ubyteswritten u written if m ubyteswritten m umaxfilesize start new log file else fflush m fp return b result clogfile pszmsg ilen m_fp size_t uwritten m_efileformat _filelength size_t utowrite ilen _tcslen pszmsg size_t ilen uwritten pszmsg utowrite m_fp tunicodetoutf8 pszmsg ilen uwritten getlength m_fp bresult m_fp m_ubyteswritten uwritten m_ubyteswritten m_umaxfilesize startnewlogfile m_fp bresult bool c log file logf lpctstr psz fmt if m fp null return false va list argp va start argp psz fmt tchar sz msg 1024 vsntprintf sz msg arrsize sz msg psz fmt argp tchar sz full msg 1060 int i len sntprintf sz full msg arrsize sz full msg t s s r n c time get current time format the prefs get date time format4 log sz msg va end argp return log sz full msg i len clogfile pszfmt m_fp va_list va_start pszfmt szmsg _vsntprintf szmsg szmsg pszfmt szfullmsg ilen _sntprintf szfullmsg szfullmsg _t ctime getcurrenttime theprefs getdatetimeformat4log szmsg va_end szfullmsg ilen void c log file start new log file time t t started m tstarted close tchar sz date log started 40 tcsftime sz date log started arrsize sz date log started t y m d h m s localtime t started tchar sz drv max drive tchar sz dir max dir tchar sz nam max fname tchar sz ext max ext tsplitpath m strfilepath sz drv sz dir sz nam sz ext c string str log bak nam str log bak nam sz nam str log bak nam t str log bak nam sz date log started tchar sz log bak file path max path tmakepath sz log bak file path sz drv sz dir str log bak nam sz ext if trename m strfilepath sz log bak file path 0 tremove m strfilepath open clogfile startnewlogfile time_t tstarted m_tstarted szdatelogstarted _tcsftime szdatelogstarted szdatelogstarted _t tstarted szdrv _max_drive szdir _max_dir sznam _max_fname szext _max_ext _tsplitpath m_strfilepath szdrv szdir sznam szext cstring strlogbaknam strlogbaknam sznam strlogbaknam _t strlogbaknam szdatelogstarted szlogbakfilepath max_path _tmakepath szlogbakfilepath szdrv szdir strlogbaknam szext _trename m_strfilepath szlogbakfilepath _tremove m_strfilepath uint8 c file dataio readu int8 uint8 n val read n val sizeof n val return n val cfiledataio readuint8 nval nval nval nval uint16 c file dataio readu int16 uint16 n val read n val sizeof n val return n val cfiledataio readuint16 nval nval nval nval uint32 c file dataio readu int32 uint32 n val read n val sizeof n val return n val cfiledataio readuint32 nval nval nval nval uint64 c file dataio readu int64 uint64 n val read n val sizeof n val return n val cfiledataio readuint64 nval nval nval nval void c file dataio readu int128 kademlia cu int128 p val read p val get data ptr 16 cfiledataio readuint128 cuint128 pval pval getdataptr void c file dataio read hash16 uchar p val read p val 16 cfiledataio readhash16 pval pval c string c file dataio read string bool b optutf8 uint u len readu int16 return read string b optutf8 u len cstring cfiledataio readstring boptutf8 ulen readuint16 readstring boptutf8 ulen c string c file dataio read string bool b optutf8 uint u raw size const uint u max short raw size short raw ed2k utf8 str if u raw size u max short raw size char ac raw u max short raw size read ac raw u raw size if u raw size 3 uchar ac raw 0 0xefu uchar ac raw 1 0xbbu uchar ac raw 2 0xbfu wchar awc u max short raw size int i chars byte stream to wide char ac raw 3 u raw size 3 awc arrsize awc if i chars 0 return c stringw awc i chars else if b optutf8 wchar awc u max short raw size int i chars byte stream to wide char ac raw u raw size awc arrsize awc int i chars utf8towc ac raw u raw size awc arrsize awc if i chars 0 return c stringw awc i chars return c stringw ac raw u raw size use local codepage else array char ac raw u raw size read ac raw u raw size if u raw size 3 uchar ac raw 0 0xefu uchar ac raw 1 0xbbu uchar ac raw 2 0xbfu array wchar awc u raw size int i chars byte stream to wide char ac raw 3 u raw size 3 awc u raw size if i chars 0 return c stringw awc i chars else if b optutf8 array wchar awc u raw size int i chars byte stream to wide char ac raw u raw size awc u raw size int i chars utf8towc ac raw u raw size awc u raw size if i chars 0 return c stringw awc i chars return c stringw ac raw u raw size use local codepage cstring cfiledataio readstring boptutf8 urawsize umaxshortrawsize short_raw_ed2k_utf8_str urawsize umaxshortrawsize acraw umaxshortrawsize acraw urawsize urawsize acraw acraw acraw umaxshortrawsize ichars bytestreamtowidechar acraw urawsize ichars cstringw ichars boptutf8 umaxshortrawsize ichars bytestreamtowidechar acraw urawsize ichars acraw urawsize ichars cstringw ichars cstringw acraw urawsize acraw urawsize acraw urawsize urawsize acraw acraw acraw urawsize ichars bytestreamtowidechar acraw urawsize urawsize ichars cstringw ichars boptutf8 urawsize ichars bytestreamtowidechar acraw urawsize urawsize ichars acraw urawsize urawsize ichars cstringw ichars cstringw acraw urawsize void c file dataio writeu int8 uint8 n val write n val sizeof n val cfiledataio writeuint8 nval nval nval void c file dataio writeu int16 uint16 n val write n val sizeof n val cfiledataio writeuint16 nval nval nval void c file dataio writeu int32 uint32 n val write n val sizeof n val cfiledataio writeuint32 nval nval nval void c file dataio writeu int64 uint64 n val write n val sizeof n val cfiledataio writeuint64 nval nval nval void c file dataio writeu int128 const kademlia cu int128 p val write p val get data 16 cfiledataio writeuint128 cuint128 pval pval getdata void c file dataio write hash16 const uchar p val write p val 16 cfiledataio writehash16 pval pval void c file dataio write string const c string rstr e utf8 str e encode define write str len n writeu int16 uint16 n if e encode utf8str raw c unicode toutf8 utf8 rstr write str len utf8 get length write lpcstr utf8 utf8 get length else if e encode utf8str optbom if needutf8 string rstr c unicode tobomutf8 bomutf8 rstr write str len bomutf8 get length write lpcstr bomutf8 bomutf8 get length else c unicode to multi byte mb rstr write str len mb get length write lpcstr mb mb get length else c unicode to multi byte mb rstr write str len mb get length write lpcstr mb mb get length undef write str len cfiledataio writestring cstring eutf8str eencode write_str_len writeuint16 eencode utf8strraw cunicodetoutf8 write_str_len getlength getlength eencode utf8stroptbom needutf8string cunicodetobomutf8 write_str_len getlength getlength cunicodetomultibyte write_str_len getlength getlength cunicodetomultibyte write_str_len getlength getlength write_str_len void c file dataio write string lpcstr psz uint u len strlen psz writeu int16 uint16 u len write psz u len cfiledataio writestring ulen writeuint16 ulen ulen void c file dataio write long string const c string rstr e utf8 str e encode define write str len n writeu int32 n if e encode utf8str raw c unicode toutf8 utf8 rstr write str len utf8 get length write lpcstr utf8 utf8 get length else if e encode utf8str optbom if needutf8 string rstr c unicode tobomutf8 bomutf8 rstr write str len bomutf8 get length write lpcstr bomutf8 bomutf8 get length else c unicode to multi byte mb rstr write str len mb get length write lpcstr mb mb get length else c unicode to multi byte mb rstr write str len mb get length write lpcstr mb mb get length undef write str len cfiledataio writelongstring cstring eutf8str eencode write_str_len writeuint32 eencode utf8strraw cunicodetoutf8 write_str_len getlength getlength eencode utf8stroptbom needutf8string cunicodetobomutf8 write_str_len getlength getlength cunicodetomultibyte write_str_len getlength getlength cunicodetomultibyte write_str_len getlength getlength write_str_len void c file dataio write long string lpcstr psz uint u len strlen psz writeu int32 u len write psz u len cfiledataio writelongstring ulen writeuint32 ulen ulen uint c safe file read void lp buf uint n count if get position n count get length afx throw file exception c file exception end of file 0 get file name return c file read lp buf n count csafefile lpbuf ncount getposition ncount getlength afxthrowfileexception cfileexception endoffile getfilename cfile lpbuf ncount void c safe file write const void lp buf uint n count c file write lp buf n count csafefile lpbuf ncount cfile lpbuf ncount ulonglong c safe file seek longlong l off uint n from return c file seek l off n from csafefile loff nfrom cfile loff nfrom ulonglong c safe file get position const return c file get position csafefile getposition cfile getposition ulonglong c safe file get length const return c file get length csafefile getlength cfile getlength uint c safe mem file read void lp buf uint n count if m nposition n count m nfilesize afx throw file exception c file exception end of file 0 get file name return c mem file read lp buf n count csafememfile lpbuf ncount m_nposition ncount m_nfilesize afxthrowfileexception cfileexception endoffile getfilename cmemfile lpbuf ncount void c safe mem file write const void lp buf uint n count c mem file write lp buf n count csafememfile lpbuf ncount cmemfile lpbuf ncount ulonglong c safe mem file seek longlong l off uint n from return c mem file seek l off n from csafememfile loff nfrom cmemfile loff nfrom ulonglong c safe mem file get position const return c mem file get position csafememfile getposition cmemfile getposition ulonglong c safe mem file get length const return c mem file get length csafememfile getlength cmemfile getlength uint8 c safe mem file readu int8 if m nposition sizeof uint8 m nfilesize afx throw file exception c file exception end of file 0 get file name return m lpbuffer m nposition csafememfile readuint8 m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename m_lpbuffer m_nposition uint16 c safe mem file readu int16 if m nposition sizeof uint16 m nfilesize afx throw file exception c file exception end of file 0 get file name uint16 n result uint16 m lpbuffer m nposition m nposition sizeof uint16 return n result csafememfile readuint16 m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename nresult m_lpbuffer m_nposition m_nposition nresult uint32 c safe mem file readu int32 if m nposition sizeof uint32 m nfilesize afx throw file exception c file exception end of file 0 get file name uint32 n result uint32 m lpbuffer m nposition m nposition sizeof uint32 return n result csafememfile readuint32 m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename nresult m_lpbuffer m_nposition m_nposition nresult uint64 c safe mem file readu int64 if m nposition sizeof uint64 m nfilesize afx throw file exception c file exception end of file 0 get file name uint64 n result uint64 m lpbuffer m nposition m nposition sizeof uint64 return n result csafememfile readuint64 m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename nresult m_lpbuffer m_nposition m_nposition nresult void c safe mem file readu int128 kademlia cu int128 p val if m nposition sizeof uint32 4 m nfilesize afx throw file exception c file exception end of file 0 get file name uint32 pu int32 val uint32 p val get data ptr const uint32 pu int32 uint32 m lpbuffer m nposition pu int32 val 0 pu int32 0 pu int32 val 1 pu int32 1 pu int32 val 2 pu int32 2 pu int32 val 3 pu int32 3 m nposition sizeof uint32 4 csafememfile readuint128 cuint128 pval m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename puint32val pval getdataptr puint32 m_lpbuffer m_nposition puint32val puint32 puint32val puint32 puint32val puint32 puint32val puint32 m_nposition void c safe mem file read hash16 uchar p val if m nposition sizeof uint32 4 m nfilesize afx throw file exception c file exception end of file 0 get file name const uint32 pu int32 uint32 m lpbuffer m nposition uint32 p val 0 pu int32 0 uint32 p val 1 pu int32 1 uint32 p val 2 pu int32 2 uint32 p val 3 pu int32 3 m nposition sizeof uint32 4 csafememfile readhash16 pval m_nposition m_nfilesize afxthrowfileexception cfileexception endoffile getfilename puint32 m_lpbuffer m_nposition pval puint32 pval puint32 pval puint32 pval puint32 m_nposition void c safe mem file writeu int8 uint8 n val if m nposition sizeof uint8 m nbuffersize grow file m nposition sizeof uint8 m lpbuffer m nposition n val if m nposition m nfilesize m nfilesize m nposition csafememfile writeuint8 nval m_nposition m_nbuffersize growfile m_nposition m_lpbuffer m_nposition nval m_nposition m_nfilesize m_nfilesize m_nposition void c safe mem file writeu int16 uint16 n val if m nposition sizeof uint16 m nbuffersize grow file m nposition sizeof uint16 uint16 m lpbuffer m nposition n val m nposition sizeof uint16 if m nposition m nfilesize m nfilesize m nposition csafememfile writeuint16 nval m_nposition m_nbuffersize growfile m_nposition m_lpbuffer m_nposition nval m_nposition m_nposition m_nfilesize m_nfilesize m_nposition void c safe mem file writeu int32 uint32 n val if m nposition sizeof uint32 m nbuffersize grow file m nposition sizeof uint32 uint32 m lpbuffer m nposition n val m nposition sizeof uint32 if m nposition m nfilesize m nfilesize m nposition csafememfile writeuint32 nval m_nposition m_nbuffersize growfile m_nposition m_lpbuffer m_nposition nval m_nposition m_nposition m_nfilesize m_nfilesize m_nposition void c safe mem file writeu int64 uint64 n val if m nposition sizeof uint64 m nbuffersize grow file m nposition sizeof uint64 uint64 m lpbuffer m nposition n val m nposition sizeof uint64 if m nposition m nfilesize m nfilesize m nposition csafememfile writeuint64 nval m_nposition m_nbuffersize growfile m_nposition m_lpbuffer m_nposition nval m_nposition m_nposition m_nfilesize m_nfilesize m_nposition void c safe mem file writeu int128 const kademlia cu int128 p val if m nposition sizeof uint32 4 m nbuffersize grow file m nposition sizeof uint32 4 uint32 pu int32 uint32 m lpbuffer m nposition const uint32 pu int32 val uint32 p val get data pu int32 0 pu int32 val 0 pu int32 1 pu int32 val 1 pu int32 2 pu int32 val 2 pu int32 3 pu int32 val 3 m nposition sizeof uint32 4 if m nposition m nfilesize m nfilesize m nposition csafememfile writeuint128 cuint128 pval m_nposition m_nbuffersize growfile m_nposition puint32 m_lpbuffer m_nposition puint32val pval getdata puint32 puint32val puint32 puint32val puint32 puint32val puint32 puint32val m_nposition m_nposition m_nfilesize m_nfilesize m_nposition void c safe mem file write hash16 const uchar p val if m nposition sizeof uint32 4 m nbuffersize grow file m nposition sizeof uint32 4 uint32 pu int32 uint32 m lpbuffer m nposition pu int32 0 uint32 p val 0 pu int32 1 uint32 p val 1 pu int32 2 uint32 p val 2 pu int32 3 uint32 p val 3 m nposition sizeof uint32 4 if m nposition m nfilesize m nfilesize m nposition csafememfile writehash16 pval m_nposition m_nbuffersize growfile m_nposition puint32 m_lpbuffer m_nposition puint32 pval puint32 pval puint32 pval puint32 pval m_nposition m_nposition m_nfilesize m_nfilesize m_nposition uint c safe buffered file read void lp buf uint n count that s terrible slow if get position n count this get length afx throw file exception c file exception end of file 0 get file name uint u read c stdio file read lp buf n count if u read n count afx throw file exception c file exception end of file 0 get file name return u read csafebufferedfile lpbuf ncount getposition ncount getlength afxthrowfileexception cfileexception endoffile getfilename uread cstdiofile lpbuf ncount uread ncount afxthrowfileexception cfileexception endoffile getfilename uread void c safe buffered file write const void lp buf uint n count c stdio file write lp buf n count csafebufferedfile lpbuf ncount cstdiofile lpbuf ncount ulonglong c safe buffered file seek longlong l off uint n from return c stdio file seek l off n from csafebufferedfile loff nfrom cstdiofile loff nfrom ulonglong c safe buffered file get position const return c stdio file get position csafebufferedfile getposition cstdiofile getposition ulonglong c safe buffered file get length const return c stdio file get length csafebufferedfile getlength cstdiofile getlength int c safe buffered file printf lpctstr psz fmt va list args va start args psz fmt int i result vftprintf m pstream psz fmt args va end args if i result 0 afx throw file exception c file exception generic doserrno m strfilename return i result csafebufferedfile pszfmt va_list va_start pszfmt iresult _vftprintf m_pstream pszfmt va_end iresult afxthrowfileexception cfileexception _doserrno m_strfilename iresult packet packet uint8 protocol m bsplitted false m blastsplitted false m bfrompf false size 0 p buffer 0 completebuffer 0 tempbuffer 0 opcode 0x00 prot protocol m bpacked false m_bsplitted m_blastsplitted m_bfrompf pbuffer m_bpacked packet packet char header m bsplitted false m bpacked false m blastsplitted false m bfrompf false tempbuffer 0 p buffer 0 completebuffer 0 header struct head header struct header size head packetlength 1 opcode head command prot head e donkeyid m_bsplitted m_bpacked m_blastsplitted m_bfrompf pbuffer header_struct header_struct edonkeyid packet packet c mem file datafile uint8 protocol uint8 uc opcode m bsplitted false m bpacked false m blastsplitted false m bfrompf false size uint datafile get length completebuffer new char uint datafile get length 10 p buffer completebuffer 6 byte tmp datafile detach memcpy p buffer tmp size free tmp tempbuffer 0 opcode uc opcode prot protocol cmemfile ucopcode m_bsplitted m_bpacked m_blastsplitted m_bfrompf getlength getlength pbuffer pbuffer ucopcode packet packet uint8 in opcode uint32 in size uint8 protocol bool b from part file m bfrompf b from part file m bsplitted false m bpacked false m blastsplitted false tempbuffer 0 if in size completebuffer new char in size 10 p buffer completebuffer 6 memset completebuffer 0 in size 10 else p buffer 0 completebuffer 0 opcode in opcode size in size prot protocol in_opcode in_size bfrompartfile m_bfrompf bfrompartfile m_bsplitted m_bpacked m_blastsplitted in_size in_size pbuffer in_size pbuffer in_opcode in_size packet packet char p packet part uint32 n size bool b last bool b from part file only used for splitted packets m bfrompf b from part file m bsplitted true m bpacked false m blastsplitted b last tempbuffer 0 p buffer 0 completebuffer p packet part size n size 6 opcode 0x00 prot 0x00 ppacketpart nsize blast bfrompartfile m_bfrompf bfrompartfile m_bsplitted m_bpacked m_blastsplitted blast pbuffer ppacketpart nsize char packet get header assert m bsplitted header struct header header struct head header command opcode header e donkeyid prot header packetlength size 1 return head getheader m_bsplitted header_struct header_struct edonkeyid char packet getudp header assert m bsplitted udp header struct header udp header struct head header command opcode header e donkeyid prot return head getudpheader m_bsplitted udp_header_struct udp_header_struct edonkeyid char packet get packet if completebuffer if m bsplitted memcpy completebuffer get header 6 return completebuffer else delete tempbuffer tempbuffer null new may throw an exception tempbuffer new char size 10 memcpy tempbuffer get header 6 memcpy tempbuffer 6 p buffer size return tempbuffer getpacket m_bsplitted getheader getheader pbuffer char packet detach packet if completebuffer if m bsplitted memcpy completebuffer get header 6 char result completebuffer completebuffer 0 p buffer 0 return result else delete tempbuffer tempbuffer null new may throw an exception tempbuffer new char size 10 memcpy tempbuffer get header 6 memcpy tempbuffer 6 p buffer size char result tempbuffer tempbuffer 0 return result detachpacket m_bsplitted getheader pbuffer getheader pbuffer void packet pack packet assert m bsplitted u longf newsize size 300 byte output new byte newsize uint result compress2 output newsize byte p buffer size z best compression if result z ok size newsize delete output return if prot op kademliaheader prot op kademliapackedprot else prot op packedprot memcpy p buffer output newsize size newsize delete output m bpacked true packpacket m_bsplitted ulongf pbuffer z_best_compression z_ok op_kademliaheader op_kademliapackedprot op_packedprot pbuffer m_bpacked bool packet un pack packet uint u max decompressed size assert prot op packedprot prot op kademliapackedprot uint32 n new size size 10 300 if n new size u max decompressed size assert 0 n new size u max decompressed size byte unpack new byte n new size u longf unpackedsize n new size uint result uncompress unpack unpackedsize byte p buffer size if result z ok assert completebuffer null assert p buffer null size unpackedsize delete p buffer p buffer char unpack if prot op kademliapackedprot prot op kademliaheader else prot op emuleprot return true delete unpack return false unpackpacket umaxdecompressedsize op_packedprot op_kademliapackedprot nnewsize nnewsize umaxdecompressedsize nnewsize umaxdecompressedsize nnewsize ulongf nnewsize pbuffer z_ok pbuffer pbuffer pbuffer op_kademliapackedprot op_kademliaheader op_emuleprot char c raw packet get header assert 0 return null crawpacket getheader char c raw packet getudp header assert 0 return null crawpacket getudpheader void c raw packet attach packet char p packet data uint u packet size bool b from part file assert p buffer null p buffer p packet data size u packet size m bfrompf b from part file crawpacket attachpacket ppacketdata upacketsize bfrompartfile pbuffer pbuffer ppacketdata upacketsize m_bfrompf bfrompartfile char c raw packet detach packet char p result p buffer p buffer null return p result crawpacket detachpacket presult pbuffer pbuffer presult c tag c tag lpcstr psz name uint64 u val bool b int64 assert u val 0xffffffff b int64 if b int64 m utype tagtype uint64 else m utype tagtype uint32 m uval u val m uname 0 m pszname nstrdup psz name m nblobsize 0 assert valid this ctag ctag pszname uval bint64 uval bint64 bint64 m_utype tagtype_uint64 m_utype tagtype_uint32 m_uval uval m_uname m_pszname pszname m_nblobsize assert_valid c tag c tag uint8 u name uint64 u val bool b int64 assert u val 0xffffffff b int64 if b int64 m utype tagtype uint64 else m utype tagtype uint32 m uval u val m uname u name m pszname null m nblobsize 0 assert valid this ctag ctag uname uval bint64 uval bint64 bint64 m_utype tagtype_uint64 m_utype tagtype_uint32 m_uval uval m_uname uname m_pszname m_nblobsize assert_valid c tag c tag lpcstr psz name lpctstr psz val m utype tagtype string m uname 0 m pszname nstrdup psz name m pstrval new c string psz val m nblobsize 0 assert valid this ctag ctag pszname pszval m_utype tagtype_string m_uname m_pszname pszname m_pstrval cstring pszval m_nblobsize assert_valid c tag c tag uint8 u name lpctstr psz val m utype tagtype string m uname u name m pszname null m pstrval new c string psz val m nblobsize 0 assert valid this ctag ctag uname pszval m_utype tagtype_string m_uname uname m_pszname m_pstrval cstring pszval m_nblobsize assert_valid c tag c tag lpcstr psz name const c string rstr val m utype tagtype string m uname 0 m pszname nstrdup psz name m pstrval new c string rstr val m nblobsize 0 assert valid this ctag ctag pszname cstring rstrval m_utype tagtype_string m_uname m_pszname pszname m_pstrval cstring rstrval m_nblobsize assert_valid c tag c tag uint8 u name const c string rstr val m utype tagtype string m uname u name m pszname null m pstrval new c string rstr val m nblobsize 0 assert valid this ctag ctag uname cstring rstrval m_utype tagtype_string m_uname uname m_pszname m_pstrval cstring rstrval m_nblobsize assert_valid c tag c tag uint8 u name const byte puc hash m utype tagtype hash m uname u name m pszname null m pdata new byte 16 md4cpy m pdata puc hash m nblobsize 0 assert valid this ctag ctag uname puchash m_utype tagtype_hash m_uname uname m_pszname m_pdata m_pdata puchash m_nblobsize assert_valid c tag c tag uint8 u name uint32 n size const byte puc data m utype tagtype blob m uname u name m pszname null m pdata new byte n size memcpy m pdata puc data n size m nblobsize n size assert valid this ctag ctag uname nsize pucdata m_utype tagtype_blob m_uname uname m_pszname m_pdata nsize m_pdata pucdata nsize m_nblobsize nsize assert_valid c tag c tag const c tag r tag m utype r tag m utype m uname r tag m uname m pszname r tag m pszname null nstrdup r tag m pszname null m nblobsize 0 if r tag is str m pstrval new c string r tag get str else if r tag is int m uval r tag get int else if r tag is int64 false m uval r tag get int64 else if r tag is float m fval r tag get float else if r tag is hash m pdata new byte 16 md4cpy m pdata r tag get hash else if r tag is blob m nblobsize r tag get blob size m pdata new byte r tag get blob size memcpy m pdata r tag get blob r tag get blob size else assert 0 m uval 0 assert valid this ctag ctag ctag rtag m_utype rtag m_utype m_uname rtag m_uname m_pszname rtag m_pszname rtag m_pszname m_nblobsize rtag isstr m_pstrval cstring rtag getstr rtag isint m_uval rtag getint rtag isint64 m_uval rtag getint64 rtag isfloat m_fval rtag getfloat rtag ishash m_pdata m_pdata rtag gethash rtag isblob m_nblobsize rtag getblobsize m_pdata rtag getblobsize m_pdata rtag getblob rtag getblobsize m_uval assert_valid c tag c tag c file dataio data bool b optutf8 m utype data readu int8 if m utype 0x80 m utype 0x7f m uname data readu int8 m pszname null else uint length data readu int16 if length 1 m uname data readu int8 m pszname null else m uname 0 m pszname new char length 1 try data read m pszname length catch c file exception ex delete m pszname throw ex m pszname length 0 m nblobsize 0 note it s very important that we read the entire packet data even if we do not use each tag otherwise we will get troubles when the packets are returned in a list like the search results from a server if m utype tagtype string m pstrval new c string data read string b optutf8 else if m utype tagtype uint32 m uval data readu int32 else if m utype tagtype uint64 m uval data readu int64 else if m utype tagtype uint16 m uval data readu int16 m utype tagtype uint32 else if m utype tagtype uint8 m uval data readu int8 m utype tagtype uint32 else if m utype tagtype float32 data read m fval 4 else if m utype tagtype str1 m utype tagtype str16 uint length m utype tagtype str1 1 m pstrval new c string data read string b optutf8 length m utype tagtype string else if m utype tagtype hash m pdata new byte 16 try data read m pdata 16 catch c file exception ex delete m pdata throw ex else if m utype tagtype bool trace note s reading bool tag n function data seek 1 c file current else if m utype tagtype boolarray trace note s reading bool array tag n function uint16 len data read len 2 07 apr 2004 e mule versions prior to 0 42e 29 used the formula len 7 8 data seek len 8 1 c file current else if m utype tagtype blob 07 apr 2004 e mule versions prior to 0 42e 29 handled the len as int16 m nblobsize data readu int32 if m nblobsize data get length data get position m pdata new byte m nblobsize data read m pdata m nblobsize else assert false m nblobsize 0 m pdata null else if m uname 0 trace s unknown tag type 0x 02x specialtag u n function m utype m uname else trace s unknown tag type 0x 02x name s n function m utype m pszname m uval 0 assert valid this ctag ctag cfiledataio boptutf8 m_utype readuint8 m_utype m_utype m_uname readuint8 m_pszname readuint16 m_uname readuint8 m_pszname m_uname m_pszname m_pszname cfileexception m_pszname m_pszname m_nblobsize m_utype tagtype_string m_pstrval cstring readstring boptutf8 m_utype tagtype_uint32 m_uval readuint32 m_utype tagtype_uint64 m_uval readuint64 m_utype tagtype_uint16 m_uval readuint16 m_utype tagtype_uint32 m_utype tagtype_uint8 m_uval readuint8 m_utype tagtype_uint32 m_utype tagtype_float32 m_fval m_utype tagtype_str1 m_utype tagtype_str16 m_utype tagtype_str1 m_pstrval cstring readstring boptutf8 m_utype tagtype_string m_utype tagtype_hash m_pdata m_pdata cfileexception m_pdata m_utype tagtype_bool __function__ cfile m_utype tagtype_boolarray __function__ emule cfile m_utype tagtype_blob emule m_nblobsize readuint32 m_nblobsize getlength getposition m_pdata m_nblobsize m_pdata m_nblobsize m_nblobsize m_pdata m_uname __function__ m_utype m_uname __function__ m_utype m_pszname m_uval assert_valid c tag c tag delete m pszname if is str delete m pstrval else if is hash delete m pdata else if is blob delete m pdata ctag ctag m_pszname isstr m_pstrval ishash m_pdata isblob m_pdata void c tag set int uint32 u val assert is int if is int m uval u val ctag setint uval isint isint m_uval uval void c tag set int64 uint64 u val assert is int64 true if is int64 true m uval u val m utype tagtype uint64 ctag setint64 uval isint64 isint64 m_uval uval m_utype tagtype_uint64 void c tag set str lpctstr psz val assert is str if is str delete m pstrval m pstrval null m pstrval new c string psz val ctag setstr pszval isstr isstr m_pstrval m_pstrval m_pstrval cstring pszval bool c tag write tag to file c file dataio file e utf8 str e str encode const assert valid this don t write tags of unknown types we wouldn t be able to read them in again and the met file would be corrupted if is str is int is float is blob is int64 file writeu int8 m utype if m pszname uint taglen strlen m pszname file writeu int16 uint16 taglen file write m pszname taglen else file writeu int16 1 file writeu int8 m uname if is str file write string get str e str encode else if is int file writeu int32 uint32 m uval else if is int64 false file writeu int64 m uval else if is float file write m fval 4 else if is blob note this will break backward compatibility with met files for e mule versions prior to 0 44a file writeu int32 m nblobsize file write m pdata m nblobsize todo support more tag types else trace s unknown tag type 0x 02x n function m utype assert 0 return false return true else trace s ignored tag with unknown type 0x 02x n function m utype assert 0 return false ctag writetagtofile cfiledataio eutf8str estrencode assert_valid isstr isint isfloat isblob isint64 writeuint8 m_utype m_pszname m_pszname writeuint16 m_pszname writeuint16 writeuint8 m_uname isstr writestring getstr estrencode isint writeuint32 m_uval isint64 writeuint64 m_uval isfloat m_fval isblob emule writeuint32 m_nblobsize m_pdata m_nblobsize __function__ m_utype __function__ m_utype bool c tag write new ed2k tag c file dataio data e utf8 str e str encode const assert valid this write tag type uint8 u type uint u str val len 0 lpcstr psz vala null c stringa pstr vala null if is int if m uval 0xff u type tagtype uint8 else if m uval 0xffff u type tagtype uint16 else u type tagtype uint32 else if is int64 false if m uval 0xff u type tagtype uint8 else if m uval 0xffff u type tagtype uint16 else if m uval 0xffffffff u type tagtype uint32 else u type tagtype uint64 else if is str if e str encode utf8str raw c unicode toutf8 utf8 m pstrval pstr vala new c stringa lpcstr utf8 utf8 get length else if e str encode utf8str optbom if needutf8 string m pstrval c unicode tobomutf8 bomutf8 m pstrval pstr vala new c stringa lpcstr bomutf8 bomutf8 get length else c unicode to multi byte mb m pstrval pstr vala new c stringa lpcstr mb mb get length else c unicode to multi byte mb m pstrval pstr vala new c stringa lpcstr mb mb get length u str val len pstr vala get length psz vala pstr vala if u str val len 1 u str val len 16 u type uint8 tagtype str1 u str val len 1 else u type tagtype string else u type m utype write tag name if m pszname data writeu int8 u type uint u tag name len strlen m pszname data writeu int16 uint16 u tag name len data write m pszname u tag name len else assert m uname 0 data writeu int8 u type 0x80 data writeu int8 m uname write tag data if u type tagtype string data writeu int16 uint16 u str val len data write psz vala u str val len else if u type tagtype str1 u type tagtype str16 data write psz vala u str val len else if u type tagtype uint64 data writeu int64 m uval else if u type tagtype uint32 data writeu int32 uint32 m uval else if u type tagtype uint16 data writeu int16 uint16 m uval else if u type tagtype uint8 data writeu int8 uint8 m uval else if u type tagtype float32 data write m fval 4 else if u type tagtype hash data write hash16 m pdata else if u type tagtype blob data writeu int32 m nblobsize data write m pdata m nblobsize else trace s unknown tag type 0x 02x n function u type assert 0 return false delete pstr vala return true ctag writenewed2ktag cfiledataio eutf8str estrencode assert_valid utype ustrvallen pszvala cstringa pstrvala isint m_uval utype tagtype_uint8 m_uval utype tagtype_uint16 utype tagtype_uint32 isint64 m_uval utype tagtype_uint8 m_uval utype tagtype_uint16 m_uval utype tagtype_uint32 utype tagtype_uint64 isstr estrencode utf8strraw cunicodetoutf8 m_pstrval pstrvala cstringa getlength estrencode utf8stroptbom needutf8string m_pstrval cunicodetobomutf8 m_pstrval pstrvala cstringa getlength cunicodetomultibyte m_pstrval pstrvala cstringa getlength cunicodetomultibyte m_pstrval pstrvala cstringa getlength ustrvallen pstrvala getlength pszvala pstrvala ustrvallen ustrvallen utype tagtype_str1 ustrvallen utype tagtype_string utype m_utype m_pszname writeuint8 utype utagnamelen m_pszname writeuint16 utagnamelen m_pszname utagnamelen m_uname writeuint8 utype writeuint8 m_uname utype tagtype_string writeuint16 ustrvallen pszvala ustrvallen utype tagtype_str1 utype tagtype_str16 pszvala ustrvallen utype tagtype_uint64 writeuint64 m_uval utype tagtype_uint32 writeuint32 m_uval utype tagtype_uint16 writeuint16 m_uval utype tagtype_uint8 writeuint8 m_uval utype tagtype_float32 m_fval utype tagtype_hash writehash16 m_pdata utype tagtype_blob writeuint32 m_nblobsize m_pdata m_nblobsize __function__ utype pstrvala czip file czip file handle h attach m battach false m hfile invalid handle value m pfile null m nfile 0 if h attach invalid handle value attach h attach czipfile czipfile hattach m_battach m_hfile invalid_handle_value m_pfile m_nfile hattach invalid_handle_value hattach czip file czip file close czipfile czipfile bool czip file open lpctstr psz file assert psz file null close m battach false m hfile create file psz file generic read file share read null open existing file attribute normal null if m hfile invalid handle value return false if locate central directory return true else close return false czipfile pszfile pszfile m_battach m_hfile createfile pszfile generic_read file_share_read open_existing file_attribute_normal m_hfile invalid_handle_value locatecentraldirectory bool czip file attach handle h file assert h file invalid handle value close m battach true m hfile h file if locate central directory return true else close return false czipfile hfile hfile invalid_handle_value m_battach m_hfile hfile locatecentraldirectory bool czip file is open const return m hfile invalid handle value czipfile isopen m_hfile invalid_handle_value void czip file close if m hfile invalid handle value if m battach close handle m hfile m hfile invalid handle value delete m pfile m pfile null m nfile 0 czipfile m_hfile invalid_handle_value m_battach closehandle m_hfile m_hfile invalid_handle_value m_pfile m_pfile m_nfile int czip file get count const return m nfile czipfile getcount m_nfile czip file file czip file get file int n file const return n file 0 n file m nfile null m pfile n file czipfile czipfile getfile nfile nfile nfile m_nfile m_pfile nfile czip file file czip file get file lpctstr psz file bool b partial const file p file m pfile for int n file m nfile n file n file p file if b partial lpctstr psz name tcsrchr p file m sname psz name psz name psz name 1 lpctstr p file m sname if tcsicoll psz name psz file 0 return p file else if tcsicoll p file m sname psz file 0 return p file return null czipfile czipfile getfile pszfile bpartial pfile m_pfile nfile m_nfile nfile nfile pfile bpartial pszname _tcsrchr pfile m_sname pszname pszname pszname pfile m_sname _tcsicoll pszname pszfile pfile _tcsicoll pfile m_sname pszfile pfile bool czip file locate central directory byte p buffer 4096 dword n buffer 0 set file pointer m hfile 4096 null file end if read file m hfile p buffer 4096 n buffer null return false if n buffer sizeof zip directory loc return false zip directory loc p loc null for dword n scan 4 n scan n buffer n scan dword pn signature dword p buffer n buffer n scan if pn signature 0x06054b50 p loc zip directory loc pn signature break if p loc null return false assert p loc n signature 0x06054b50 if get file size m hfile null p loc n directory size return false if set file pointer m hfile p loc n directory offset null file begin p loc n directory offset return false byte p directory new byte p loc n directory size read file m hfile p directory p loc n directory size n buffer null if n buffer p loc n directory size m nfile int p loc n total files m pfile new file m nfile if parse central directory p directory p loc n directory size delete m pfile m pfile null m nfile 0 delete p directory return m nfile 0 czipfile locatecentraldirectory pbuffer nbuffer setfilepointer m_hfile file_end readfile m_hfile pbuffer nbuffer nbuffer zip_directory_loc zip_directory_loc ploc nscan nscan nbuffer nscan pnsignature pbuffer nbuffer nscan pnsignature ploc zip_directory_loc pnsignature ploc ploc nsignature getfilesize m_hfile ploc ndirectorysize setfilepointer m_hfile ploc ndirectoryoffset file_begin ploc ndirectoryoffset pdirectory ploc ndirectorysize readfile m_hfile pdirectory ploc ndirectorysize nbuffer nbuffer ploc ndirectorysize m_nfile ploc ntotalfiles m_pfile m_nfile parsecentraldirectory pdirectory ploc ndirectorysize m_pfile m_pfile m_nfile pdirectory m_nfile bool czip file parse central directory byte p directory dword n directory for int n file 0 n file m nfile n file zip central file p record zip central file p directory if n directory sizeof p record return false if p record n signature 0x02014b50 return false p directory sizeof p record n directory sizeof p record int n tail len int p record n name len int p record n extra len int p record n comment len if n directory dword n tail len return false m pfile n file m pzip this m pfile n file m nsize p record n actual size m pfile n file m nlocaloffset p record n local offset m pfile n file m ncompressedsize p record n compressed size m pfile n file m ncompression p record n compression lptstr psz name m pfile n file m sname get buffer p record n name len for word n char 0 n char p record n name len n char psz name n char tchar p directory n char if psz name n char psz name n char m pfile n file m sname release buffer p record n name len p directory dword n tail len n directory dword n tail len return true czipfile parsecentraldirectory pdirectory ndirectory nfile nfile m_nfile nfile zip_central_file precord zip_central_file pdirectory ndirectory precord precord nsignature pdirectory precord ndirectory precord ntaillen precord nnamelen precord nextralen precord ncommentlen ndirectory ntaillen m_pfile nfile m_pzip m_pfile nfile m_nsize precord nactualsize m_pfile nfile m_nlocaloffset precord nlocaloffset m_pfile nfile m_ncompressedsize precord ncompressedsize m_pfile nfile m_ncompression precord ncompression pszname m_pfile nfile m_sname getbuffer precord nnamelen nchar nchar precord nnamelen nchar pszname nchar pdirectory nchar pszname nchar pszname nchar m_pfile nfile m_sname releasebuffer precord nnamelen pdirectory ntaillen ndirectory ntaillen bool czip file seek to file file p file assert this null assert p file null assert p file m pzip this if m hfile invalid handle value return false if set file pointer m hfile dword p file m nlocaloffset null file begin p file m nlocaloffset return false zip local file p local dword n read 0 read file m hfile p local sizeof p local n read null if n read sizeof p local return false if p local n signature 0x04034b50 return false if p local n compression z deflated p local n compression 0 return false set file pointer m hfile p local n name len p local n extra len null file current return true czipfile seektofile pfile pfile pfile m_pzip m_hfile invalid_handle_value setfilepointer m_hfile pfile m_nlocaloffset file_begin pfile m_nlocaloffset zip_local_file plocal nread readfile m_hfile plocal plocal nread nread plocal plocal nsignature plocal ncompression z_deflated plocal ncompression setfilepointer m_hfile plocal nnamelen plocal nextralen file_current bool czip file file extract lpctstr psz file z stream p stream handle h file h file create file psz file generic write 0 null create new file attribute normal null if h file invalid handle value return false if prepare to decompress p stream return null uint64 n compressed 0 n uncompressed 0 if m ncompression z deflated byte p buffer in new byte buffer in size byte p buffer out new byte buffer out size while n compressed m ncompressedsize n uncompressed m nsize if p stream avail in 0 p stream avail in dword min m ncompressedsize n compressed buffer in size p stream next in p buffer in dword n read 0 read file m pzip m hfile p buffer in p stream avail in n read null if n read p stream avail in break n compressed n read p stream avail out buffer out size p stream next out p buffer out inflate p stream z sync flush if p stream avail out buffer out size dword n write buffer out size p stream avail out write file h file p buffer out n write n write null if n write buffer out size p stream avail out break n uncompressed n write delete p buffer out delete p buffer in inflate end p stream else byte p buffer out new byte buffer out size while n uncompressed m nsize dword n chunk dword min m nsize n uncompressed buffer out size dword n process 0 read file m pzip m hfile p buffer out n chunk n process null if n chunk n process break write file h file p buffer out n chunk n process null if n chunk n process break n compressed n chunk n uncompressed n chunk delete p buffer out close handle h file if n uncompressed m nsize return true delete file psz file return false czipfile pszfile z_stream pstream hfile hfile createfile pszfile generic_write create_new file_attribute_normal hfile invalid_handle_value preparetodecompress pstream ncompressed nuncompressed m_ncompression z_deflated pbufferin buffer_in_size pbufferout buffer_out_size ncompressed m_ncompressedsize nuncompressed m_nsize pstream avail_in pstream avail_in m_ncompressedsize ncompressed buffer_in_size pstream next_in pbufferin nread readfile m_pzip m_hfile pbufferin pstream avail_in nread nread pstream avail_in ncompressed nread pstream avail_out buffer_out_size pstream next_out pbufferout pstream z_sync_flush pstream avail_out buffer_out_size nwrite buffer_out_size pstream avail_out writefile hfile pbufferout nwrite nwrite nwrite buffer_out_size pstream avail_out nuncompressed nwrite pbufferout pbufferin inflateend pstream pbufferout buffer_out_size nuncompressed m_nsize nchunk m_nsize nuncompressed buffer_out_size nprocess readfile m_pzip m_hfile pbufferout nchunk nprocess nchunk nprocess writefile hfile pbufferout nchunk nprocess nchunk nprocess ncompressed nchunk nuncompressed nchunk pbufferout closehandle hfile nuncompressed m_nsize deletefile pszfile bool czip file file prepare to decompress lpvoid p stream zero memory p stream sizeof z stream if m pzip seek to file this return false if m ncompression 0 return m nsize m ncompressedsize else assert m ncompression z deflated return z ok inflate init2 z stream p stream max wbits czipfile preparetodecompress pstream zeromemory pstream z_stream m_pzip seektofile m_ncompression m_nsize m_ncompressedsize m_ncompression z_deflated z_ok inflateinit2 z_stream pstream max_wbits cp pg general cp pg general c property page cp pg general idd cppggeneral cppggeneral cpropertypage cppggeneral cp pg general cp pg general cppggeneral cppggeneral void cp pg general localize void if m hwnd set window text get res string ids pw general get dlg item idc nick frm set window text get res string ids ql username get dlg item idc lang frm set window text get res string ids pw lang get dlg item idc misc frm set window text get res string ids pw misc get dlg item idc beeper set window text get res string ids pw beep get dlg item idc exit set window text get res string ids pw prompt get dlg item idc splashon set window text get res string ids pw splash get dlg item idc bringtoforeground set window text get res string ids pw front get dlg item idc onlinesig set window text get res string ids pref onlinesig get dlg item idc startmin set window text get res string ids pref startmin get dlg item idc websvedit set window text get res string ids websvedit get dlg item idc ed2kfix set window text get res string ids ed2klinkfix get dlg item idc check4update set window text get res string ids check4update get dlg item idc startup set window text get res string ids startup get dlg item idc startwin set window text get res string ids startwithwindows cppggeneral m_hwnd setwindowtext getresstring ids_pw_general getdlgitem idc_nick_frm setwindowtext getresstring ids_ql_username getdlgitem idc_lang_frm setwindowtext getresstring ids_pw_lang getdlgitem idc_misc_frm setwindowtext getresstring ids_pw_misc getdlgitem idc_beeper setwindowtext getresstring ids_pw_beep getdlgitem idc_exit setwindowtext getresstring ids_pw_prompt getdlgitem idc_splashon setwindowtext getresstring ids_pw_splash getdlgitem idc_bringtoforeground setwindowtext getresstring ids_pw_front getdlgitem idc_onlinesig setwindowtext getresstring ids_pref_onlinesig getdlgitem idc_startmin setwindowtext getresstring ids_pref_startmin getdlgitem idc_websvedit setwindowtext getresstring ids_websvedit getdlgitem idc_ed2kfix setwindowtext getresstring ids_ed2klinkfix getdlgitem idc_check4update setwindowtext getresstring ids_check4update getdlgitem idc_startup setwindowtext getresstring ids_startup getdlgitem idc_startwin setwindowtext getresstring ids_startwithwindows void cp pg general load settings void get dlg item idc nick set window text the prefs get user nick for int i 0 i m language get count i if m language get item data i the prefs get languageid m language set cur sel i if the prefs m bautostart check dlg button idc startwin 1 else check dlg button idc startwin 0 if the prefs start minimized check dlg button idc startmin 1 else check dlg button idc startmin 0 if the prefs online sig check dlg button idc onlinesig 1 else check dlg button idc onlinesig 0 if the prefs beep on error check dlg button idc beeper 1 else check dlg button idc beeper 0 if the prefs confirm exit check dlg button idc exit 1 else check dlg button idc exit 0 if the prefs splashscreen check dlg button idc splashon 1 else check dlg button idc splashon 0 if the prefs bringtoforeground check dlg button idc bringtoforeground 1 else check dlg button idc bringtoforeground 0 if the prefs updatenotify check dlg button idc check4update 1 else check dlg button idc check4update 0 c string str buffer str buffer format t i s the prefs versioncheckdays get res string ids days2 get dlg item idc days set window text str buffer cppggeneral loadsettings getdlgitem idc_nick setwindowtext theprefs getusernick m_language getcount m_language getitemdata theprefs getlanguageid m_language setcursel theprefs m_bautostart checkdlgbutton idc_startwin checkdlgbutton idc_startwin theprefs startminimized checkdlgbutton idc_startmin checkdlgbutton idc_startmin theprefs onlinesig checkdlgbutton idc_onlinesig checkdlgbutton idc_onlinesig theprefs beeponerror checkdlgbutton idc_beeper checkdlgbutton idc_beeper theprefs confirmexit checkdlgbutton idc_exit checkdlgbutton idc_exit theprefs checkdlgbutton idc_splashon checkdlgbutton idc_splashon theprefs checkdlgbutton idc_bringtoforeground checkdlgbutton idc_bringtoforeground theprefs checkdlgbutton idc_check4update checkdlgbutton idc_check4update cstring strbuffer strbuffer _t theprefs getresstring ids_days2 getdlgitem idc_days setwindowtext strbuffer void cp pg general update ed2k link fix ctrl get dlg item idc ed2kfix enable window have ed2k reg access ask4 reg fix true cppggeneral updateed2klinkfixctrl getdlgitem idc_ed2kfix enablewindow haveed2kregaccess ask4regfix void cp pg general do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc langs m language cppggeneral dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_langs m_language bool cp pg general on init dialog c property page on init dialog init window styles this c edit get dlg item idc nick set limit text the prefs get max user nick length c word array a languagei ds the prefs get languages a languagei ds for int i 0 i a languagei ds get size i tchar sz lang 128 int ret get locale info a languagei ds i locale slanguage sz lang arrsize sz lang if ret 0 a languagei ds i langid gl es tcscpy sz lang t galician else if ret 0 a languagei ds i langid fr br tcscpy sz lang t breton brezhoneg else if ret 0 a languagei ds i langid mt mt tcscpy sz lang t maltese else if ret 0 a languagei ds i langid es as tcscpy sz lang t asturian m language set item data m language add string sz lang a languagei ds i update ed2k link fix ctrl get dlg item idc onlinesig show window the prefs is ext controls enabled sw show sw hide c slider ctrl slider update c slider ctrl get dlg item idc checkdays slider update set range 2 7 true slider update set pos the prefs get update days load settings localize get dlg item idc checkdays show window is dlg button checked idc check4update sw show sw hide get dlg item idc days show window is dlg button checked idc check4update sw show sw hide return true return true unless you set the focus to a control exception ocx property pages should return false cppggeneral oninitdialog cpropertypage oninitdialog initwindowstyles cedit getdlgitem idc_nick setlimittext theprefs getmaxusernicklength cwordarray alanguageids theprefs getlanguages alanguageids alanguageids getsize szlang getlocaleinfo alanguageids locale_slanguage szlang szlang alanguageids langid_gl_es _tcscpy szlang _t alanguageids langid_fr_br _tcscpy szlang _t alanguageids langid_mt_mt _tcscpy szlang _t alanguageids langid_es_as _tcscpy szlang _t m_language setitemdata m_language addstring szlang alanguageids updateed2klinkfixctrl getdlgitem idc_onlinesig showwindow theprefs isextcontrolsenabled sw_show sw_hide csliderctrl sliderupdate csliderctrl getdlgitem idc_checkdays sliderupdate setrange sliderupdate setpos theprefs getupdatedays loadsettings getdlgitem idc_checkdays showwindow isdlgbuttonchecked idc_check4update sw_show sw_hide getdlgitem idc_days showwindow isdlgbuttonchecked idc_check4update sw_show sw_hide bool cp pg general on apply c string str nick get dlg item idc nick get window text str nick str nick trim if is valid ed2k string str nick str nick empty if str nick is empty str nick default nick get dlg item idc nick set window text str nick the prefs set user nick str nick if m language get cur sel cb err word w new lang word m language get item data m language get cur sel if the prefs get languageid w new lang the prefs set languageid w new lang the prefs set language ifdef debug can t yet be switched on the fly too much unresolved issues if the prefs getrtl windows layout modify all window styles the app emuledlg ws ex layoutrtl ws ex rtlreading ws ex right ws ex leftscrollbar 0 modify all window styles the app emuledlg preferenceswnd ws ex layoutrtl ws ex rtlreading ws ex right ws ex leftscrollbar 0 the app disablertl windows layout the prefs m brtlwindowslayout false endif the app emuledlg preferenceswnd localize the app emuledlg statisticswnd create my tree the app emuledlg statisticswnd localize the app emuledlg statisticswnd show statistics true the app emuledlg serverwnd localize the app emuledlg transferwnd localize the app emuledlg transferwnd update cat tab titles the app emuledlg searchwnd localize the app emuledlg sharedfileswnd localize the app emuledlg chatwnd localize the app emuledlg localize the app emuledlg ircwnd localize the app emuledlg kademliawnd localize the prefs start minimized is dlg button checked idc startmin 0 the prefs m bautostart is dlg button checked idc startwin 0 if the prefs m bautostart add auto start else rem auto start the prefs beep on error is dlg button checked idc beeper 0 the prefs confirm exit is dlg button checked idc exit 0 the prefs splashscreen is dlg button checked idc splashon 0 the prefs bringtoforeground is dlg button checked idc bringtoforeground 0 the prefs updatenotify is dlg button checked idc check4update 0 the prefs online sig is dlg button checked idc onlinesig 0 the prefs versioncheckdays c slider ctrl get dlg item idc checkdays get pos the app emuledlg transferwnd downloadlistctrl set style load settings set modified false return c property page on apply cppggeneral onapply cstring strnick getdlgitem idc_nick getwindowtext strnick strnick isvalided2kstring strnick strnick strnick isempty strnick default_nick getdlgitem idc_nick setwindowtext strnick theprefs setusernick strnick m_language getcursel cb_err wnewlang m_language getitemdata m_language getcursel theprefs getlanguageid wnewlang theprefs setlanguageid wnewlang theprefs setlanguage _debug theprefs getrtlwindowslayout modifyallwindowstyles theapp ws_ex_layoutrtl ws_ex_rtlreading ws_ex_right ws_ex_leftscrollbar modifyallwindowstyles theapp ws_ex_layoutrtl ws_ex_rtlreading ws_ex_right ws_ex_leftscrollbar theapp disablertlwindowslayout theprefs m_brtlwindowslayout theapp theapp createmytree theapp theapp showstatistics theapp theapp theapp updatecattabtitles theapp theapp theapp theapp theapp theapp theprefs startminimized isdlgbuttonchecked idc_startmin theprefs m_bautostart isdlgbuttonchecked idc_startwin theprefs m_bautostart addautostart remautostart theprefs beeponerror isdlgbuttonchecked idc_beeper theprefs confirmexit isdlgbuttonchecked idc_exit theprefs isdlgbuttonchecked idc_splashon theprefs isdlgbuttonchecked idc_bringtoforeground theprefs isdlgbuttonchecked idc_check4update theprefs onlinesig isdlgbuttonchecked idc_onlinesig theprefs csliderctrl getdlgitem idc_checkdays getpos theapp setstyle loadsettings setmodified cpropertypage onapply bool cp pg general on set active update ed2k link fix ctrl return super on set active cppggeneral onsetactive updateed2klinkfixctrl __super onsetactive bool cp pg general on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppggeneral oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg general onh scroll uint nsb code uint n pos c scroll bar p scroll bar set modified true if p scroll bar get dlg item idc checkdays c slider ctrl slider c slider ctrl p scroll bar c string text text format t i s slider get pos get res string ids days2 get dlg item idc days set window text text update data false c property page onh scroll nsb code n pos p scroll bar cppggeneral onhscroll nsbcode npos cscrollbar pscrollbar setmodified pscrollbar getdlgitem idc_checkdays csliderctrl csliderctrl pscrollbar cstring _t getpos getresstring ids_days2 getdlgitem idc_days setwindowtext updatedata cpropertypage onhscroll nsbcode npos pscrollbar void cp pg general on bn clicked ed2kfix ask4 reg fix false false true get dlg item idc ed2kfix enable window ask4 reg fix true cppggeneral onbnclickeded2kfix ask4regfix getdlgitem idc_ed2kfix enablewindow ask4regfix void cp pg general on bn clicked edit webservices the web services edit cppggeneral onbnclickededitwebservices thewebservices void cp pg general on lang change define mirrors url t http langmirror i emule project org lang i i i i word by new lang word m language get item data m language get cur sel if the prefs get languageid by new lang if the prefs is language supported by new lang false if afx message box get res string ids askdownloadlangcap t r n r n get res string ids askdownloadlang mb iconquestion mb yesno idyes download file create url use random mirror for load balancing uint n rand rand rand max 3 1 c string str url str url format mirrors url n rand cemule app m nversionmjr cemule app m nversionmin cemule app m nversionupd cemule app m nversionbld str url the prefs get langdll name byid by new lang safeto c string str filename the prefs get lang dir if path file exists str filename create directory str filename 0 str filename append the prefs get langdll name byid by new lang start c http download dlg dlg download dlg download m strtitle get res string ids download langfile dlg download m surltodownload str url dlg download m sfiletodownloadinto str filename if dlg download do modal idok the prefs is language supported by new lang true everything ok new language downloaded and working on settings change return c string str err str err format get res string ids err faileddownloadlang str url log error log statusbar t s str err afx message box str err mb iconerror mb ok undo change selection for int i 0 i m language get count i if m language get item data i the prefs get languageid m language set cur sel i else on settings change cppggeneral onlangchange mirrors_url _t bynewlang m_language getitemdata m_language getcursel theprefs getlanguageid bynewlang theprefs islanguagesupported bynewlang afxmessagebox getresstring ids_askdownloadlangcap _t getresstring ids_askdownloadlang mb_iconquestion mb_yesno nrand rand_max cstring strurl strurl mirrors_url nrand cemuleapp m_nversionmjr cemuleapp m_nversionmin cemuleapp m_nversionupd cemuleapp m_nversionbld strurl theprefs getlangdllnamebyid bynewlang cstring strfilename theprefs getlangdir pathfileexists strfilename createdirectory strfilename strfilename theprefs getlangdllnamebyid bynewlang chttpdownloaddlg dlgdownload dlgdownload m_strtitle getresstring ids_download_langfile dlgdownload m_surltodownload strurl dlgdownload m_sfiletodownloadinto strfilename dlgdownload domodal theprefs islanguagesupported bynewlang onsettingschange cstring strerr strerr getresstring ids_err_faileddownloadlang strurl logerror log_statusbar _t strerr afxmessagebox strerr mb_iconerror mb_ok m_language getcount m_language getitemdata theprefs getlanguageid m_language setcursel onsettingschange void cp pg general on bn clicked check4 update set modified get dlg item idc checkdays show window is dlg button checked idc check4update sw show sw hide get dlg item idc days show window is dlg button checked idc check4update sw show sw hide cppggeneral onbnclickedcheck4update setmodified getdlgitem idc_checkdays showwindow isdlgbuttonchecked idc_check4update sw_show sw_hide getdlgitem idc_days showwindow isdlgbuttonchecked idc_check4update sw_show sw_hide void cp pg general on help the app show help emule faq preferences general cppggeneral onhelp theapp showhelp emule_faq_preferences_general bool cp pg general on help info helpinfo p help info on help return true cppggeneral onhelpinfo phelpinfo onhelp cp pg server cp pg server c property page cp pg server idd cppgserver cppgserver cpropertypage cppgserver cp pg server cp pg server cppgserver cppgserver void cp pg server localize void if m hwnd set window text get res string ids pw server get dlg item idc removedead set window text get res string ids pw rdead get dlg item idc retries lbl set window text get res string ids pw retries get dlg item idc updateserverconnect set window text get res string ids pw usc get dlg item idc updateserverclient set window text get res string ids pw ucc get dlg item idc autoserver set window text get res string ids pw uss get dlg item idc smartidcheck set window text get res string ids smartlowidcheck get dlg item idc safeserverconnect set window text get res string ids pw fastsrvcon get dlg item idc score set window text get res string ids pw score get dlg item idc manualserverhighprio set window text get res string ids manualserverhighprio get dlg item idc editadr set window text get res string ids editlist get dlg item idc autoconnectstaticonly set window text get res string ids pw autoconnectstaticonly cppgserver m_hwnd setwindowtext getresstring ids_pw_server getdlgitem idc_removedead setwindowtext getresstring ids_pw_rdead getdlgitem idc_retries_lbl setwindowtext getresstring ids_pw_retries getdlgitem idc_updateserverconnect setwindowtext getresstring ids_pw_usc getdlgitem idc_updateserverclient setwindowtext getresstring ids_pw_ucc getdlgitem idc_autoserver setwindowtext getresstring ids_pw_uss getdlgitem idc_smartidcheck setwindowtext getresstring ids_smartlowidcheck getdlgitem idc_safeserverconnect setwindowtext getresstring ids_pw_fastsrvcon getdlgitem idc_score setwindowtext getresstring ids_pw_score getdlgitem idc_manualserverhighprio setwindowtext getresstring ids_manualserverhighprio getdlgitem idc_editadr setwindowtext getresstring ids_editlist getdlgitem idc_autoconnectstaticonly setwindowtext getresstring ids_pw_autoconnectstaticonly void cp pg server load settings void set dlg item int idc serverretries the prefs m udeadserverretries false check dlg button idc autoserver the prefs m bautoupdateserverlist check dlg button idc updateserverconnect the prefs m baddserversfromserver check dlg button idc updateserverclient the prefs m baddserversfromclients check dlg button idc score the prefs m buseserverpriorities check dlg button idc smartidcheck the prefs m bsmartserveridcheck check dlg button idc safeserverconnect the prefs m bsafeserverconnect check dlg button idc autoconnectstaticonly the prefs m bautoconnecttostaticserversonly check dlg button idc manualserverhighprio the prefs m bmanualaddedservershighpriority cppgserver loadsettings setdlgitemint idc_serverretries theprefs m_udeadserverretries checkdlgbutton idc_autoserver theprefs m_bautoupdateserverlist checkdlgbutton idc_updateserverconnect theprefs m_baddserversfromserver checkdlgbutton idc_updateserverclient theprefs m_baddserversfromclients checkdlgbutton idc_score theprefs m_buseserverpriorities checkdlgbutton idc_smartidcheck theprefs m_bsmartserveridcheck checkdlgbutton idc_safeserverconnect theprefs m_bsafeserverconnect checkdlgbutton idc_autoconnectstaticonly theprefs m_bautoconnecttostaticserversonly checkdlgbutton idc_manualserverhighprio theprefs m_bmanualaddedservershighpriority void cp pg server do data exchange c data exchange pdx c property page do data exchange pdx cppgserver dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg server on init dialog c property page on init dialog init window styles this load settings localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgserver oninitdialog cpropertypage oninitdialog initwindowstyles loadsettings bool cp pg server on apply uint u cur dead server retries the prefs m udeadserverretries the prefs m udeadserverretries get dlg item int idc serverretries null false if the prefs m udeadserverretries 1 the prefs m udeadserverretries 1 else if the prefs m udeadserverretries max serverfailcount the prefs m udeadserverretries max serverfailcount if u cur dead server retries the prefs m udeadserverretries the app emuledlg serverwnd serverlistctrl invalidate the app emuledlg serverwnd serverlistctrl update window the prefs m bautoupdateserverlist is dlg button checked idc autoserver 0 the prefs m baddserversfromserver is dlg button checked idc updateserverconnect 0 the prefs m baddserversfromclients is dlg button checked idc updateserverclient 0 the prefs m buseserverpriorities is dlg button checked idc score 0 the prefs m bsmartserveridcheck is dlg button checked idc smartidcheck 0 the prefs set safe server connect enabled is dlg button checked idc safeserverconnect 0 the prefs m bautoconnecttostaticserversonly is dlg button checked idc autoconnectstaticonly 0 the prefs m bmanualaddedservershighpriority is dlg button checked idc manualserverhighprio 0 load settings set modified return c property page on apply cppgserver onapply ucurdeadserverretries theprefs m_udeadserverretries theprefs m_udeadserverretries getdlgitemint idc_serverretries theprefs m_udeadserverretries theprefs m_udeadserverretries theprefs m_udeadserverretries max_serverfailcount theprefs m_udeadserverretries max_serverfailcount ucurdeadserverretries theprefs m_udeadserverretries theapp theapp updatewindow theprefs m_bautoupdateserverlist isdlgbuttonchecked idc_autoserver theprefs m_baddserversfromserver isdlgbuttonchecked idc_updateserverconnect theprefs m_baddserversfromclients isdlgbuttonchecked idc_updateserverclient theprefs m_buseserverpriorities isdlgbuttonchecked idc_score theprefs m_bsmartserveridcheck isdlgbuttonchecked idc_smartidcheck theprefs setsafeserverconnectenabled isdlgbuttonchecked idc_safeserverconnect theprefs m_bautoconnecttostaticserversonly isdlgbuttonchecked idc_autoconnectstaticonly theprefs m_bmanualaddedservershighpriority isdlgbuttonchecked idc_manualserverhighprio loadsettings setmodified cpropertypage onapply bool cp pg server on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgserver oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg server on bn clicked editadr shell execute null t open the prefs get txt editor t the prefs get config dir t addresses dat null sw show cppgserver onbnclickededitadr shellexecute _t theprefs gettxteditor _t theprefs getconfigdir _t sw_show void cp pg server on help the app show help emule faq preferences server cppgserver onhelp theapp showhelp emule_faq_preferences_server bool cp pg server on help info helpinfo p help info on help return true cppgserver onhelpinfo phelpinfo onhelp void c directory tree ctrl init void send message ccm setunicodeformat true show window sw hide delete all items modify style 0 tvs checkboxes start added by fo rc ha word w win ver the prefs get windows version maybe causes problems on 98 nt4 if w win ver winver 2k w win ver winver xp w win ver winver me shfileinfo sh finfo himagelist h img list null get the system image list using a path which is available on all systems patch by bluecow h img list himagelist sh get file info t 0 sh finfo sizeof sh finfo shgfi sysiconindex shgfi smallicon if h img list trace t cannot retrieve the handle of system image list return m image m himagelist h img list set image list m image tvsil normal tchar drivebuffer 500 get logical drive strings arrsize drivebuffer drivebuffer e g a c d const tchar pos drivebuffer while pos t 0 copy drive name tchar drive 4 tcsncpy drive pos arrsize drive drive arrsize drive 1 t 0 switch drive 0 case t a case t a case t b case t b skip floppy disk break default drive 2 t 0 add child item null drive e g c point to the next drive 4 chars interval pos pos 4 show window sw show cdirectorytreectrl sendmessage ccm_setunicodeformat showwindow sw_hide deleteallitems modifystyle tvs_checkboxes forcha wwinver theprefs getwindowsversion wwinver _winver_2k_ wwinver _winver_xp_ wwinver _winver_me_ shfinfo himglist himglist shgetfileinfo _t shfinfo shfinfo shgfi_sysiconindex shgfi_smallicon himglist _t systemimagelist m_image m_himagelist himglist setimagelist m_image tvsil_normal getlogicaldrivestrings _t _tcsncpy _t _t _t _t _t _t addchilditem showwindow sw_show void c directory tree ctrl get shared directories c string list list for position pos m lstshared get head position pos null list add tail m lstshared get next pos cdirectorytreectrl getshareddirectories cstringlist m_lstshared getheadposition addtail m_lstshared getnext void c directory tree ctrl set shared directories c string list list m lstshared remove all for position pos list get head position pos null c string str list get next pos if str left 2 t continue if str right 1 t str t m lstshared add tail str init cdirectorytreectrl setshareddirectories cstringlist m_lstshared removeall getheadposition cstring getnext _t _t _t m_lstshared addtail htreeitem c directory tree ctrl add child item htreeitem h root c string str text c string str path get full path h root if h root null str path right 1 t str path t c string str dir str path str text tv insertstruct it insert 0 start changed by fo rc ha word w win ver the prefs get windows version if w win ver winver 2k w win ver winver xp w win ver winver me it insert item mask tvif children tvif handle tvif text tvif state tvif image tvif selectedimage it insert item state mask tvis bold tvis stateimagemask else it insert item mask tvif children tvif handle tvif text tvif state it insert item state mask tvis bold end changed by fo rc ha if has shared subdirectory str dir it insert item state tvis bold else it insert item state 0 if has subdirectories str dir it insert item c children i childrencallback used to display the symbol next to each item else it insert item c children 0 it insert item psz text const cast lptstr lpctstr str text it insert h insert after h root tvi sort tvi last it insert h parent h root start added by fo rc ha if w win ver winver 2k w win ver winver xp w win ver winver me c string str temp str dir if str temp right 1 t str temp t uint n type get drive type str temp if drive removable n type n type drive ramdisk it insert item i image n type shfileinfo sh finfo sh finfo sz display name 0 t 0 if sh get file info str temp 0 sh finfo sizeof sh finfo shgfi icon shgfi smallicon shgfi displayname trace t error gettting system file info it insert itemex i image 0 else it insert itemex i image sh finfo i icon destroy icon sh finfo h icon if h root null sh finfo sz display name 0 t 0 s tree item pti new s tree item pti str path str text str text sh finfo sz display name it insert item psz text const cast lptstr lpctstr str text it insert item mask tvif param it insert item l param lparam pti if sh get file info str temp 0 sh finfo sizeof sh finfo shgfi icon shgfi openicon shgfi smallicon trace t error gettting system file info it insert itemex i image 0 else it insert itemex i selected image sh finfo i icon destroy icon sh finfo h icon end added by fo rc ha htreeitem h item insert item it insert if is shared str dir set check h item str text release buffer return h item cdirectorytreectrl addchilditem hroot cstring strtext cstring strpath getfullpath hroot hroot strpath _t strpath _t cstring strdir strpath strtext tv_insertstruct itinsert forcha wwinver theprefs getwindowsversion wwinver _winver_2k_ wwinver _winver_xp_ wwinver _winver_me_ itinsert tvif_children tvif_handle tvif_text tvif_state tvif_image tvif_selectedimage itinsert statemask tvis_bold tvis_stateimagemask itinsert tvif_children tvif_handle tvif_text tvif_state itinsert statemask tvis_bold forcha hassharedsubdirectory strdir itinsert tvis_bold itinsert hassubdirectories strdir itinsert cchildren i_childrencallback itinsert cchildren itinsert psztext const_cast strtext itinsert hinsertafter hroot tvi_sort tvi_last itinsert hparent hroot forcha wwinver _winver_2k_ wwinver _winver_xp_ wwinver _winver_me_ cstring strtemp strdir strtemp _t strtemp _t ntype getdrivetype strtemp drive_removable ntype ntype drive_ramdisk itinsert iimage ntype shfinfo shfinfo szdisplayname _t shgetfileinfo strtemp shfinfo shfinfo shgfi_icon shgfi_smallicon shgfi_displayname _t systemfileinfo itinsert iimage itinsert iimage shfinfo iicon destroyicon shfinfo hicon hroot shfinfo szdisplayname _t streeitem streeitem strpath strtext strtext shfinfo szdisplayname itinsert psztext const_cast strtext itinsert tvif_param itinsert lparam shgetfileinfo strtemp shfinfo shfinfo shgfi_icon shgfi_openicon shgfi_smallicon _t systemfileinfo itinsert iimage itinsert iselectedimage shfinfo iicon destroyicon shfinfo hicon forcha hitem insertitem itinsert isshared strdir setcheck hitem strtext releasebuffer hitem void c directory tree ctrl add subdirectories htreeitem h root c string str dir if str dir right 1 t str dir t c file find finder bool b working finder find file str dir t while b working b working finder find next file if finder is dots continue if finder is system continue if finder is directory continue c string str filename finder get file name if str filename reverse find t 1 str filename str filename mid str filename reverse find t 1 add child item h root str filename finder close cdirectorytreectrl addsubdirectories hroot cstring strdir strdir _t strdir _t cfilefind bworking findfile strdir _t bworking bworking findnextfile isdots issystem isdirectory cstring strfilename getfilename strfilename reversefind _t strfilename strfilename strfilename reversefind _t addchilditem hroot strfilename c string c directory tree ctrl get full path htreeitem h item c string str dir htreeitem h search item h item while h search item null c string str search item dir s tree item pti s tree item get item data h search item if pti str search item dir pti str path else str search item dir get item text h search item str dir str search item dir t str dir h search item get parent item h search item return str dir cstring cdirectorytreectrl getfullpath hitem cstring strdir hsearchitem hitem hsearchitem cstring strsearchitemdir streeitem streeitem getitemdata hsearchitem strsearchitemdir strpath strsearchitemdir getitemtext hsearchitem strdir strsearchitemdir _t strdir hsearchitem getparentitem hsearchitem strdir bool c directory tree ctrl has subdirectories c string str dir if str dir right 1 t str dir t c file find finder bool b working finder find file str dir t while b working b working finder find next file if finder is dots continue if finder is system continue if finder is directory continue finder close return true finder close return false cdirectorytreectrl hassubdirectories cstring strdir strdir _t strdir _t cfilefind bworking findfile strdir _t bworking bworking findnextfile isdots issystem isdirectory void c directory tree ctrl check changed htreeitem h item bool b checked c string str dir get full path h item if b checked add share str dir else del share str dir update parent items h item get parent send message wm command um itemstatechanged long m hwnd cdirectorytreectrl checkchanged hitem bchecked cstring strdir getfullpath hitem bchecked addshare strdir delshare strdir updateparentitems hitem getparent sendmessage wm_command um_itemstatechanged m_hwnd bool c directory tree ctrl has shared subdirectory c string str dir if str dir right 1 t str dir t str dir make lower for position pos m lstshared get head position pos null c string str m lstshared get next pos str make lower if str find str dir 0 str dir str str dir get length str get length return true return false cdirectorytreectrl hassharedsubdirectory cstring strdir strdir _t strdir _t strdir makelower m_lstshared getheadposition cstring m_lstshared getnext makelower strdir strdir strdir getlength getlength void c directory tree ctrl update parent items htreeitem h child htreeitem h search get parent item h child while h search null if has shared subdirectory get full path h search set item state h search tvis bold tvis bold else set item state h search 0 tvis bold h search get parent item h search cdirectorytreectrl updateparentitems hchild hsearch getparentitem hchild hsearch hassharedsubdirectory getfullpath hsearch setitemstate hsearch tvis_bold tvis_bold setitemstate hsearch tvis_bold hsearch getparentitem hsearch void c directory tree ctrl share sub dir tree htreeitem h item bool b recurse c wait cursor cur wait set redraw false htreeitem h item visible item get first visible item check changed h item get check h item if b recurse expand h item tve toggle htreeitem h child get child item h item while h child null mark childs h child get check h item h child get next sibling item h child expand h item tve toggle if h item visible item select set first visible h item visible item set redraw true invalidate cdirectorytreectrl sharesubdirtree hitem brecurse cwaitcursor curwait setredraw hitemvisibleitem getfirstvisibleitem checkchanged hitem getcheck hitem brecurse hitem tve_toggle hchild getchilditem hitem hchild markchilds hchild getcheck hitem hchild getnextsiblingitem hchild hitem tve_toggle hitemvisibleitem selectsetfirstvisible hitemvisibleitem setredraw bool c directory tree ctrl is shared c string str dir if str dir right 1 t str dir t for position pos m lstshared get head position pos null c string str m lstshared get next pos if str right 1 t str t if str compare no case str dir 0 return true return false cdirectorytreectrl isshared cstring strdir strdir _t strdir _t m_lstshared getheadposition cstring m_lstshared getnext _t _t comparenocase strdir void c directory tree ctrl add share c string str dir if str dir right 1 t str dir t if is shared str dir str dir compare no case the prefs get config dir return m lstshared add tail str dir cdirectorytreectrl addshare cstring strdir strdir _t strdir _t isshared strdir strdir comparenocase theprefs getconfigdir m_lstshared addtail strdir void c directory tree ctrl del share c string str dir if str dir right 1 t str dir t for position pos m lstshared get head position pos null position pos2 pos c string str m lstshared get next pos if str compare no case str dir 0 m lstshared remove at pos2 cdirectorytreectrl delshare cstring strdir strdir _t strdir _t m_lstshared getheadposition cstring m_lstshared getnext comparenocase strdir m_lstshared removeat void c directory tree ctrl mark childs htreeitem h child bool mark check changed h child mark set check h child mark expand h child tve toggle vqb make sure tree has entries htreeitem h child2 h child2 get child item h child while h child2 null mark childs h child2 mark h child2 get next sibling item h child2 expand h child tve toggle vqb restore tree to initial disposition cdirectorytreectrl markchilds hchild checkchanged hchild setcheck hchild hchild tve_toggle hchild2 hchild2 getchilditem hchild hchild2 markchilds hchild2 hchild2 getnextsiblingitem hchild2 hchild tve_toggle c directory tree ctrl c directory tree ctrl m bselectsubdirs false cdirectorytreectrl cdirectorytreectrl m_bselectsubdirs c directory tree ctrl c directory tree ctrl don t destroy the system s image list m image detach cdirectorytreectrl cdirectorytreectrl m_image bool c directory tree ctrl on command wparam w param lparam l param if w param mp sharedfolders first shell execute null t open m strlastrightclicked null null sw show else position pos m lstshared find index w param mp sharedfolders first if pos shell execute null t open m lstshared get at pos null null sw show return true cdirectorytreectrl oncommand wparam lparam wparam mp_sharedfolders_first shellexecute _t m_strlastrightclicked sw_show m_lstshared findindex wparam mp_sharedfolders_first shellexecute _t m_lstshared getat sw_show void c directory tree ctrl on tvn itemexpanding nmhdr pnmhdr lresult p result c wait cursor cur wait set redraw false lpnmtreeview pnm tree view reinterpret cast lpnmtreeview pnmhdr htreeitem h item pnm tree view item new h item remove all subitems htreeitem h remove get child item h item while h remove delete item h remove h remove get child item h item get the directory c string str dir get full path h item fetch all subdirectories and add them to the node add subdirectories h item str dir set redraw true invalidate p result 0 cdirectorytreectrl ontvnitemexpanding presult cwaitcursor curwait setredraw pnmtreeview reinterpret_cast hitem pnmtreeview itemnew hitem hremove getchilditem hitem hremove deleteitem hremove hremove getchilditem hitem cstring strdir getfullpath hitem addsubdirectories hitem strdir setredraw presult void c directory tree ctrl on tvn getdispinfo nmhdr pnmhdr lresult p result lpnmtvdispinfo ptv disp info reinterpret cast lpnmtvdispinfo pnmhdr ptv disp info item c children 1 p result 0 cdirectorytreectrl ontvngetdispinfo presult ptvdispinfo reinterpret_cast ptvdispinfo cchildren presult void c directory tree ctrl onl button down uint n flags c point point vqb adjustments to provide for sharing or unsharing of subdirectories when control key is down uint u hit flags htreeitem h item hit test point u hit flags if h item u hit flags tvht onitemstateicon share sub dir tree h item n flags mk control c tree ctrl onl button down n flags point cdirectorytreectrl onlbuttondown nflags cpoint uhitflags hitem hittest uhitflags hitem uhitflags tvht_onitemstateicon sharesubdirtree hitem nflags mk_control ctreectrl onlbuttondown nflags void c directory tree ctrl on tvn delete item nmhdr pnmhdr lresult p result lpnmtreeview pnm tree view reinterpret cast lpnmtreeview pnmhdr if pnm tree view item old l param delete s tree item pnm tree view item old l param p result 0 cdirectorytreectrl ontvndeleteitem presult pnmtreeview reinterpret_cast pnmtreeview itemold lparam streeitem pnmtreeview itemold lparam presult void c directory tree ctrl on context menu c wnd p wnd c point point c point pt menu 1 1 if point x 1 point y 1 pt menu point screen to client point else htreeitem h sel get next item tvi root tvgn caret if h sel c rect rc item if get item rect h sel rc item true pt menu x rc item left pt menu y rc item top client to screen pt menu else client to screen pt menu 0 0 htreeitem h item hit test point create the menu c title menu shared menu shared menu create popup menu shared menu add menu title get res string ids sharedfolders bool b menu is empty true add all shared directories int i cnt 0 for position pos m lstshared get head position pos null i cnt c string str display path m lstshared get next pos path remove backslash str display path get buffer str display path get length str display path release buffer shared menu append menu mf string mp sharedfolders first i cnt get res string ids view1 str display path b menu is empty false add right clicked folder if any if h item m strlastrightclicked get full path h item if is shared m strlastrightclicked c string str display path m strlastrightclicked path remove backslash str display path get buffer str display path get length str display path release buffer if b menu is empty shared menu append menu mf separator shared menu append menu mf string mp sharedfolders first 1 get res string ids view1 str display path get res string ids view2 b menu is empty false display menu if b menu is empty shared menu track popup menu tpm leftalign tpm rightbutton pt menu x pt menu y this verify shared menu destroy menu cdirectorytreectrl oncontextmenu cwnd pwnd cpoint cpoint ptmenu ptmenu screentoclient hsel getnextitem tvi_root tvgn_caret hsel crect rcitem getitemrect hsel rcitem ptmenu rcitem ptmenu rcitem clienttoscreen ptmenu clienttoscreen ptmenu hitem hittest ctitlemenu sharedmenu sharedmenu createpopupmenu sharedmenu addmenutitle getresstring ids_sharedfolders bmenuisempty icnt m_lstshared getheadposition icnt cstring strdisplaypath m_lstshared getnext pathremovebackslash strdisplaypath getbuffer strdisplaypath getlength strdisplaypath releasebuffer sharedmenu appendmenu mf_string mp_sharedfolders_first icnt getresstring ids_view1 strdisplaypath bmenuisempty hitem m_strlastrightclicked getfullpath hitem isshared m_strlastrightclicked cstring strdisplaypath m_strlastrightclicked pathremovebackslash strdisplaypath getbuffer strdisplaypath getlength strdisplaypath releasebuffer bmenuisempty sharedmenu appendmenu mf_separator sharedmenu appendmenu mf_string mp_sharedfolders_first getresstring ids_view1 strdisplaypath getresstring ids_view2 bmenuisempty bmenuisempty sharedmenu trackpopupmenu tpm_leftalign tpm_rightbutton ptmenu ptmenu sharedmenu destroymenu void c directory tree ctrl onr button down uint n flags c point point catch wm rbuttondown and do not route it the default way otherwise we won t get a wm contextmenu c tree ctrl onr button down n flags point cdirectorytreectrl onrbuttondown nflags cpoint wm_rbuttondown wm_contextmenu ctreectrl onrbuttondown nflags void c directory tree ctrl on key down uint n char uint n rep cnt uint n flags if n char vk space htreeitem h item get selected item if h item share sub dir tree h item get key state vk control 0x8000 if ctrl space is passed to the tree control it just beeps and does not check uncheck the item set check h item get check h item return c tree ctrl on key down n char n rep cnt n flags cdirectorytreectrl onkeydown nchar nrepcnt nflags nchar vk_space hitem getselecteditem hitem sharesubdirtree hitem getkeystate vk_control setcheck hitem getcheck hitem ctreectrl onkeydown nchar nrepcnt nflags void c directory tree ctrl on char uint n char uint n rep cnt uint n flags if we let any keystrokes which are handled by us but not by the tree control pass to the control the user will hear a system event sound standard error bool b call default true if get key state vk control 0x8000 if n char vk space b call default false if b call default c tree ctrl on char n char n rep cnt n flags cdirectorytreectrl onchar nchar nrepcnt nflags bcalldefault getkeystate vk_control nchar vk_space bcalldefault bcalldefault ctreectrl onchar nchar nrepcnt nflags c property page cp pg directories idd cpropertypage cppgdirectories cp pg directories cp pg directories cppgdirectories cppgdirectories void cp pg directories localize void if m hwnd set window text get res string ids pw dir get dlg item idc incoming frm set window text get res string ids pw incoming get dlg item idc temp frm set window text get res string ids pw temp get dlg item idc selincdir set window text get res string ids pw browse get dlg item idc seltempdir set window text get res string ids pw browse get dlg item idc shared frm set window text get res string ids pw shared cppgdirectories m_hwnd setwindowtext getresstring ids_pw_dir getdlgitem idc_incoming_frm setwindowtext getresstring ids_pw_incoming getdlgitem idc_temp_frm setwindowtext getresstring ids_pw_temp getdlgitem idc_selincdir setwindowtext getresstring ids_pw_browse getdlgitem idc_seltempdir setwindowtext getresstring ids_pw_browse getdlgitem idc_shared_frm setwindowtext getresstring ids_pw_shared void cp pg directories load settings void get dlg item idc incfiles set window text the prefs incomingdir c string tempfolders for int i 0 i the prefs tempdir get count i tempfolders append the prefs get temp dir i if i 1 the prefs tempdir get count tempfolders append t get dlg item idc tempfiles set window text tempfolders m shareselector set shared directories the prefs shareddir list fill unc list cppgdirectories loadsettings getdlgitem idc_incfiles setwindowtext theprefs cstring theprefs getcount theprefs gettempdir theprefs getcount _t getdlgitem idc_tempfiles setwindowtext m_shareselector setshareddirectories theprefs shareddir_list fillunclist void cp pg directories fill unc list void m ctluncpaths delete all items for position pos the prefs shareddir list get head position pos 0 c string folder the prefs shareddir list get next pos if path isunc folder m ctluncpaths insert item 0 folder cppgdirectories fillunclist m_ctluncpaths deleteallitems theprefs shareddir_list getheadposition cstring theprefs shareddir_list getnext pathisunc m_ctluncpaths insertitem void cp pg directories do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc shareselector m shareselector ddx control pdx idc unclist m ctluncpaths cppgdirectories dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_shareselector m_shareselector ddx_control idc_unclist m_ctluncpaths bool cp pg directories on init dialog c wait cursor cur wait initialization of that dialog may take a while c property page on init dialog init window styles this m shareselector init c edit get dlg item idc incfiles set limit text 509 c edit get dlg item idc tempfiles set limit text 509 m ctluncpaths insert column 0 get res string ids uncfolders lvcfmt left 280 1 m ctluncpaths set extended style lvs ex fullrowselect get dlg item idc seltempdiradd show window the prefs is ext controls enabled sw show sw hide load settings localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgdirectories oninitdialog cwaitcursor curwait cpropertypage oninitdialog initwindowstyles m_shareselector cedit getdlgitem idc_incfiles setlimittext cedit getdlgitem idc_tempfiles setlimittext m_ctluncpaths insertcolumn getresstring ids_uncfolders lvcfmt_left m_ctluncpaths setextendedstyle lvs_ex_fullrowselect getdlgitem idc_seltempdiradd showwindow theprefs isextcontrolsenabled sw_show sw_hide loadsettings bool cp pg directories on apply bool testtempdirchanged false c string testincdirchanged the prefs get incoming dir c string str incoming dir get dlg item text idc incfiles str incoming dir if str incoming dir is empty str incoming dir the prefs get app dir t incoming set dlg item text idc incfiles str incoming dir if the prefs is installation directory str incoming dir afx message box get res string ids wrn incfile reserved return false checking specified tempdir s c string str temp dir get dlg item text idc tempfiles str temp dir if str temp dir is empty str temp dir the prefs get app dir t temp set dlg item text idc tempfiles str temp dir int cur pos 0 c string array temptempfolders c string atmp str temp dir tokenize t cur pos while atmp is empty atmp trim if atmp is empty if compare directories str incoming dir atmp 0 afx message box get res string ids wrn inctemp same return false if the prefs is installation directory atmp afx message box get res string ids wrn tempfiles reserved return false bool doubled false for int i 0 i temptempfolders get count i avoid double tempdirs if temptempfolders get at i compare no case atmp 0 doubled true break if doubled temptempfolders add atmp if the prefs tempdir get count temptempfolders get count if atmp compare no case the prefs get temp dir temptempfolders get count 1 0 testtempdirchanged true else testtempdirchanged true atmp str temp dir tokenize t cur pos if temptempfolders is empty temptempfolders add str temp dir the prefs get app dir t temp if temptempfolders get count the prefs tempdir get count testtempdirchanged true applying tempdirs if testtempdirchanged the prefs tempdir remove all for int i 0 i temptempfolders get count i c string toadd temptempfolders get at i make foldername toadd get buffer max path toadd release buffer if path file exists toadd create directory toadd null if path file exists toadd the prefs tempdir add toadd incomingdir sntprintf the prefs incomingdir arrsize the prefs incomingdir t s str incoming dir make foldername the prefs incomingdir stprintf the prefs get category 0 incomingpath t s the prefs incomingdir the prefs shareddir list remove all m shareselector get shared directories the prefs shareddir list for int i 0 i m ctluncpaths get item count i the prefs shareddir list add tail m ctluncpaths get item text i 0 check shared directories for reserved folder names position pos the prefs shareddir list get head position while pos position pos last pos const c string rstr dir the prefs shareddir list get next pos if the prefs is shareable directory rstr dir the prefs shareddir list remove at pos last if testtempdirchanged afx message box get res string ids settingchanged restart on changing incoming dir update incoming dirs of category of the same path if testincdirchanged compare no case the prefs get incoming dir 0 c string oldpath bool dontaskagain false for int cat 1 cat the prefs get cat count 1 cat oldpath c string the prefs get cat path cat if oldpath left testincdirchanged get length compare no case testincdirchanged 0 if dontaskagain dontaskagain true if afx message box get res string ids updatecatincomingdirs mb yesno idno break sntprintf the prefs get category cat incomingpath arrsize the prefs get category cat incomingpath t s s the prefs get incoming dir oldpath mid testincdirchanged get length the app emuledlg sharedfileswnd reload set modified 0 return c property page on apply cppgdirectories onapply cstring theprefs getincomingdir cstring strincomingdir getdlgitemtext idc_incfiles strincomingdir strincomingdir isempty strincomingdir theprefs getappdir _t setdlgitemtext idc_incfiles strincomingdir theprefs isinstallationdirectory strincomingdir afxmessagebox getresstring ids_wrn_incfile_reserved cstring strtempdir getdlgitemtext idc_tempfiles strtempdir strtempdir isempty strtempdir theprefs getappdir _t setdlgitemtext idc_tempfiles strtempdir curpos cstringarray cstring strtempdir _t curpos isempty isempty comparedirectories strincomingdir afxmessagebox getresstring ids_wrn_inctemp_same theprefs isinstallationdirectory afxmessagebox getresstring ids_wrn_tempfiles_reserved getcount getat comparenocase theprefs getcount getcount comparenocase theprefs gettempdir getcount strtempdir _t curpos isempty strtempdir theprefs getappdir _t getcount theprefs getcount theprefs removeall getcount cstring getat makefoldername getbuffer max_path releasebuffer pathfileexists createdirectory pathfileexists theprefs _sntprintf theprefs theprefs _t strincomingdir makefoldername theprefs _stprintf theprefs getcategory _t theprefs theprefs shareddir_list removeall m_shareselector getshareddirectories theprefs shareddir_list m_ctluncpaths getitemcount theprefs shareddir_list addtail m_ctluncpaths getitemtext theprefs shareddir_list getheadposition poslast cstring rstrdir theprefs shareddir_list getnext theprefs isshareabledirectory rstrdir theprefs shareddir_list removeat poslast afxmessagebox getresstring ids_settingchanged_restart comparenocase theprefs getincomingdir cstring theprefs getcatcount cstring theprefs getcatpath getlength comparenocase afxmessagebox getresstring ids_updatecatincomingdirs mb_yesno _sntprintf theprefs getcategory theprefs getcategory _t theprefs getincomingdir getlength theapp setmodified cpropertypage onapply bool cp pg directories on command wparam w param lparam l param if w param um itemstatechanged set modified else if w param id help on help return true return c property page on command w param l param cppgdirectories oncommand wparam lparam wparam um_itemstatechanged setmodified wparam id_help onhelp cpropertypage oncommand wparam lparam void cp pg directories on bn clicked selincdir tchar buffer max path 0 get dlg item text idc incfiles buffer arrsize buffer if select dir get safe hwnd buffer get res string ids select incomingdir get dlg item idc incfiles set window text buffer cppgdirectories onbnclickedselincdir max_path getdlgitemtext idc_incfiles selectdir getsafehwnd getresstring ids_select_incomingdir getdlgitem idc_incfiles setwindowtext void cp pg directories on bn clicked seltempdir tchar buffer max path 0 get dlg item text idc tempfiles buffer arrsize buffer if select dir get safe hwnd buffer get res string ids select tempdir get dlg item idc tempfiles set window text buffer cppgdirectories onbnclickedseltempdir max_path getdlgitemtext idc_tempfiles selectdir getsafehwnd getresstring ids_select_tempdir getdlgitem idc_tempfiles setwindowtext void cp pg directories on bn clicked addunc input box inputbox inputbox set labels get res string ids uncfolders get res string ids uncfolders t server share if inputbox do modal idok return c string unc inputbox get input basic unc check if path isunc unc afx message box get res string ids err badunc mb iconerror return if unc right 1 t unc delete unc get length 1 1 for position pos the prefs shareddir list get head position pos 0 if unc compare no case the prefs shareddir list get next pos 0 return for int posi 0 posi m ctluncpaths get item count posi if unc compare no case m ctluncpaths get item text posi 0 0 return m ctluncpaths insert item m ctluncpaths get item count unc set modified cppgdirectories onbnclickedaddunc inputbox setlabels getresstring ids_uncfolders getresstring ids_uncfolders _t domodal cstring getinput pathisunc afxmessagebox getresstring ids_err_badunc mb_iconerror _t getlength theprefs shareddir_list getheadposition comparenocase theprefs shareddir_list getnext m_ctluncpaths getitemcount comparenocase m_ctluncpaths getitemtext m_ctluncpaths insertitem m_ctluncpaths getitemcount setmodified void cp pg directories on bn clicked remunc int index m ctluncpaths get selection mark if index 1 m ctluncpaths get selected count 0 return m ctluncpaths delete item index set modified cppgdirectories onbnclickedremunc m_ctluncpaths getselectionmark m_ctluncpaths getselectedcount m_ctluncpaths deleteitem setmodified void cp pg directories on help the app show help emule faq preferences directories cppgdirectories onhelp theapp showhelp emule_faq_preferences_directories bool cp pg directories on help info helpinfo p help info on help return true cppgdirectories onhelpinfo phelpinfo onhelp void cp pg directories on bn clicked seltempdiradd c string paths get dlg item text idc tempfiles paths tchar buffer max path 0 get dlg item text idc tempfiles buffer arrsize buffer if select dir get safe hwnd buffer get res string ids select tempdir paths append t paths append buffer set dlg item text idc tempfiles paths cppgdirectories onbnclickedseltempdiradd cstring getdlgitemtext idc_tempfiles max_path getdlgitemtext idc_tempfiles selectdir getsafehwnd getresstring ids_select_tempdir _t setdlgitemtext idc_tempfiles cp pg files cp pg files c property page cp pg files idd cppgfiles cppgfiles cpropertypage cppgfiles cp pg files cp pg files cppgfiles cppgfiles void cp pg files localize void if m hwnd set window text get res string ids pw files get dlg item idc pf timecalc set window text get res string ids pf advancedcalc get dlg item idc seemyshare frm set window text get res string ids pw share get dlg item idc seeshare1 set window text get res string ids pw ever get dlg item idc seeshare2 set window text get res string ids fstatus friendsonly get dlg item idc seeshare3 set window text get res string ids pw noone get dlg item idc uap set window text get res string ids pw uap get dlg item idc dap set window text get res string ids pw dap get dlg item idc previewprio set window text get res string ids downloadmoviechunks get dlg item idc addnewfilespaused set window text get res string ids addnewfilespaused get dlg item idc watchcb set window text get res string ids pf watchcb get dlg item idc fullchunktrans set window text get res string ids fullchunktrans get dlg item idc startnextfile set window text get res string ids startnextfile get dlg item idc startnextfilecat set window text get res string ids pref startnextfilecat get dlg item idc startnextfilecat2 set window text get res string ids pref startnextfilecatonly get dlg item idc fnc set window text get res string ids edit get dlg item idc onnd set window text get res string ids onnewdownload get dlg item idc fncleanup set window text get res string ids autocleanupfn get dlg item idc staticvideoplayer set window text get res string ids pw videoplayer get dlg item idc videobackup set window text get res string ids videobackup get dlg item idc static empty set window text get res string ids static empty get dlg item idc browsev set window text get res string ids pw browse get dlg item idc rememberdownloaded set window text get res string ids pw rememberdownloaded get dlg item idc remembercancelled set window text get res string ids pw remembercancelled cppgfiles m_hwnd setwindowtext getresstring ids_pw_files getdlgitem idc_pf_timecalc setwindowtext getresstring ids_pf_advancedcalc getdlgitem idc_seemyshare_frm setwindowtext getresstring ids_pw_share getdlgitem idc_seeshare1 setwindowtext getresstring ids_pw_ever getdlgitem idc_seeshare2 setwindowtext getresstring ids_fstatus_friendsonly getdlgitem idc_seeshare3 setwindowtext getresstring ids_pw_noone getdlgitem idc_uap setwindowtext getresstring ids_pw_uap getdlgitem idc_dap setwindowtext getresstring ids_pw_dap getdlgitem idc_previewprio setwindowtext getresstring ids_downloadmoviechunks getdlgitem idc_addnewfilespaused setwindowtext getresstring ids_addnewfilespaused getdlgitem idc_watchcb setwindowtext getresstring ids_pf_watchcb getdlgitem idc_fullchunktrans setwindowtext getresstring ids_fullchunktrans getdlgitem idc_startnextfile setwindowtext getresstring ids_startnextfile getdlgitem idc_startnextfilecat setwindowtext getresstring ids_pref_startnextfilecat getdlgitem idc_startnextfilecat2 setwindowtext getresstring ids_pref_startnextfilecatonly getdlgitem idc_fnc setwindowtext getresstring ids_edit getdlgitem idc_onnd setwindowtext getresstring ids_onnewdownload getdlgitem idc_fncleanup setwindowtext getresstring ids_autocleanupfn getdlgitem idc_staticvideoplayer setwindowtext getresstring ids_pw_videoplayer getdlgitem idc_videobackup setwindowtext getresstring ids_videobackup getdlgitem idc_static_empty setwindowtext getresstring ids_static_empty getdlgitem idc_browsev setwindowtext getresstring ids_pw_browse getdlgitem idc_rememberdownloaded setwindowtext getresstring ids_pw_rememberdownloaded getdlgitem idc_remembercancelled setwindowtext getresstring ids_pw_remembercancelled void cp pg files load settings void assert vsfa everybody 0 assert vsfa friends 1 assert vsfa nobody 2 check radio button idc seeshare1 idc seeshare3 idc seeshare1 the prefs m iseeshares if the prefs addnewfilespaused check dlg button idc addnewfilespaused 1 else check dlg button idc addnewfilespaused 0 if the prefs m buseoldtimeremaining check dlg button idc pf timecalc 0 else check dlg button idc pf timecalc 1 if the prefs m bpreviewprio check dlg button idc previewprio 1 else check dlg button idc previewprio 0 if the prefs m bdap check dlg button idc dap 1 else check dlg button idc dap 0 if the prefs m buap check dlg button idc uap 1 else check dlg button idc uap 0 if the prefs m btransferfullchunks check dlg button idc fullchunktrans 1 else check dlg button idc fullchunktrans 0 check dlg button idc startnextfilecat false check dlg button idc startnextfilecat2 false if the prefs m istartnextfile check dlg button idc startnextfile 1 if the prefs m istartnextfile 2 check dlg button idc startnextfilecat true else if the prefs m istartnextfile 3 check dlg button idc startnextfilecat2 true else check dlg button idc startnextfile 0 get dlg item idc videoplayer set window text the prefs video player if the prefs movie preview backup check dlg button idc videobackup 1 else check dlg button idc videobackup 0 check dlg button idc fncleanup uint8 the prefs auto filename cleanup if the prefs watchclipboard check dlg button idc watchcb 1 else check dlg button idc watchcb 0 if the prefs is remembering downloaded files check dlg button idc rememberdownloaded 1 else check dlg button idc rememberdownloaded 0 if the prefs is remembering cancelled files check dlg button idc remembercancelled 1 else check dlg button idc remembercancelled 0 get dlg item idc startnextfilecat enable window is dlg button checked idc startnextfile cppgfiles loadsettings vsfaeverybody vsfafriends vsfanobody checkradiobutton idc_seeshare1 idc_seeshare3 idc_seeshare1 theprefs m_iseeshares theprefs checkdlgbutton idc_addnewfilespaused checkdlgbutton idc_addnewfilespaused theprefs m_buseoldtimeremaining checkdlgbutton idc_pf_timecalc checkdlgbutton idc_pf_timecalc theprefs m_bpreviewprio checkdlgbutton idc_previewprio checkdlgbutton idc_previewprio theprefs m_bdap checkdlgbutton idc_dap checkdlgbutton idc_dap theprefs m_buap checkdlgbutton idc_uap checkdlgbutton idc_uap theprefs m_btransferfullchunks checkdlgbutton idc_fullchunktrans checkdlgbutton idc_fullchunktrans checkdlgbutton idc_startnextfilecat checkdlgbutton idc_startnextfilecat2 theprefs m_istartnextfile checkdlgbutton idc_startnextfile theprefs m_istartnextfile checkdlgbutton idc_startnextfilecat theprefs m_istartnextfile checkdlgbutton idc_startnextfilecat2 checkdlgbutton idc_startnextfile getdlgitem idc_videoplayer setwindowtext theprefs videoplayer theprefs moviepreviewbackup checkdlgbutton idc_videobackup checkdlgbutton idc_videobackup checkdlgbutton idc_fncleanup theprefs autofilenamecleanup theprefs checkdlgbutton idc_watchcb checkdlgbutton idc_watchcb theprefs isrememberingdownloadedfiles checkdlgbutton idc_rememberdownloaded checkdlgbutton idc_rememberdownloaded theprefs isrememberingcancelledfiles checkdlgbutton idc_remembercancelled checkdlgbutton idc_remembercancelled getdlgitem idc_startnextfilecat enablewindow isdlgbuttonchecked idc_startnextfile void cp pg files on settings change cat uint8 index bool on is dlg button checked index 1 idc startnextfilecat idc startnextfilecat2 0 if on check dlg button index 1 idc startnextfilecat2 idc startnextfilecat false on settings change cppgfiles onsettingschangecat isdlgbuttonchecked idc_startnextfilecat idc_startnextfilecat2 checkdlgbutton idc_startnextfilecat2 idc_startnextfilecat onsettingschange void cp pg files do data exchange c data exchange pdx c property page do data exchange pdx cppgfiles dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg files on init dialog c property page on init dialog init window styles this load settings localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgfiles oninitdialog cpropertypage oninitdialog initwindowstyles loadsettings bool cp pg files on apply c string buffer if is dlg button checked idc seeshare1 the prefs m iseeshares vsfa everybody else if is dlg button checked idc seeshare2 the prefs m iseeshares vsfa friends else the prefs m iseeshares vsfa nobody bool b old preview prio the prefs m bpreviewprio if is dlg button checked idc previewprio the prefs m bpreviewprio true else the prefs m bpreviewprio false if b old preview prio the prefs m bpreviewprio the app emuledlg transferwnd downloadlistctrl create menues if is dlg button checked idc dap the prefs m bdap true else the prefs m bdap false if is dlg button checked idc uap the prefs m buap true else the prefs m buap false if is dlg button checked idc startnextfile the prefs m istartnextfile 1 if is dlg button checked idc startnextfilecat the prefs m istartnextfile 2 else if is dlg button checked idc startnextfilecat2 the prefs m istartnextfile 3 else the prefs m istartnextfile 0 if is dlg button checked idc fullchunktrans the prefs m btransferfullchunks true else the prefs m btransferfullchunks false if is dlg button checked idc watchcb the prefs watchclipboard true else the prefs watchclipboard false if is dlg button checked idc rememberdownloaded the prefs set remember downloaded files true else the prefs set remember downloaded files false if is dlg button checked idc remembercancelled the prefs set remember cancelled files true else the prefs set remember cancelled files false the prefs addnewfilespaused is dlg button checked idc addnewfilespaused 0 the prefs autofilenamecleanup is dlg button checked idc fncleanup 0 the prefs m buseoldtimeremaining is dlg button checked idc pf timecalc 0 get dlg item idc videoplayer get window text buffer sntprintf the prefs video player arrsize the prefs video player t s buffer the prefs movie preview backup is dlg button checked idc videobackup 0 load settings set modified false return c property page on apply cppgfiles onapply cstring isdlgbuttonchecked idc_seeshare1 theprefs m_iseeshares vsfaeverybody isdlgbuttonchecked idc_seeshare2 theprefs m_iseeshares vsfafriends theprefs m_iseeshares vsfanobody boldpreviewprio theprefs m_bpreviewprio isdlgbuttonchecked idc_previewprio theprefs m_bpreviewprio theprefs m_bpreviewprio boldpreviewprio theprefs m_bpreviewprio theapp createmenues isdlgbuttonchecked idc_dap theprefs m_bdap theprefs m_bdap isdlgbuttonchecked idc_uap theprefs m_buap theprefs m_buap isdlgbuttonchecked idc_startnextfile theprefs m_istartnextfile isdlgbuttonchecked idc_startnextfilecat theprefs m_istartnextfile isdlgbuttonchecked idc_startnextfilecat2 theprefs m_istartnextfile theprefs m_istartnextfile isdlgbuttonchecked idc_fullchunktrans theprefs m_btransferfullchunks theprefs m_btransferfullchunks isdlgbuttonchecked idc_watchcb theprefs theprefs isdlgbuttonchecked idc_rememberdownloaded theprefs setrememberdownloadedfiles theprefs setrememberdownloadedfiles isdlgbuttonchecked idc_remembercancelled theprefs setremembercancelledfiles theprefs setremembercancelledfiles theprefs isdlgbuttonchecked idc_addnewfilespaused theprefs isdlgbuttonchecked idc_fncleanup theprefs m_buseoldtimeremaining isdlgbuttonchecked idc_pf_timecalc getdlgitem idc_videoplayer getwindowtext _sntprintf theprefs videoplayer theprefs videoplayer _t theprefs moviepreviewbackup isdlgbuttonchecked idc_videobackup loadsettings setmodified cpropertypage onapply bool cp pg files on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgfiles oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg files on set cleanup filter c string prompt get res string ids filterfilenameword input box inputbox inputbox set labels get res string ids fnfiltertitle prompt the prefs get filename cleanups inputbox do modal if inputbox was cancelled the prefs set filename cleanups inputbox get input cppgfiles onsetcleanupfilter cstring getresstring ids_filterfilenameword inputbox setlabels getresstring ids_fnfiltertitle theprefs getfilenamecleanups domodal wascancelled theprefs setfilenamecleanups getinput void cp pg files browse videoplayer c string str player path get dlg item text idc videoplayer str player path c file dialog dlg file true t exe str player path ofn filemustexist ofn pathmustexist ofn hidereadonly t executable exe exe null 0 if dlg file do modal idok get dlg item idc videoplayer set window text dlg file get path name set modified cppgfiles browsevideoplayer cstring strplayerpath getdlgitemtext idc_videoplayer strplayerpath cfiledialog dlgfile _t strplayerpath ofn_filemustexist ofn_pathmustexist ofn_hidereadonly _t dlgfile domodal getdlgitem idc_videoplayer setwindowtext dlgfile getpathname setmodified void cp pg files on settings change set modified get dlg item idc startnextfilecat enable window is dlg button checked idc startnextfile get dlg item idc startnextfilecat2 enable window is dlg button checked idc startnextfile cppgfiles onsettingschange setmodified getdlgitem idc_startnextfilecat enablewindow isdlgbuttonchecked idc_startnextfile getdlgitem idc_startnextfilecat2 enablewindow isdlgbuttonchecked idc_startnextfile void cp pg files on help the app show help emule faq preferences files cppgfiles onhelp theapp showhelp emule_faq_preferences_files bool cp pg files on help info helpinfo p help info on help return true cppgfiles onhelpinfo phelpinfo onhelp c colour popup c colour popup initialise ccolourpopup ccolourpopup lpctstr sz custom text null initialise m crcolour m crinitialcolour cr colour m pparent p parent wnd m strdefaulttext sz default text sz default text t m strcustomtext sz custom text sz custom text t c colour popup create p cr colour p parent wnd sz default text sz custom text szcustomtext m_crcolour m_crinitialcolour crcolour m_pparent pparentwnd m_strdefaulttext szdefaulttext szdefaulttext _t m_strcustomtext szcustomtext szcustomtext _t ccolourpopup crcolour pparentwnd szdefaulttext szcustomtext void c colour popup initialise m nnumcolours sizeof m crcolours sizeof colour table entry assert m nnumcolours max colours if m nnumcolours max colours m nnumcolours max colours m nnumcolumns 0 m nnumrows 0 m nboxsize 18 m nmargin get system metrics sm cxedge m ncurrentsel invalid colour m nchosencoloursel invalid colour m pparent null m crcolour m crinitialcolour rgb 0 0 0 m bchildwindowvisible false idiot check make sure the colour square is at least 5 x 5 if m nboxsize 2 m nmargin 2 5 m nboxsize 5 2 m nmargin 2 create the font nonclientmetrics ncm ncm cb size sizeof nonclientmetrics verify system parameters info spi getnonclientmetrics sizeof nonclientmetrics ncm 0 m font create font indirect ncm lf message font create the palette struct logpalette log palette paletteentry pal entry max colours pal logpalette p log palette logpalette pal p log palette pal version 0x300 p log palette pal num entries word m nnumcolours for int i 0 i m nnumcolours i p log palette pal pal entry i pe red getr value m crcolours i cr colour p log palette pal pal entry i pe green getg value m crcolours i cr colour p log palette pal pal entry i pe blue getb value m crcolours i cr colour p log palette pal pal entry i pe flags 0 m palette create palette p log palette ccolourpopup m_nnumcolours m_crcolours colourtableentry m_nnumcolours max_colours m_nnumcolours max_colours m_nnumcolours max_colours m_nnumcolumns m_nnumrows m_nboxsize m_nmargin getsystemmetrics sm_cxedge m_ncurrentsel invalid_colour m_nchosencoloursel invalid_colour m_pparent m_crcolour m_crinitialcolour m_bchildwindowvisible m_nboxsize m_nmargin m_nboxsize m_nmargin cbsize systemparametersinfo spi_getnonclientmetrics m_font createfontindirect lfmessagefont logpalette palentry max_colours plogpalette plogpalette palversion plogpalette palnumentries m_nnumcolours m_nnumcolours plogpalette palpalentry pered getrvalue m_crcolours crcolour plogpalette palpalentry pegreen getgvalue m_crcolours crcolour plogpalette palpalentry peblue getbvalue m_crcolours crcolour plogpalette palpalentry peflags m_palette createpalette plogpalette lpctstr sz custom text null assert p parent wnd is window p parent wnd get safe hwnd m pparent p parent wnd m crcolour m crinitialcolour cr colour get the class name and create the window c string sz class name afx register wnd class cs classdc cs savebits cs hredraw cs vredraw afx get app load standard cursor idc arrow hbrush color btnface 1 0 if c wnd create ex 0 sz class name t ws visible ws popup p x p y 100 100 size updated soon p parent wnd get safe hwnd 0 null return false store the custom text if sz custom text null m strcustomtext sz custom text store the default area text if sz default text null m strdefaulttext sz default text set the window size set window size create the tooltips create tool tips find which cell if any corresponds to the initial colour find cell from colour cr colour capture all mouse events for the life of this window set capture return true szcustomtext pparentwnd iswindow pparentwnd getsafehwnd m_pparent pparentwnd m_crcolour m_crinitialcolour crcolour cstring szclassname afxregisterwndclass cs_classdc cs_savebits cs_hredraw cs_vredraw afxgetapp loadstandardcursor idc_arrow color_btnface cwnd createex szclassname _t ws_visible ws_popup pparentwnd getsafehwnd szcustomtext m_strcustomtext szcustomtext szdefaulttext m_strdefaulttext szdefaulttext setwindowsize createtooltips findcellfromcolour crcolour setcapture bool c colour popup pre translate message msg p msg m tooltip relay event p msg fix adrian roman sometimes if the picker loses focus it is never destroyed if get capture get safe hwnd m hwnd set capture return c wnd pre translate message p msg ccolourpopup pretranslatemessage pmsg m_tooltip relayevent pmsg getcapture getsafehwnd m_hwnd setcapture cwnd pretranslatemessage pmsg c colour popup c colour popup m font delete object m palette delete object ccolourpopup ccolourpopup m_font deleteobject m_palette deleteobject bool c colour popup get cell rect int n index const lprect rect if n index custom box value set rect rect m customtextrect left m customtextrect top m customtextrect right m customtextrect bottom return true else if n index default box value set rect rect m defaulttextrect left m defaulttextrect top m defaulttextrect right m defaulttextrect bottom return true if n index 0 n index m nnumcolours return false rect left get column n index m nboxsize m nmargin rect top get row n index m nboxsize m nmargin move everything down if we are displaying a default text area if m strdefaulttext get length rect top m nmargin m defaulttextrect height rect right rect left m nboxsize rect bottom rect top m nboxsize return true ccolourpopup getcellrect nindex nindex custom_box_value setrect m_customtextrect m_customtextrect m_customtextrect m_customtextrect nindex default_box_value setrect m_defaulttextrect m_defaulttextrect m_defaulttextrect m_defaulttextrect nindex nindex m_nnumcolours getcolumn nindex m_nboxsize m_nmargin getrow nindex m_nboxsize m_nmargin m_strdefaulttext getlength m_nmargin m_defaulttextrect m_nboxsize m_nboxsize void c colour popup find cell from colour colorref cr colour if cr colour clr default m strdefaulttext get length m nchosencoloursel default box value return for int i 0 i m nnumcolours i if get colour i cr colour m nchosencoloursel i return if m strcustomtext get length m nchosencoloursel custom box value else m nchosencoloursel invalid colour ccolourpopup findcellfromcolour crcolour crcolour clr_default m_strdefaulttext getlength m_nchosencoloursel default_box_value m_nnumcolours getcolour crcolour m_nchosencoloursel m_strcustomtext getlength m_nchosencoloursel custom_box_value m_nchosencoloursel invalid_colour void c colour popup set window size c size text size if we are showing a custom or default text area get the font and text size if m strcustomtext get length m strdefaulttext get length c clientdc dc this c font p old font c font dc select object m font get the size of the custom text if there is custom text text size c size 0 0 if m strcustomtext get length text size dc get text extent m strcustomtext get the size of the default text if there is default text if m strdefaulttext get length c size default size dc get text extent m strdefaulttext if default size cx text size cx text size cx default size cx if default size cy text size cy text size cy default size cy dc select object p old font text size c size 2 m nmargin 2 m nmargin add even more space to draw the horizontal line text size cy 2 m nmargin 2 get the number of columns and rows m nnumcolumns int sqrt double m nnumcolours for a square window yuk m nnumcolumns 8 m nnumrows m nnumcolours m nnumcolumns if m nnumcolours m nnumcolumns m nnumrows get the current window position and set the new size c rect rect get window rect rect m windowrect set rect rect left rect top rect left m nnumcolumns m nboxsize 2 m nmargin rect top m nnumrows m nboxsize 2 m nmargin if custom text then expand window if necessary and set text width as window width if m strdefaulttext get length if text size cx m windowrect width m windowrect right m windowrect left text size cx text size cx m windowrect width 2 m nmargin work out the text area m defaulttextrect set rect m nmargin m nmargin m nmargin text size cx 2 m nmargin text size cy m windowrect bottom m defaulttextrect height 2 m nmargin if custom text then expand window if necessary and set text width as window width if m strcustomtext get length if text size cx m windowrect width m windowrect right m windowrect left text size cx text size cx m windowrect width 2 m nmargin work out the text area m customtextrect set rect m nmargin m windowrect height m nmargin text size cx m windowrect height m nmargin text size cy m windowrect bottom m customtextrect height 2 m nmargin need to check it ll fit on screen too far right c size screen size get system metrics sm cxscreen get system metrics sm cyscreen if m windowrect right screen size cx m windowrect offset rect m windowrect right screen size cx 0 too far left if m windowrect left 0 m windowrect offset rect m windowrect left 0 bottom falling out of screen if m windowrect bottom screen size cy c rect parent rect m pparent get window rect parent rect m windowrect offset rect 0 parent rect height m windowrect height set the window size and position move window m windowrect true ccolourpopup setwindowsize csize textsize m_strcustomtext getlength m_strdefaulttext getlength cclientdc cfont poldfont cfont selectobject m_font textsize csize m_strcustomtext getlength textsize gettextextent m_strcustomtext m_strdefaulttext getlength csize defaultsize gettextextent m_strdefaulttext defaultsize textsize textsize defaultsize defaultsize textsize textsize defaultsize selectobject poldfont textsize csize m_nmargin m_nmargin textsize m_nmargin m_nnumcolumns m_nnumcolours m_nnumcolumns m_nnumrows m_nnumcolours m_nnumcolumns m_nnumcolours m_nnumcolumns m_nnumrows crect getwindowrect m_windowrect setrect m_nnumcolumns m_nboxsize m_nmargin m_nnumrows m_nboxsize m_nmargin m_strdefaulttext getlength textsize m_windowrect m_windowrect m_windowrect textsize textsize m_windowrect m_nmargin m_defaulttextrect setrect m_nmargin m_nmargin m_nmargin textsize m_nmargin textsize m_windowrect m_defaulttextrect m_nmargin m_strcustomtext getlength textsize m_windowrect m_windowrect m_windowrect textsize textsize m_windowrect m_nmargin m_customtextrect setrect m_nmargin m_windowrect m_nmargin textsize m_windowrect m_nmargin textsize m_windowrect m_customtextrect m_nmargin csize screensize getsystemmetrics sm_cxscreen getsystemmetrics sm_cyscreen m_windowrect screensize m_windowrect offsetrect m_windowrect screensize m_windowrect m_windowrect offsetrect m_windowrect m_windowrect screensize crect parentrect m_pparent getwindowrect parentrect m_windowrect offsetrect parentrect m_windowrect movewindow m_windowrect void c colour popup create tool tips create the tool tip if m tooltip create this return add a tool for each cell for int i 0 i m nnumcolours i c rect rect if get cell rect i rect continue m tooltip add tool this t rect 1 get colour name i ccolourpopup createtooltips m_tooltip m_nnumcolours crect getcellrect m_tooltip addtool _t getcolourname void c colour popup change selection int n index c clientdc dc this device context for drawing if n index m nnumcolours n index custom box value if m ncurrentsel 0 m ncurrentsel m nnumcolours m ncurrentsel custom box value m ncurrentsel default box value set current selection as invalid and redraw old selection this way the old selection will be drawn unselected int old sel m ncurrentsel m ncurrentsel invalid colour draw cell dc old sel set the current selection as row col and draw it will be drawn selected m ncurrentsel n index draw cell dc m ncurrentsel store the current colour if m ncurrentsel custom box value m pparent send message um cpn selchange wparam m crinitialcolour 0 else if m ncurrentsel default box value m crcolour clr default m pparent send message um cpn selchange wparam clr default 0 else m crcolour get colour m ncurrentsel m pparent send message um cpn selchange wparam m crcolour 0 ccolourpopup changeselection nindex cclientdc nindex m_nnumcolours nindex custom_box_value m_ncurrentsel m_ncurrentsel m_nnumcolours m_ncurrentsel custom_box_value m_ncurrentsel default_box_value oldsel m_ncurrentsel m_ncurrentsel invalid_colour drawcell oldsel m_ncurrentsel nindex drawcell m_ncurrentsel m_ncurrentsel custom_box_value m_pparent sendmessage um_cpn_selchange m_crinitialcolour m_ncurrentsel default_box_value m_crcolour clr_default m_pparent sendmessage um_cpn_selchange clr_default m_crcolour getcolour m_ncurrentsel m_pparent sendmessage um_cpn_selchange m_crcolour void c colour popup end selection int n message release capture if custom text selected perform a custom colour selection if n message um cpn selendcancel m ncurrentsel custom box value m bchildwindowvisible true c color dialog dlg m crinitialcolour cc fullopen cc anycolor this if dlg do modal idok m crcolour dlg get color else n message um cpn selendcancel m bchildwindowvisible false if n message um cpn selendcancel m crcolour m crinitialcolour m pparent send message n message wparam m crcolour 0 kill focus bug fixed by martin wawrusch if m bchildwindowvisible destroy window ccolourpopup endselection nmessage releasecapture nmessage um_cpn_selendcancel m_ncurrentsel custom_box_value m_bchildwindowvisible ccolordialog m_crinitialcolour cc_fullopen cc_anycolor domodal m_crcolour getcolor nmessage um_cpn_selendcancel m_bchildwindowvisible nmessage um_cpn_selendcancel m_crcolour m_crinitialcolour m_pparent sendmessage nmessage m_crcolour m_bchildwindowvisible destroywindow void c colour popup draw cell cdc pdc int n index for the custom text area if m strcustomtext get length n index custom box value the extent of the actual text button c rect text button rect m customtextrect text button rect top 2 m nmargin fill background pdc fill solid rect text button rect get sys color color 3dface draw horizontal line pdc fill solid rect m customtextrect left 2 m nmargin m customtextrect top m customtextrect width 4 m nmargin 1 get sys color color 3dshadow pdc fill solid rect m customtextrect left 2 m nmargin m customtextrect top 1 m customtextrect width 4 m nmargin 1 get sys color color 3dhilight text button rect deflate rect 1 1 fill background if m nchosencoloursel n index m ncurrentsel n index pdc fill solid rect text button rect get sys color color 3dlight else pdc fill solid rect text button rect get sys color color 3dface draw button if m ncurrentsel n index pdc draw edge text button rect bdr raisedinner bf rect else if m nchosencoloursel n index pdc draw edge text button rect bdr sunkenouter bf rect draw custom text c font p old font c font pdc select object m font pdc set bk mode transparent pdc draw text m strcustomtext text button rect dt center dt vcenter dt singleline pdc select object p old font return for the default text area if m strdefaulttext get length n index default box value fill background pdc fill solid rect m defaulttextrect get sys color color 3dface the extent of the actual text button c rect text button rect m defaulttextrect text button rect deflate rect 1 1 fill background if m nchosencoloursel n index m ncurrentsel n index pdc fill solid rect text button rect get sys color color 3dlight else pdc fill solid rect text button rect get sys color color 3dface draw thin line around text c rect line rect text button rect line rect deflate rect 2 m nmargin 2 m nmargin c pen pen ps solid 1 get sys color color 3dshadow c pen p old pen pdc select object pen pdc select stock object null brush pdc rectangle line rect pdc select object p old pen draw button if m ncurrentsel n index pdc draw edge text button rect bdr raisedinner bf rect else if m nchosencoloursel n index pdc draw edge text button rect bdr sunkenouter bf rect draw custom text c font p old font c font pdc select object m font pdc set bk mode transparent pdc draw text m strdefaulttext text button rect dt center dt vcenter dt singleline pdc select object p old font return c rect rect if get cell rect n index rect return select and realize the palette c palette p old palette null if pdc get device caps rastercaps rc palette p old palette pdc select palette m palette false pdc realize palette fill background if m nchosencoloursel n index m ncurrentsel n index pdc fill solid rect rect get sys color color 3dhilight else pdc fill solid rect rect get sys color color 3dface draw button if m ncurrentsel n index pdc draw edge rect bdr raisedinner bf rect else if m nchosencoloursel n index pdc draw edge rect bdr sunkenouter bf rect c brush brush palettergb getr value get colour n index getg value get colour n index getb value get colour n index c pen pen pen create pen ps solid 1 get sys color color 3dshadow c brush p old brush c brush pdc select object brush c pen p old pen c pen pdc select object pen draw the cell colour rect deflate rect m nmargin 1 m nmargin 1 pdc rectangle rect restore dc and cleanup pdc select object p old brush pdc select object p old pen brush delete object pen delete object if p old palette pdc get device caps rastercaps rc palette pdc select palette p old palette false ccolourpopup drawcell nindex m_strcustomtext getlength nindex custom_box_value crect textbuttonrect m_customtextrect textbuttonrect m_nmargin fillsolidrect textbuttonrect getsyscolor color_3dface fillsolidrect m_customtextrect m_nmargin m_customtextrect m_customtextrect m_nmargin getsyscolor color_3dshadow fillsolidrect m_customtextrect m_nmargin m_customtextrect m_customtextrect m_nmargin getsyscolor color_3dhilight textbuttonrect deflaterect m_nchosencoloursel nindex m_ncurrentsel nindex fillsolidrect textbuttonrect getsyscolor color_3dlight fillsolidrect textbuttonrect getsyscolor color_3dface m_ncurrentsel nindex drawedge textbuttonrect bdr_raisedinner bf_rect m_nchosencoloursel nindex drawedge textbuttonrect bdr_sunkenouter bf_rect cfont poldfont cfont selectobject m_font setbkmode drawtext m_strcustomtext textbuttonrect dt_center dt_vcenter dt_singleline selectobject poldfont m_strdefaulttext getlength nindex default_box_value fillsolidrect m_defaulttextrect getsyscolor color_3dface crect textbuttonrect m_defaulttextrect textbuttonrect deflaterect m_nchosencoloursel nindex m_ncurrentsel nindex fillsolidrect textbuttonrect getsyscolor color_3dlight fillsolidrect textbuttonrect getsyscolor color_3dface crect linerect textbuttonrect linerect deflaterect m_nmargin m_nmargin cpen ps_solid getsyscolor color_3dshadow cpen poldpen selectobject selectstockobject null_brush linerect selectobject poldpen m_ncurrentsel nindex drawedge textbuttonrect bdr_raisedinner bf_rect m_nchosencoloursel nindex drawedge textbuttonrect bdr_sunkenouter bf_rect cfont poldfont cfont selectobject m_font setbkmode drawtext m_strdefaulttext textbuttonrect dt_center dt_vcenter dt_singleline selectobject poldfont crect getcellrect nindex cpalette poldpalette getdevicecaps rc_palette poldpalette selectpalette m_palette realizepalette m_nchosencoloursel nindex m_ncurrentsel nindex fillsolidrect getsyscolor color_3dhilight fillsolidrect getsyscolor color_3dface m_ncurrentsel nindex drawedge bdr_raisedinner bf_rect m_nchosencoloursel nindex drawedge bdr_sunkenouter bf_rect cbrush getrvalue getcolour nindex getgvalue getcolour nindex getbvalue getcolour nindex cpen createpen ps_solid getsyscolor color_3dshadow cbrush poldbrush cbrush selectobject cpen poldpen cpen selectobject deflaterect m_nmargin m_nmargin selectobject poldbrush selectobject poldpen deleteobject deleteobject poldpalette getdevicecaps rc_palette selectpalette poldpalette int c colour popup get index int row int col const if row custom box value col custom box value m strcustomtext get length return custom box value else if row default box value col default box value m strdefaulttext get length return default box value else if row 0 col 0 row m nnumrows col m nnumcolumns return invalid colour else if row m nnumcolumns col m nnumcolours return invalid colour else return row m nnumcolumns col ccolourpopup getindex custom_box_value custom_box_value m_strcustomtext getlength custom_box_value default_box_value default_box_value m_strdefaulttext getlength default_box_value m_nnumrows m_nnumcolumns invalid_colour m_nnumcolumns m_nnumcolours invalid_colour m_nnumcolumns int c colour popup get row int n index const if n index custom box value m strcustomtext get length return custom box value else if n index default box value m strdefaulttext get length return default box value else if n index 0 n index m nnumcolours return invalid colour else return n index m nnumcolumns ccolourpopup getrow nindex nindex custom_box_value m_strcustomtext getlength custom_box_value nindex default_box_value m_strdefaulttext getlength default_box_value nindex nindex m_nnumcolours invalid_colour nindex m_nnumcolumns int c colour popup get column int n index const if n index custom box value m strcustomtext get length return custom box value else if n index default box value m strdefaulttext get length return default box value else if n index 0 n index m nnumcolours return invalid colour else return n index m nnumcolumns ccolourpopup getcolumn nindex nindex custom_box_value m_strcustomtext getlength custom_box_value nindex default_box_value m_strdefaulttext getlength default_box_value nindex nindex m_nnumcolours invalid_colour nindex m_nnumcolumns void c colour popup on nc destroy c wnd on nc destroy delete this ccolourpopup onncdestroy cwnd onncdestroy void c colour popup onl button up uint n flags c point point c wnd onl button up n flags point dword pos get message pos point c point loword pos hiword pos if m windowrect pt in rect point end selection um cpn selendok else end selection um cpn selendcancel ccolourpopup onlbuttonup nflags cpoint cwnd onlbuttonup nflags getmessagepos cpoint m_windowrect ptinrect endselection um_cpn_selendok endselection um_cpn_selendcancel void c colour popup on paint c paintdc dc this device context for painting draw the default area text if m strdefaulttext get length draw cell dc default box value draw colour cells for int i 0 i m nnumcolours i draw cell dc i draw custom text if m strcustomtext get length draw cell dc custom box value draw raised window edge ex window style ws ex windowedge is sposed to do this but for some reason isn t c rect rect get client rect rect dc draw edge rect edge raised bf rect ccolourpopup onpaint cpaintdc m_strdefaulttext getlength drawcell default_box_value m_nnumcolours drawcell m_strcustomtext getlength drawcell custom_box_value ws_ex_windowedge crect getclientrect drawedge edge_raised bf_rect void c colour popup on mouse move uint n flags c point point int n new selection invalid colour translate points to be relative raised window edge point x m nmargin point y m nmargin first check we aren t in text box if m strcustomtext get length m customtextrect pt in rect point n new selection custom box value else if m strdefaulttext get length m defaulttextrect pt in rect point n new selection default box value else take into account text box if m strdefaulttext get length point y m defaulttextrect height get the row and column n new selection get index point y m nboxsize point x m nboxsize in range if not default and exit if n new selection 0 n new selection m nnumcolours c wnd on mouse move n flags point return ok we have the row and column of the current selection may be custom box value has the row col selection changed if yes then redraw old and new cells if n new selection m ncurrentsel change selection n new selection c wnd on mouse move n flags point ccolourpopup onmousemove nflags cpoint nnewselection invalid_colour m_nmargin m_nmargin m_strcustomtext getlength m_customtextrect ptinrect nnewselection custom_box_value m_strdefaulttext getlength m_defaulttextrect ptinrect nnewselection default_box_value m_strdefaulttext getlength m_defaulttextrect nnewselection getindex m_nboxsize m_nboxsize nnewselection nnewselection m_nnumcolours cwnd onmousemove nflags custom_box_value nnewselection m_ncurrentsel changeselection nnewselection cwnd onmousemove nflags void c colour popup on key down uint n char uint n rep cnt uint n flags int row get row m ncurrentsel col get column m ncurrentsel if n char vk down if row default box value row col 0 else if row custom box value if m strdefaulttext get length row col default box value else row col 0 else row if get index row col 0 if m strcustomtext get length row col custom box value else if m strdefaulttext get length row col default box value else row col 0 change selection get index row col if n char vk up if row default box value if m strcustomtext get length row col custom box value else row get row m nnumcolours 1 col get column m nnumcolours 1 else if row custom box value row get row m nnumcolours 1 col get column m nnumcolours 1 else if row 0 row else row 0 if m strdefaulttext get length row col default box value else if m strcustomtext get length row col custom box value else row get row m nnumcolours 1 col get column m nnumcolours 1 change selection get index row col if n char vk right if row default box value row col 0 else if row custom box value if m strdefaulttext get length row col default box value else row col 0 else if col m nnumcolumns 1 col else col 0 row if get index row col invalid colour if m strcustomtext get length row col custom box value else if m strdefaulttext get length row col default box value else row col 0 change selection get index row col if n char vk left if row default box value if m strcustomtext get length row col custom box value else row get row m nnumcolours 1 col get column m nnumcolours 1 else if row custom box value row get row m nnumcolours 1 col get column m nnumcolours 1 else if col 0 col else col 0 if row 0 row col m nnumcolumns 1 else if m strdefaulttext get length row col default box value else if m strcustomtext get length row col custom box value else row get row m nnumcolours 1 col get column m nnumcolours 1 change selection get index row col if n char vk escape m crcolour m crinitialcolour end selection um cpn selendcancel return if n char vk return n char vk space end selection um cpn selendok return c wnd on key down n char n rep cnt n flags ccolourpopup onkeydown nchar nrepcnt nflags getrow m_ncurrentsel getcolumn m_ncurrentsel nchar vk_down default_box_value custom_box_value m_strdefaulttext getlength default_box_value getindex m_strcustomtext getlength custom_box_value m_strdefaulttext getlength default_box_value changeselection getindex nchar vk_up default_box_value m_strcustomtext getlength custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours m_strdefaulttext getlength default_box_value m_strcustomtext getlength custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours changeselection getindex nchar vk_right default_box_value custom_box_value m_strdefaulttext getlength default_box_value m_nnumcolumns getindex invalid_colour m_strcustomtext getlength custom_box_value m_strdefaulttext getlength default_box_value changeselection getindex nchar vk_left default_box_value m_strcustomtext getlength custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours m_nnumcolumns m_strdefaulttext getlength default_box_value m_strcustomtext getlength custom_box_value getrow m_nnumcolours getcolumn m_nnumcolours changeselection getindex nchar vk_escape m_crcolour m_crinitialcolour endselection um_cpn_selendcancel nchar vk_return nchar vk_space endselection um_cpn_selendok cwnd onkeydown nchar nrepcnt nflags bool c colour popup on query new palette invalidate return c wnd on query new palette ccolourpopup onquerynewpalette cwnd onquerynewpalette void c colour popup on palette changed c wnd p focus wnd c wnd on palette changed p focus wnd if p focus wnd get safe hwnd get safe hwnd invalidate ccolourpopup onpalettechanged cwnd pfocuswnd cwnd onpalettechanged pfocuswnd pfocuswnd getsafehwnd getsafehwnd void c colour popup on kill focus c wnd p new wnd c wnd on kill focus p new wnd release capture destroy window causes crash when custom colour dialog appears ccolourpopup onkillfocus cwnd pnewwnd cwnd onkillfocus pnewwnd releasecapture destroywindow void c colour popup on activate app bool b active dword h task c wnd on activate app b active h task if deactivating app cancel this selection if b active end selection um cpn selendcancel ccolourpopup onactivateapp bactive htask cwnd onactivateapp bactive htask bactive endselection um_cpn_selendcancel m bpopupactive false m btrackselection false m_bpopupactive m_btrackselection c color button c color button void ccolorbutton ccolorbutton colorref c color button get color void const return m color ccolorbutton getcolor m_color void c color button set color colorref color m color color if is window m hwnd redraw window ccolorbutton setcolor m_color iswindow m_hwnd redrawwindow colorref c color button get default color void const return m defaultcolor ccolorbutton getdefaultcolor m_defaultcolor void c color button set default color colorref color m defaultcolor color ccolorbutton setdefaultcolor m_defaultcolor void c color button set custom text lpctstr tsz text m strcustomtext tsz text ccolorbutton setcustomtext tsztext m_strcustomtext tsztext void c color button set default text lpctstr tsz text m strdefaulttext tsz text ccolorbutton setdefaulttext tsztext m_strdefaulttext tsztext void c color button set track selection bool b track m btrackselection b track ccolorbutton settrackselection btrack m_btrackselection btrack bool c color button get track selection void const return m btrackselection ccolorbutton gettrackselection m_btrackselection void c color button draw item lpdrawitemstruct lp draw item struct assert lp draw item struct cdc pdc cdc from handle lp draw item struct hdc uint state lp draw item struct item state c rect r draw lp draw item struct rc item c rect r arrow if m bpopupactive state ods selected ods focus draw outer edge uint u frame state dfcs buttonpush dfcs adjustrect if state ods selected u frame state dfcs pushed if state ods disabled u frame state dfcs inactive pdc draw frame control r draw dfc button u frame state if state ods selected r draw offset rect 1 1 draw focus if state ods focus rect r focus r draw left r draw top r draw right 1 r draw bottom pdc draw focus rect r focus r draw deflate rect get system metrics sm cxedge get system metrics sm cyedge draw arrow r arrow left r draw right g ciarrowsizex get system metrics sm cxedge 2 r arrow right r arrow left g ciarrowsizex r arrow top r draw bottom r draw top 2 g ciarrowsizey 2 r arrow bottom r draw bottom r draw top 2 g ciarrowsizey 2 draw arrow pdc r arrow 0 state ods disabled get sys color color graytext rgb 0 0 0 r draw right r arrow left get system metrics sm cxedge 2 draw separator pdc draw edge r draw edge etched bf right r draw right get system metrics sm cxedge 2 1 draw color if state ods disabled 0 pdc fill solid rect r draw m color clr default m defaultcolor m color frame rect pdc m hdc r draw hbrush get stock object black brush ccolorbutton drawitem lpdrawitemstruct lpdrawitemstruct fromhandle lpdrawitemstruct lpdrawitemstruct itemstate crect rdraw lpdrawitemstruct rcitem crect rarrow m_bpopupactive ods_selected ods_focus uframestate dfcs_buttonpush dfcs_adjustrect ods_selected uframestate dfcs_pushed ods_disabled uframestate dfcs_inactive drawframecontrol rdraw dfc_button uframestate ods_selected rdraw offsetrect ods_focus rfocus rdraw rdraw rdraw rdraw drawfocusrect rfocus rdraw deflaterect getsystemmetrics sm_cxedge getsystemmetrics sm_cyedge rarrow rdraw g_ciarrowsizex getsystemmetrics sm_cxedge rarrow rarrow g_ciarrowsizex rarrow rdraw rdraw g_ciarrowsizey rarrow rdraw rdraw g_ciarrowsizey drawarrow rarrow ods_disabled getsyscolor color_graytext rdraw rarrow getsystemmetrics sm_cxedge drawedge rdraw edge_etched bf_right rdraw getsystemmetrics sm_cxedge ods_disabled fillsolidrect rdraw m_color clr_default m_defaultcolor m_color framerect m_hdc rdraw getstockobject black_brush void c color button pre subclass window modify style 0 bs ownerdraw inherited pre subclass window ccolorbutton presubclasswindow modifystyle bs_ownerdraw _inherited presubclasswindow bool c color button on clicked m bpopupactive true c rect r draw get window rect r draw new c colour popup c point r draw left r draw bottom point to display popup m color selected colour this parent m strdefaulttext default text area m strcustomtext custom text c wnd p parent get parent if p parent p parent send message um cpn dropdown lparam m color wparam get dlg ctrlid return true ccolorbutton onclicked m_bpopupactive crect rdraw getwindowrect rdraw ccolourpopup cpoint rdraw rdraw m_color m_strdefaulttext m_strcustomtext cwnd pparent getparent pparent pparent sendmessage um_cpn_dropdown m_color getdlgctrlid int c color button on create lpcreatestruct lp create struct if c button on create lp create struct 1 return 1 return 0 ccolorbutton oncreate lpcreatestruct cbutton oncreate lpcreatestruct long c color button on sel endok uint l param long w param m bpopupactive false colorref old color m color color colorref l param c wnd p parent get parent if p parent p parent send message um cpn closeup l param wparam get dlg ctrlid p parent send message um cpn selendok l param wparam get dlg ctrlid if old color m color if p parent p parent send message um cpn selchange m color clr default m color m defaultcolor wparam get dlg ctrlid return true ccolorbutton onselendok lparam wparam m_bpopupactive oldcolor m_color lparam cwnd pparent getparent pparent pparent sendmessage um_cpn_closeup lparam getdlgctrlid pparent sendmessage um_cpn_selendok lparam getdlgctrlid oldcolor m_color pparent pparent sendmessage um_cpn_selchange m_color clr_default m_color m_defaultcolor getdlgctrlid long c color button on sel end cancel uint l param long w param m bpopupactive false color colorref l param c wnd p parent get parent if p parent p parent send message um cpn closeup l param wparam get dlg ctrlid p parent send message um cpn selendcancel l param wparam get dlg ctrlid return true ccolorbutton onselendcancel lparam wparam m_bpopupactive lparam cwnd pparent getparent pparent pparent sendmessage um_cpn_closeup lparam getdlgctrlid pparent sendmessage um_cpn_selendcancel lparam getdlgctrlid long c color button on sel change uint l param long w param if m btrackselection color colorref l param c wnd p parent get parent if p parent p parent send message um cpn selchange m color clr default m color m defaultcolor wparam get dlg ctrlid cax2 defaultcol fix return true ccolorbutton onselchange lparam wparam m_btrackselection lparam cwnd pparent getparent pparent pparent sendmessage um_cpn_selchange m_color clr_default m_color m_defaultcolor getdlgctrlid colorref clr arrow rgb 0 0 0 point pts arrow 3 switch i direction case 0 down pts arrow 0 x p rect left pts arrow 0 y p rect top pts arrow 1 x p rect right pts arrow 1 y p rect top pts arrow 2 x p rect left p rect right 2 pts arrow 2 y p rect bottom break case 1 up pts arrow 0 x p rect left pts arrow 0 y p rect bottom pts arrow 1 x p rect right pts arrow 1 y p rect bottom pts arrow 2 x p rect left p rect right 2 pts arrow 2 y p rect top break case 2 left pts arrow 0 x p rect right pts arrow 0 y p rect top pts arrow 1 x p rect right pts arrow 1 y p rect bottom pts arrow 2 x p rect left pts arrow 2 y p rect top p rect bottom 2 break case 3 right pts arrow 0 x p rect left pts arrow 0 y p rect top pts arrow 1 x p rect left pts arrow 1 y p rect bottom pts arrow 2 x p rect right pts arrow 2 y p rect top p rect bottom 2 break c brush brs arrow clr arrow c pen pen arrow ps solid 1 clr arrow c brush p old brush pdc select object brs arrow c pen p old pen pdc select object pen arrow pdc set poly fill mode winding pdc polygon pts arrow 3 pdc select object p old brush pdc select object p old pen clrarrow ptsarrow idirection ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect ptsarrow prect prect cbrush brsarrow clrarrow cpen penarrow ps_solid clrarrow cbrush poldbrush selectobject brsarrow cpen poldpen selectobject penarrow setpolyfillmode ptsarrow selectobject poldbrush selectobject poldpen c property page cp pg stats idd m igraphsupdate 0 m igraphsavgtime 0 m istatsupdate 0 m istatscolors 0 m pdwstatscolors null m bmodified false cpropertypage cppgstats m_igraphsupdate m_igraphsavgtime m_istatsupdate m_istatscolors m_pdwstatscolors m_bmodified cp pg stats cp pg stats cppgstats cppgstats void cp pg stats localize void if m hwnd get dlg item idc graphs set window text get res string ids graphs get dlg item idc stree set window text get res string ids stree get dlg item idc static cgraphscale set window text get res string ids ppgstats yscale get dlg item idc static cgraphratio set window text get res string ids ppgstats acratio set window text get res string ids statssetupinfo get dlg item idc prefcolors set window text get res string ids colors m colors reset content int i item i item m colors add string get res string ids sp background m colors set item data i item 0 i item m colors add string get res string ids sp grid m colors set item data i item 1 i item m colors add string get res string ids sp dl3 m colors set item data i item 4 i item m colors add string get res string ids sp dl2 m colors set item data i item 3 i item m colors add string get res string ids sp dl1 m colors set item data i item 2 i item m colors add string get res string ids sp ul3 m colors set item data i item 7 i item m colors add string get res string ids sp ul2 m colors set item data i item 6 i item m colors add string get res string ids sp ul1 m colors set item data i item 5 i item m colors add string get res string ids sp ulslotsnooverhead m colors set item data i item 14 i item m colors add string get res string ids sp ulfriends m colors set item data i item 13 i item m colors add string get res string ids sp actcon m colors set item data i item 8 i item m colors add string get res string ids sp actul m colors set item data i item 10 i item m colors add string get res string ids sp totalul m colors set item data i item 9 i item m colors add string get res string ids sp actdl m colors set item data i item 12 i item m colors add string get res string ids sp iconbar m colors set item data i item 11 m ctlcolor custom text get res string ids col morecolors m ctlcolor default text null m colors set cur sel 0 on cbn selchange colorselector show interval cppgstats m_hwnd getdlgitem idc_graphs setwindowtext getresstring ids_graphs getdlgitem idc_stree setwindowtext getresstring ids_stree getdlgitem idc_static_cgraphscale setwindowtext getresstring ids_ppgstats_yscale getdlgitem idc_static_cgraphratio setwindowtext getresstring ids_ppgstats_acratio setwindowtext getresstring ids_statssetupinfo getdlgitem idc_prefcolors setwindowtext getresstring ids_colors m_colors resetcontent iitem iitem m_colors addstring getresstring ids_sp_background m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_grid m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_dl3 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_dl2 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_dl1 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_ul3 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_ul2 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_ul1 m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_ulslotsnooverhead m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_ulfriends m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_actcon m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_actul m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_totalul m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_actdl m_colors setitemdata iitem iitem m_colors addstring getresstring ids_sp_iconbar m_colors setitemdata iitem m_ctlcolor customtext getresstring ids_col_morecolors m_ctlcolor defaulttext m_colors setcursel oncbnselchangecolorselector showinterval void cp pg stats show interval c string str label if m igraphsupdate 0 str label format get res string ids disabled else str label format get res string ids stats updatelabel m igraphsupdate get dlg item idc sliderinfo set window text str label if m igraphsavgtime 0 str label format get res string ids disabled else str label format get res string ids stats updatelabel m igraphsavgtime get dlg item idc sliderinfo2 set window text str label str label format get res string ids stats avglabel m istatsupdate get dlg item idc sliderinfo3 set window text str label cppgstats showinterval cstring strlabel m_igraphsupdate strlabel getresstring ids_disabled strlabel getresstring ids_stats_updatelabel m_igraphsupdate getdlgitem idc_sliderinfo setwindowtext strlabel m_igraphsavgtime strlabel getresstring ids_disabled strlabel getresstring ids_stats_updatelabel m_igraphsavgtime getdlgitem idc_sliderinfo2 setwindowtext strlabel strlabel getresstring ids_stats_avglabel m_istatsupdate getdlgitem idc_sliderinfo3 setwindowtext strlabel void cp pg stats set modified bool b changed m bmodified b changed c property page set modified b changed cppgstats setmodified bchanged m_bmodified bchanged cpropertypage setmodified bchanged void cp pg stats do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc colorselector m colors ddx control pdx idc color button m ctlcolor ddx control pdx idc cratio m cratio ddx control pdx idc slider m ctlgraphsupdate ddx control pdx idc slider2 m ctlstatsupdate ddx control pdx idc slider3 m ctlgraphsavgtime cppgstats dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_colorselector m_colors ddx_control idc_color_button m_ctlcolor ddx_control idc_cratio m_cratio ddx_control idc_slider m_ctlgraphsupdate ddx_control idc_slider2 m_ctlstatsupdate ddx_control idc_slider3 m_ctlgraphsavgtime bool cp pg stats on init dialog c property page on init dialog init window styles this c slider ctrl get dlg item idc slider set range 0 200 true m ctlgraphsupdate set pos the prefs get traffico meter interval m ctlgraphsupdate set tic freq 10 m ctlgraphsupdate set page size 10 m ctlstatsupdate set pos the prefs get stats interval m ctlstatsupdate set tic freq 10 m ctlstatsupdate set page size 10 m ctlgraphsavgtime set range 0 99 m ctlgraphsavgtime set pos the prefs get stats average minutes 1 for int i 10 i 100 i 10 m ctlgraphsavgtime set tic i 1 m ctlgraphsavgtime set page size 10 m igraphsupdate the prefs get traffico meter interval m igraphsavgtime the prefs get stats interval m istatsupdate the prefs get stats average minutes set the connections statistics y axis scale set dlg item int idc cgraphscale the prefs get stats max false build our ratio combo and select the item corresponding to the currently set preference m cratio add string t 1 1 m cratio add string t 1 2 m cratio add string t 1 3 m cratio add string t 1 4 m cratio add string t 1 5 m cratio add string t 1 10 m cratio add string t 1 20 int n the prefs get stats connections graph ratio m cratio set cur sel n 10 5 n 20 6 n 1 m istatscolors the prefs get num stats colors m pdwstatscolors new dword m istatscolors the prefs get all stats colors m istatscolors m pdwstatscolors localize set modified false return true return true unless you set the focus to a control exception ocx property pages should return false cppgstats oninitdialog cpropertypage oninitdialog initwindowstyles csliderctrl getdlgitem idc_slider setrange m_ctlgraphsupdate setpos theprefs gettrafficometerinterval m_ctlgraphsupdate setticfreq m_ctlgraphsupdate setpagesize m_ctlstatsupdate setpos theprefs getstatsinterval m_ctlstatsupdate setticfreq m_ctlstatsupdate setpagesize m_ctlgraphsavgtime setrange m_ctlgraphsavgtime setpos theprefs getstatsaverageminutes m_ctlgraphsavgtime settic m_ctlgraphsavgtime setpagesize m_igraphsupdate theprefs gettrafficometerinterval m_igraphsavgtime theprefs getstatsinterval m_istatsupdate theprefs getstatsaverageminutes setdlgitemint idc_cgraphscale theprefs getstatsmax m_cratio addstring _t m_cratio addstring _t m_cratio addstring _t m_cratio addstring _t m_cratio addstring _t m_cratio addstring _t m_cratio addstring _t theprefs getstatsconnectionsgraphratio m_cratio setcursel m_istatscolors theprefs getnumstatscolors m_pdwstatscolors m_istatscolors theprefs getallstatscolors m_istatscolors m_pdwstatscolors setmodified bool cp pg stats on apply todo cache all parameters stats should be redrawn deleted only if really needed if m bmodified bool b invalidate graphs false if the prefs set all stats colors m istatscolors m pdwstatscolors the app emuledlg show transfer rate true b invalidate graphs true if the prefs get traffico meter interval uint m igraphsupdate the prefs set traffico meter interval m igraphsupdate b invalidate graphs true if the prefs get stats interval uint m igraphsavgtime the prefs set stats interval m igraphsavgtime b invalidate graphs true if the prefs get stats average minutes uint m istatsupdate the prefs set stats average minutes m istatsupdate b invalidate graphs true tchar buffer 20 get dlg item idc cgraphscale get window text buffer arrsize buffer uint stats max tstoi buffer if stats max the prefs get max connections 5 if the prefs get stats max the prefs get max connections 5 the prefs set stats max the prefs get max connections 5 b invalidate graphs true sntprintf buffer arrsize buffer t d the prefs get stats max get dlg item idc cgraphscale set window text buffer else if the prefs get stats max stats max the prefs set stats max stats max b invalidate graphs true int n m cratio get cur sel uint u ratio n 5 10 n 6 20 n 1 index 5 1 10 and 6 1 20 if the prefs get stats connections graph ratio u ratio the prefs set stats connections graph ratio u ratio b invalidate graphs true if b invalidate graphs the app emuledlg statisticswnd update connections graph set new y upper bound and y ratio for active connections the app emuledlg statisticswnd localize the app emuledlg statisticswnd show interval the app emuledlg statisticswnd repaint meters the app emuledlg statisticswnd get dlg item idc stattree enable window the prefs get stats interval 0 set modified false return c property page on apply cppgstats onapply m_bmodified binvalidategraphs theprefs setallstatscolors m_istatscolors m_pdwstatscolors theapp showtransferrate binvalidategraphs theprefs gettrafficometerinterval m_igraphsupdate theprefs settrafficometerinterval m_igraphsupdate binvalidategraphs theprefs getstatsinterval m_igraphsavgtime theprefs setstatsinterval m_igraphsavgtime binvalidategraphs theprefs getstatsaverageminutes m_istatsupdate theprefs setstatsaverageminutes m_istatsupdate binvalidategraphs getdlgitem idc_cgraphscale getwindowtext statsmax _tstoi statsmax theprefs getmaxconnections theprefs getstatsmax theprefs getmaxconnections theprefs setstatsmax theprefs getmaxconnections binvalidategraphs _sntprintf _t theprefs getstatsmax getdlgitem idc_cgraphscale setwindowtext theprefs getstatsmax statsmax theprefs setstatsmax statsmax binvalidategraphs m_cratio getcursel uratio theprefs getstatsconnectionsgraphratio uratio theprefs setstatsconnectionsgraphratio uratio binvalidategraphs binvalidategraphs theapp updateconnectionsgraph theapp theapp showinterval theapp repaintmeters theapp getdlgitem idc_stattree enablewindow theprefs getstatsinterval setmodified cpropertypage onapply bool cp pg stats on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgstats oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg stats onh scroll uint nsb code uint n pos c scroll bar p scroll bar c slider ctrl slider c slider ctrl p scroll bar int position slider get pos if p scroll bar get safe hwnd m ctlgraphsupdate m hwnd if m igraphsupdate position m igraphsupdate position set modified true else if p scroll bar get safe hwnd m ctlstatsupdate m hwnd if m igraphsavgtime position m igraphsavgtime position set modified true else assert p scroll bar get safe hwnd m ctlgraphsavgtime m hwnd if m istatsupdate position 1 m istatsupdate position 1 set modified true show interval update data false c property page onh scroll nsb code n pos p scroll bar cppgstats onhscroll nsbcode npos cscrollbar pscrollbar csliderctrl csliderctrl pscrollbar getpos pscrollbar getsafehwnd m_ctlgraphsupdate m_hwnd m_igraphsupdate m_igraphsupdate setmodified pscrollbar getsafehwnd m_ctlstatsupdate m_hwnd m_igraphsavgtime m_igraphsavgtime setmodified pscrollbar getsafehwnd m_ctlgraphsavgtime m_hwnd m_istatsupdate m_istatsupdate setmodified showinterval updatedata cpropertypage onhscroll nsbcode npos pscrollbar void cp pg stats on cbn selchange colorselector int i sel m colors get cur sel if i sel 0 int i index m colors get item data i sel if i index 0 i index m istatscolors m ctlcolor set color m pdwstatscolors i index cppgstats oncbnselchangecolorselector isel m_colors getcursel isel iindex m_colors getitemdata isel iindex iindex m_istatscolors m_ctlcolor setcolor m_pdwstatscolors iindex long cp pg stats on color popup sel change uint l param long w param int i sel m colors get cur sel if i sel 0 int i index m colors get item data i sel if i index 0 i index m istatscolors colorref cr color m ctlcolor get color if cr color m pdwstatscolors i index m pdwstatscolors i index cr color set modified true return true cppgstats oncolorpopupselchange lparam wparam isel m_colors getcursel isel iindex m_colors getitemdata isel iindex iindex m_istatscolors crcolor m_ctlcolor getcolor crcolor m_pdwstatscolors iindex m_pdwstatscolors iindex crcolor setmodified void cp pg stats on help the app show help emule faq preferences statistics cppgstats onhelp theapp showhelp emule_faq_preferences_statistics bool cp pg stats on help info helpinfo p help info on help return true cppgstats onhelpinfo phelpinfo onhelp void cp pg stats on destroy delete m pdwstatscolors m pdwstatscolors null cppgstats ondestroy m_pdwstatscolors m_pdwstatscolors c property page cp pg notify idd m benableemail true cpropertypage cppgnotify m_benableemail cp pg notify cp pg notify cppgnotify cppgnotify void cp pg notify localize void if m hwnd set window text get res string ids pw ekdev options get dlg item idc cb tbn usesound set window text get res string ids pw tbn usesound get dlg item idc cb tbn nosound set window text get res string ids nosound get dlg item idc btn browse wav set window text get res string ids pw browse get dlg item idc cb tbn onlog set window text get res string ids pw tbn onlog get dlg item idc cb tbn onchat set window text get res string ids pw tbn onchat get dlg item idc cb tbn pop always set window text get res string ids pw tbn pop always get dlg item idc cb tbn ondownload set window text get res string ids pw tbn ondownload t get dlg item idc cb tbn onnewdownload set window text get res string ids tbn onnewdownload get dlg item idc taskbarnotifier set window text get res string ids pw taskbarnotifier get dlg item idc cb tbn importatnt set window text get res string ids ps tbn important t get dlg item idc cb tbn onnewversion set window text get res string ids cb tbn onnewversion get dlg item idc tbn options set window text get res string ids pw tbn options get dlg item idc cb tbn usespeech set window text get res string ids usespeech get dlg item idc emailnot group set window text get res string ids pw emailnotifications t get dlg item idc txt smtpserver set window text get res string ids pw smtpserver get dlg item idc txt receiver set window text get res string ids pw receiveraddress get dlg item idc txt sender set window text get res string ids pw senderaddress get dlg item idc cb enablenotifications set window text get res string ids pw enableemail cppgnotify m_hwnd setwindowtext getresstring ids_pw_ekdev_options getdlgitem idc_cb_tbn_usesound setwindowtext getresstring ids_pw_tbn_usesound getdlgitem idc_cb_tbn_nosound setwindowtext getresstring ids_nosound getdlgitem idc_btn_browse_wav setwindowtext getresstring ids_pw_browse getdlgitem idc_cb_tbn_onlog setwindowtext getresstring ids_pw_tbn_onlog getdlgitem idc_cb_tbn_onchat setwindowtext getresstring ids_pw_tbn_onchat getdlgitem idc_cb_tbn_pop_always setwindowtext getresstring ids_pw_tbn_pop_always getdlgitem idc_cb_tbn_ondownload setwindowtext getresstring ids_pw_tbn_ondownload _t getdlgitem idc_cb_tbn_onnewdownload setwindowtext getresstring ids_tbn_onnewdownload getdlgitem idc_taskbarnotifier setwindowtext getresstring ids_pw_taskbarnotifier getdlgitem idc_cb_tbn_importatnt setwindowtext getresstring ids_ps_tbn_important _t getdlgitem idc_cb_tbn_onnewversion setwindowtext getresstring ids_cb_tbn_onnewversion getdlgitem idc_tbn_options setwindowtext getresstring ids_pw_tbn_options getdlgitem idc_cb_tbn_usespeech setwindowtext getresstring ids_usespeech getdlgitem idc_emailnot_group setwindowtext getresstring ids_pw_emailnotifications _t getdlgitem idc_txt_smtpserver setwindowtext getresstring ids_pw_smtpserver getdlgitem idc_txt_receiver setwindowtext getresstring ids_pw_receiveraddress getdlgitem idc_txt_sender setwindowtext getresstring ids_pw_senderaddress getdlgitem idc_cb_enablenotifications setwindowtext getresstring ids_pw_enableemail void cp pg notify update controls get dlg item idc edit tbn wavfile enable window is dlg button checked idc cb tbn usesound get dlg item idc btn browse wav enable window is dlg button checked idc cb tbn usesound get dlg item idc edit smtpserver enable window is dlg button checked idc cb enablenotifications get dlg item idc edit receiver enable window is dlg button checked idc cb enablenotifications get dlg item idc edit sender enable window is dlg button checked idc cb enablenotifications cppgnotify updatecontrols getdlgitem idc_edit_tbn_wavfile enablewindow isdlgbuttonchecked idc_cb_tbn_usesound getdlgitem idc_btn_browse_wav enablewindow isdlgbuttonchecked idc_cb_tbn_usesound getdlgitem idc_edit_smtpserver enablewindow isdlgbuttonchecked idc_cb_enablenotifications getdlgitem idc_edit_receiver enablewindow isdlgbuttonchecked idc_cb_enablenotifications getdlgitem idc_edit_sender enablewindow isdlgbuttonchecked idc_cb_enablenotifications void cp pg notify apply notifier sound type get dlg item text idc edit tbn wavfile the prefs notifier sound file if is dlg button checked idc cb tbn usesound the prefs notifier sound type ntfst sound file else if is dlg button checked idc cb tbn usespeech the prefs notifier sound type is speech engine available ntfst speech ntfst no sound else assert is dlg button checked idc cb tbn nosound the prefs notifier sound type ntfst no sound cppgnotify applynotifiersoundtype getdlgitemtext idc_edit_tbn_wavfile theprefs notifiersoundfile isdlgbuttonchecked idc_cb_tbn_usesound theprefs notifiersoundtype ntfstsoundfile isdlgbuttonchecked idc_cb_tbn_usespeech theprefs notifiersoundtype isspeechengineavailable ntfstspeech ntfstnosound isdlgbuttonchecked idc_cb_tbn_nosound theprefs notifiersoundtype ntfstnosound void cp pg notify do data exchange c data exchange pdx c property page do data exchange pdx cppgnotify dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg notify on init dialog if atl ver 0x0710 m benableemail is runningxpsp2 0 endif c property page on init dialog init window styles this int i btnid if the prefs notifier sound type ntfst sound file i btnid idc cb tbn usesound else if the prefs notifier sound type ntfst speech i btnid idc cb tbn usespeech else assert the prefs notifier sound type ntfst no sound i btnid idc cb tbn nosound assert idc cb tbn nosound idc cb tbn usesound idc cb tbn usesound idc cb tbn usespeech check radio button idc cb tbn nosound idc cb tbn usespeech i btnid check dlg button idc cb tbn ondownload the prefs notifier on download finished bst checked bst unchecked check dlg button idc cb tbn onnewdownload the prefs notifier on new download bst checked bst unchecked check dlg button idc cb tbn onchat the prefs notifier on chat bst checked bst unchecked check dlg button idc cb tbn onlog the prefs notifier on log bst checked bst unchecked check dlg button idc cb tbn importatnt the prefs notifier on important error bst checked bst unchecked check dlg button idc cb tbn pop always the prefs notifier on every chat msg bst checked bst unchecked check dlg button idc cb tbn onnewversion the prefs notifier on new version bst checked bst unchecked c button btnptr c button get dlg item idc cb tbn pop always btnptr enable window is dlg button checked idc cb tbn onchat set dlg item text idc edit tbn wavfile the prefs notifier sound file if m benableemail check dlg button idc cb enablenotifications bst unchecked get dlg item idc emailnot group enable window false get dlg item idc cb enablenotifications enable window false get dlg item idc txt smtpserver enable window false get dlg item idc txt receiver enable window false get dlg item idc txt sender enable window false get dlg item idc edit smtpserver enable window false get dlg item idc edit receiver enable window false get dlg item idc edit sender enable window false else set dlg item text idc edit smtpserver the prefs get notifier mail server set dlg item text idc edit receiver the prefs get notifier mail receiver set dlg item text idc edit sender the prefs get notifier mail sender if the prefs is notifier send mail enabled check dlg button idc cb enablenotifications bst checked get dlg item idc edit smtpserver enable window true get dlg item idc edit receiver enable window true get dlg item idc edit sender enable window true else check dlg button idc cb enablenotifications bst unchecked get dlg item idc edit smtpserver enable window false get dlg item idc edit receiver enable window false get dlg item idc edit sender enable window false update controls localize get dlg item idc cb tbn usespeech enable window is speech engine available return true return true unless you set the focus to a control exception ocx property pages should return false cppgnotify oninitdialog _atl_ver m_benableemail isrunningxpsp2 cpropertypage oninitdialog initwindowstyles ibtnid theprefs notifiersoundtype ntfstsoundfile ibtnid idc_cb_tbn_usesound theprefs notifiersoundtype ntfstspeech ibtnid idc_cb_tbn_usespeech theprefs notifiersoundtype ntfstnosound ibtnid idc_cb_tbn_nosound idc_cb_tbn_nosound idc_cb_tbn_usesound idc_cb_tbn_usesound idc_cb_tbn_usespeech checkradiobutton idc_cb_tbn_nosound idc_cb_tbn_usespeech ibtnid checkdlgbutton idc_cb_tbn_ondownload theprefs notifierondownloadfinished bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_onnewdownload theprefs notifieronnewdownload bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_onchat theprefs notifieronchat bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_onlog theprefs notifieronlog bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_importatnt theprefs notifieronimportanterror bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_pop_always theprefs notifieroneverychatmsg bst_checked bst_unchecked checkdlgbutton idc_cb_tbn_onnewversion theprefs notifieronnewversion bst_checked bst_unchecked cbutton cbutton getdlgitem idc_cb_tbn_pop_always enablewindow isdlgbuttonchecked idc_cb_tbn_onchat setdlgitemtext idc_edit_tbn_wavfile theprefs notifiersoundfile m_benableemail checkdlgbutton idc_cb_enablenotifications bst_unchecked getdlgitem idc_emailnot_group enablewindow getdlgitem idc_cb_enablenotifications enablewindow getdlgitem idc_txt_smtpserver enablewindow getdlgitem idc_txt_receiver enablewindow getdlgitem idc_txt_sender enablewindow getdlgitem idc_edit_smtpserver enablewindow getdlgitem idc_edit_receiver enablewindow getdlgitem idc_edit_sender enablewindow setdlgitemtext idc_edit_smtpserver theprefs getnotifiermailserver setdlgitemtext idc_edit_receiver theprefs getnotifiermailreceiver setdlgitemtext idc_edit_sender theprefs getnotifiermailsender theprefs isnotifiersendmailenabled checkdlgbutton idc_cb_enablenotifications bst_checked getdlgitem idc_edit_smtpserver enablewindow getdlgitem idc_edit_receiver enablewindow getdlgitem idc_edit_sender enablewindow checkdlgbutton idc_cb_enablenotifications bst_unchecked getdlgitem idc_edit_smtpserver enablewindow getdlgitem idc_edit_receiver enablewindow getdlgitem idc_edit_sender enablewindow updatecontrols getdlgitem idc_cb_tbn_usespeech enablewindow isspeechengineavailable bool cp pg notify on apply the prefs notifier on download finished is dlg button checked idc cb tbn ondownload 0 the prefs notifier on new download is dlg button checked idc cb tbn onnewdownload 0 the prefs notifier on chat is dlg button checked idc cb tbn onchat 0 the prefs notifier on log is dlg button checked idc cb tbn onlog 0 the prefs notifier on important error is dlg button checked idc cb tbn importatnt 0 the prefs notifier on every chat msg is dlg button checked idc cb tbn pop always 0 the prefs notifier on new version is dlg button checked idc cb tbn onnewversion 0 if m benableemail get dlg item text idc edit smtpserver the prefs m strnotifiermailserver get dlg item text idc edit sender the prefs m strnotifiermailsender get dlg item text idc edit receiver the prefs m strnotifiermailreceiver the prefs set notifier send mail is dlg button checked idc cb enablenotifications 0 apply notifier sound type if the prefs notifier sound type ntfst speech releasetts set modified false return c property page on apply cppgnotify onapply theprefs notifierondownloadfinished isdlgbuttonchecked idc_cb_tbn_ondownload theprefs notifieronnewdownload isdlgbuttonchecked idc_cb_tbn_onnewdownload theprefs notifieronchat isdlgbuttonchecked idc_cb_tbn_onchat theprefs notifieronlog isdlgbuttonchecked idc_cb_tbn_onlog theprefs notifieronimportanterror isdlgbuttonchecked idc_cb_tbn_importatnt theprefs notifieroneverychatmsg isdlgbuttonchecked idc_cb_tbn_pop_always theprefs notifieronnewversion isdlgbuttonchecked idc_cb_tbn_onnewversion m_benableemail getdlgitemtext idc_edit_smtpserver theprefs m_strnotifiermailserver getdlgitemtext idc_edit_sender theprefs m_strnotifiermailsender getdlgitemtext idc_edit_receiver theprefs m_strnotifiermailreceiver theprefs setnotifiersendmail isdlgbuttonchecked idc_cb_enablenotifications applynotifiersoundtype theprefs notifiersoundtype ntfstspeech setmodified cpropertypage onapply bool cp pg notify on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgnotify oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg notify on help the app show help emule faq preferences notifications cppgnotify onhelp theapp showhelp emule_faq_preferences_notifications bool cp pg notify on help info helpinfo p help info on help return true cppgnotify onhelpinfo phelpinfo onhelp void cp pg notify on bn clicked no sound update controls set modified cppgnotify onbnclickednosound updatecontrols setmodified void cp pg notify on bn clicked use sound update controls set modified cppgnotify onbnclickedusesound updatecontrols setmodified void cp pg notify on bn clicked use speech update controls set modified cppgnotify onbnclickedusespeech updatecontrols setmodified void cp pg notify on bn clicked on chat get dlg item idc cb tbn pop always enable window is dlg button checked idc cb tbn onchat set modified cppgnotify onbnclickedonchat getdlgitem idc_cb_tbn_pop_always enablewindow isdlgbuttonchecked idc_cb_tbn_onchat setmodified void cp pg notify on bn clicked browse audio file c string str wav path get dlg item text idc edit tbn wavfile str wav path c string buffer if dialog browse file buffer t audio files wav wav str wav path set dlg item text idc edit tbn wavfile buffer set modified cppgnotify onbnclickedbrowseaudiofile cstring strwavpath getdlgitemtext idc_edit_tbn_wavfile strwavpath cstring dialogbrowsefile _t strwavpath setdlgitemtext idc_edit_tbn_wavfile setmodified void cp pg notify on bn clicked test notification save current pref settings bool b cur notify on important error the prefs notifier on important error e notifier sound type i cur sound type the prefs notifier sound type c string str sound file the prefs notifier sound file temporary apply current settings from dialog the prefs notifier on important error true apply notifier sound type play test notification c string str test str test format get res string ids main ready the app m strcurversionlong the app emuledlg show notifier str test tbn importantevent restore pref settings the prefs notifier sound file str sound file the prefs notifier sound type i cur sound type the prefs notifier on important error b cur notify on important error cppgnotify onbnclickedtestnotification bcurnotifyonimportanterror theprefs notifieronimportanterror enotifiersoundtype icursoundtype theprefs notifiersoundtype cstring strsoundfile theprefs notifiersoundfile theprefs notifieronimportanterror applynotifiersoundtype cstring strtest strtest getresstring ids_main_ready theapp m_strcurversionlong theapp shownotifier strtest tbn_importantevent theprefs notifiersoundfile strsoundfile theprefs notifiersoundtype icursoundtype theprefs notifieronimportanterror bcurnotifyonimportanterror void cp pg notify on bn clicked cb enablenotifications update controls set modified cppgnotify onbnclickedcbenablenotifications updatecontrols setmodified c tree options ctrl c tree options ctrl m pcombo null m pedit null m pspin null m pbutton null m pdatetime null m pipaddress null ifdef idb tree ctrl options m nilid idb tree ctrl options endif m hcontrolitem null m btoggleovericononly false m bautoselect false m sseparator t m bbeingcleared false ctreeoptionsctrl ctreeoptionsctrl m_pcombo m_pedit m_pspin m_pbutton m_pdatetime m_pipaddress idb_tree_ctrl_options m_nilid idb_tree_ctrl_options m_hcontrolitem m_btoggleovericononly m_bautoselect m_sseparator _t m_bbeingcleared c tree options ctrl c tree options ctrl destroy old child control assert m pcombo null assert m pedit null assert m pspin null assert m pbutton null assert m pdatetime null assert m pipaddress null ctreeoptionsctrl ctreeoptionsctrl destroyoldchildcontrol m_pcombo m_pedit m_pspin m_pbutton m_pdatetime m_pipaddress dword c tree options ctrl get user item data htreeitem h item const c tree options item data p item data c tree options item data get item data h item assert p item data return p item data m dwitemdata ctreeoptionsctrl getuseritemdata hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwitemdata bool c tree options ctrl set user item data htreeitem h item dword dw data c tree options item data p item data c tree options item data get item data h item assert p item data p item data m dwitemdata dw data return true ctreeoptionsctrl setuseritemdata hitem dwdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwitemdata dwdata void c tree options ctrl clear m bbeingcleared true htreeitem h root get root item m hcontrolitem null if h root mem delete all items h root m bbeingcleared false ctreeoptionsctrl m_bbeingcleared hroot getrootitem m_hcontrolitem hroot memdeleteallitems hroot m_bbeingcleared bool c tree options ctrl delete all items clear let the base class do its thing return c tree ctrl delete all items ctreeoptionsctrl deleteallitems ctreectrl deleteallitems htreeitem c tree options ctrl insert group lpctstr lpsz item int n image htreeitem h parent htreeitem h after dword dw item data assert n image 9 you must specify an image index greater than 9 as the first 10 images in the image list are reserved for the checked and unchecked check box and radio buttons images htreeitem h item insert item lpsz item n image n image h parent h after c tree options item data p item data new c tree options item data p item data m pruntimeclass1 null p item data m type c tree options item data normal p item data m dwitemdata dw item data set item data h item dword p item data return h item ctreeoptionsctrl insertgroup lpszitem nimage hparent hafter dwitemdata nimage hitem insertitem lpszitem nimage nimage hparent hafter ctreeoptionsitemdata pitemdata ctreeoptionsitemdata pitemdata m_pruntimeclass1 pitemdata m_type ctreeoptionsitemdata pitemdata m_dwitemdata dwitemdata setitemdata hitem pitemdata hitem htreeitem c tree options ctrl insert check box lpctstr lpsz item htreeitem h parent bool b check htreeitem h after dword dw item data assert h parent tvi root is group h parent is check box h parent the parent of a check box must be a group item or another check box htreeitem h item insert item lpsz item 0 0 h parent h after c tree options item data p item data new c tree options item data p item data m pruntimeclass1 null p item data m type c tree options item data check box p item data m dwitemdata dw item data set item data h item dword p item data bool b success set check box h item b check assert b success return h item ctreeoptionsctrl insertcheckbox lpszitem hparent bcheck hafter dwitemdata hparent tvi_root isgroup hparent ischeckbox hparent hitem insertitem lpszitem hparent hafter ctreeoptionsitemdata pitemdata ctreeoptionsitemdata pitemdata m_pruntimeclass1 pitemdata m_type ctreeoptionsitemdata checkbox pitemdata m_dwitemdata dwitemdata setitemdata hitem pitemdata bsuccess setcheckbox hitem bcheck bsuccess hitem htreeitem c tree options ctrl insert radio button lpctstr lpsz item htreeitem h parent bool b check htreeitem h after dword dw item data assert is group h parent the parent of a radio item must be a group item htreeitem h item insert item lpsz item 2 2 h parent h after c tree options item data p item data new c tree options item data p item data m pruntimeclass1 null p item data m type c tree options item data radio button p item data m dwitemdata dw item data set item data h item dword p item data if b check if requested to check the newly added radio button bool b success set radio button h item assert b success return h item ctreeoptionsctrl insertradiobutton lpszitem hparent bcheck hafter dwitemdata isgroup hparent hitem insertitem lpszitem hparent hafter ctreeoptionsitemdata pitemdata ctreeoptionsitemdata pitemdata m_pruntimeclass1 pitemdata m_type ctreeoptionsitemdata radiobutton pitemdata m_dwitemdata dwitemdata setitemdata hitem pitemdata bcheck bsuccess setradiobutton hitem bsuccess hitem bool c tree options ctrl is group htreeitem h item const int n image 1 int n selected image 1 bool b success get item image h item n image n selected image assert b success return n image 7 ctreeoptionsctrl isgroup hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess nimage bool c tree options ctrl is check box htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data check box else return false ctreeoptionsctrl ischeckbox hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata checkbox bool c tree options ctrl is radio button htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data radio button else return false ctreeoptionsctrl isradiobutton hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata radiobutton bool c tree options ctrl is edit box htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data edit box else return false ctreeoptionsctrl iseditbox hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata editbox bool c tree options ctrl is file item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data file browser else return false ctreeoptionsctrl isfileitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata filebrowser bool c tree options ctrl is folder item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data folder browser else return false ctreeoptionsctrl isfolderitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata folderbrowser bool c tree options ctrl is color item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data color browser else return false ctreeoptionsctrl iscoloritem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata colorbrowser bool c tree options ctrl is font item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data font browser else return false ctreeoptionsctrl isfontitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata fontbrowser bool c tree options ctrl is date time item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data date time ctrl else return false ctreeoptionsctrl isdatetimeitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata datetimectrl bool c tree options ctrl isip address item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data ip address ctrl else return false ctreeoptionsctrl isipaddressitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata ipaddressctrl bool c tree options ctrl is opaque item htreeitem h item const c tree options item data p item data c tree options item data get item data h item if p item data return p item data m type c tree options item data opaque browser else return false ctreeoptionsctrl isopaqueitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata opaquebrowser bool c tree options ctrl set check box htreeitem h item bool b check validate our parameters assert is check box h item must be a check box to check it bool b semi verify get semi check box h item b semi bool b success if b check if b semi b success set item image h item 8 8 else b success set item image h item 1 1 else b success set item image h item 0 0 return b success ctreeoptionsctrl setcheckbox hitem bcheck ischeckbox hitem bsemi getsemicheckbox hitem bsemi bsuccess bcheck bsemi bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess bool c tree options ctrl get check box htreeitem h item bool b check const validate our parameters assert is check box h item must be a combo item to check it int n image int n selected image bool b success get item image h item n image n selected image assert b success b check n image 1 n image 5 n image 8 n image 9 return b success ctreeoptionsctrl getcheckbox hitem bcheck ischeckbox hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess bcheck nimage nimage nimage nimage bsuccess bool c tree options ctrl set radio button htreeitem h parent int n index validate our parameters assert is group h parent parent item must be a group item iterate through the child items and turn on the specified one and turn off all the other ones htreeitem h child get next item h parent tvgn child turn of redraw to q all the changes we re going to make here set redraw false int i 0 bool b checked some item false while h child if we reach a non radio button then break out of the loop if is radio button h child break if i n index turn this item on verify set item image h child 3 3 b checked some item true else bool b enable verify get radio button enable h child b enable turn this item off if b enable verify set item image h child 2 2 else verify set item image h child 4 4 move on to the next item h child get next item h child tvgn next i assert b checked some item you specified an index which does not exist reset the redraw flag set redraw true return true ctreeoptionsctrl setradiobutton hparent nindex isgroup hparent hchild getnextitem hparent tvgn_child setredraw bcheckedsomeitem hchild isradiobutton hchild nindex setitemimage hchild bcheckedsomeitem benable getradiobuttonenable hchild benable benable setitemimage hchild setitemimage hchild hchild getnextitem hchild tvgn_next bcheckedsomeitem setredraw bool c tree options ctrl set radio button htreeitem h item validate our parameters assert is radio button h item must be a radio item to check it iterate through the sibling items and turn them all off except this one htreeitem h parent get next item h item tvgn parent assert is group h parent parent item must be a group item iterate through the child items and turn on the specified one and turn off all the other ones htreeitem h child get next item h parent tvgn child turn of redraw to q all the changes we re going to make here set redraw false while h child if we reach a non radio button then break out of the loop if is radio button h child break if h child h item turn this item on bool b success set item image h child 3 3 assert b success else bool b enable verify get radio button enable h child b enable turn this item off if b enable verify set item image h child 2 2 else verify set item image h child 6 6 move on to the next item h child get next item h child tvgn next reset the redraw flag set redraw true return true ctreeoptionsctrl setradiobutton hitem isradiobutton hitem hparent getnextitem hitem tvgn_parent isgroup hparent hchild getnextitem hparent tvgn_child setredraw hchild isradiobutton hchild hchild hitem bsuccess setitemimage hchild bsuccess benable getradiobuttonenable hchild benable benable setitemimage hchild setitemimage hchild hchild getnextitem hchild tvgn_next setredraw bool c tree options ctrl get radio button htreeitem h parent int n index htreeitem h check item const assert is group h parent parent item must be a group item iterate through the child items and turn on the specified one and turn off all the other ones htreeitem h child get next item h parent tvgn child assert h child must have some child items find the checked item n index 0 bool b found false while b found if is radio button h child handle multiple groups n index 0 bool b success get radio button h child b found assert b success move on to the next sibling if not found if b found h child get next item h child tvgn next assert h child n index else h check item h child break this group is done return true ctreeoptionsctrl getradiobutton hparent nindex hcheckitem isgroup hparent hchild getnextitem hparent tvgn_child hchild nindex bfound bfound isradiobutton hchild nindex bsuccess getradiobutton hchild bfound bsuccess bfound hchild getnextitem hchild tvgn_next hchild nindex hcheckitem hchild bool c tree options ctrl get radio button htreeitem h item bool b check const assert is radio button h item must be a radio item to check it int n image int n selected image bool b success get item image h item n image n selected image assert b success b check n image 3 n image 7 return b success ctreeoptionsctrl getradiobutton hitem bcheck isradiobutton hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess bcheck nimage nimage bsuccess bool c tree options ctrl set group enable htreeitem h item bool b enable allows you to quickly enable disable all the items in a group assert is group h item must be group item iterate through the child items and enable disable all the items htreeitem h child get next item h item tvgn child turn of redraw to q all the changes we re going to make here set redraw false while h child if is radio button h child int n image int n selected image verify get item image h child n image n selected image bool b check n image 3 n image 7 if b check if b enable verify set item image h child 3 3 else verify set item image h child 7 7 else if b enable verify set item image h child 2 2 else verify set item image h child 6 6 else if is check box h child verify set check box enable h child b enable else assert false move onto the next child h child get next item h child tvgn next reset the redraw flag set redraw true return true ctreeoptionsctrl setgroupenable hitem benable isgroup hitem hchild getnextitem hitem tvgn_child setredraw hchild isradiobutton hchild nimage nselectedimage getitemimage hchild nimage nselectedimage bcheck nimage nimage bcheck benable setitemimage hchild setitemimage hchild benable setitemimage hchild setitemimage hchild ischeckbox hchild setcheckboxenable hchild benable hchild getnextitem hchild tvgn_next setredraw bool c tree options ctrl set check box enable htreeitem h item bool b enable assert is check box h item must be a check box bool b success false if b enable bool b check verify get check box h item b check bool b semi verify get semi check box h item b semi if b check if b semi b success set item image h item 8 8 else b success set item image h item 1 1 else b success set item image h item 0 0 else bool b check verify get check box h item b check bool b semi verify get semi check box h item b semi if b check if b semi b success set item image h item 9 9 else b success set item image h item 5 5 else b success set item image h item 4 4 return b success ctreeoptionsctrl setcheckboxenable hitem benable ischeckbox hitem bsuccess benable bcheck getcheckbox hitem bcheck bsemi getsemicheckbox hitem bsemi bcheck bsemi bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess setitemimage hitem bcheck getcheckbox hitem bcheck bsemi getsemicheckbox hitem bsemi bcheck bsemi bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess bool c tree options ctrl set radio button enable htreeitem h item bool b enable assert is radio button h item must be a radio button bool b success false if b enable bool b check verify get radio button h item b check if b check b success set item image h item 3 3 else b success set item image h item 2 2 else bool b check verify get radio button h item b check if b check b success set item image h item 7 7 else b success set item image h item 6 6 return b success ctreeoptionsctrl setradiobuttonenable hitem benable isradiobutton hitem bsuccess benable bcheck getradiobutton hitem bcheck bcheck bsuccess setitemimage hitem bsuccess setitemimage hitem bcheck getradiobutton hitem bcheck bcheck bsuccess setitemimage hitem bsuccess setitemimage hitem bsuccess bool c tree options ctrl get radio button enable htreeitem h item bool b enable const assert is radio button h item must be a radio button int n image int n selected image bool b success get item image h item n image n selected image assert b success b enable n image 2 n image 3 return b success ctreeoptionsctrl getradiobuttonenable hitem benable isradiobutton hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess benable nimage nimage bsuccess bool c tree options ctrl get check box enable htreeitem h item bool b enable const assert is check box h item must be a check box int n image int n selected image bool b success get item image h item n image n selected image assert b success b enable n image 0 n image 1 n image 8 return b success ctreeoptionsctrl getcheckboxenable hitem benable ischeckbox hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess benable nimage nimage nimage bsuccess bool c tree options ctrl add combo box htreeitem h item c runtime class p runtime class dword dw item data assert p runtime class delete the old item data in the item if there is one already c tree options item data p old item data c tree options item data get item data h item delete p old item data a pointer to the runtime class is stored in the item data which itself is an internal structure we maintain per tree item c tree options item data p item data new c tree options item data p item data m dwitemdata dw item data p item data m pruntimeclass1 p runtime class p item data m type c tree options item data combo box return set item data h item dword p item data ctreeoptionsctrl addcombobox hitem cruntimeclass pruntimeclass dwitemdata pruntimeclass ctreeoptionsitemdata polditemdata ctreeoptionsitemdata getitemdata hitem polditemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata pitemdata m_dwitemdata dwitemdata pitemdata m_pruntimeclass1 pruntimeclass pitemdata m_type ctreeoptionsitemdata combobox setitemdata hitem pitemdata c string c tree options ctrl get combo text htreeitem h item const c string s text get item text h item int n separator s text find m sseparator c string s combo text if n separator 1 s combo text s text right s text get length n separator m sseparator get length return s combo text cstring ctreeoptionsctrl getcombotext hitem cstring stext getitemtext hitem nseparator stext m_sseparator cstring scombotext nseparator scombotext stext stext getlength nseparator m_sseparator getlength scombotext void c tree options ctrl set combo text htreeitem h item const c string s combo text c string s text get item text h item int n separator s text find m sseparator if n separator 1 s text m sseparator s text s combo text else s text s text left n separator m sseparator get length s text s combo text set item text h item s text ctreeoptionsctrl setcombotext hitem cstring scombotext cstring stext getitemtext hitem nseparator stext m_sseparator nseparator stext m_sseparator stext scombotext stext stext nseparator m_sseparator getlength stext scombotext setitemtext hitem stext bool c tree options ctrl add edit box htreeitem h item c runtime class p runtime class edit ctrl dword dw item data just call the combo box version as currently there is no difference bool b success add combo box h item p runtime class edit ctrl dw item data update the type in the item data c tree options item data p item data c tree options item data get item data h item assert p item data p item data m type c tree options item data edit box return b success ctreeoptionsctrl addeditbox hitem cruntimeclass pruntimeclasseditctrl dwitemdata bsuccess addcombobox hitem pruntimeclasseditctrl dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata editbox bsuccess bool c tree options ctrl add edit box htreeitem h item c runtime class p runtime class edit ctrl c runtime class p runtime class spin ctrl dword dw item data add the edit box bool b success add edit box h item p runtime class edit ctrl dw item data add the spin ctrl c tree options item data p item data c tree options item data get item data h item assert p item data assert p item data m pruntimeclass1 assert p item data m pruntimeclass2 null assert p runtime class spin ctrl p item data m pruntimeclass2 p runtime class spin ctrl p item data m type c tree options item data spin p item data m dwitemdata dw item data return b success ctreeoptionsctrl addeditbox hitem cruntimeclass pruntimeclasseditctrl cruntimeclass pruntimeclassspinctrl dwitemdata bsuccess addeditbox hitem pruntimeclasseditctrl dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_pruntimeclass1 pitemdata m_pruntimeclass2 pruntimeclassspinctrl pitemdata m_pruntimeclass2 pruntimeclassspinctrl pitemdata m_type ctreeoptionsitemdata pitemdata m_dwitemdata dwitemdata bsuccess c string c tree options ctrl get edit text htreeitem h item const just call the combo box version as currently there is no difference return get combo text h item cstring ctreeoptionsctrl getedittext hitem getcombotext hitem void c tree options ctrl set edit text htreeitem h item const c string s edit text just call the combo box version as currently there is no difference set combo text h item s edit text ctreeoptionsctrl setedittext hitem cstring sedittext setcombotext hitem sedittext bool c tree options ctrl add file edit box htreeitem h item c runtime class p runtime class edit ctrl c runtime class p runtime class button dword dw item data add the edit box bool b success add edit box h item p runtime class edit ctrl dw item data add the browse button c tree options item data p item data c tree options item data get item data h item assert p item data assert p item data m pruntimeclass1 assert p item data m pruntimeclass2 null assert p runtime class button p item data m pruntimeclass2 p runtime class button p item data m type c tree options item data file browser return b success ctreeoptionsctrl addfileeditbox hitem cruntimeclass pruntimeclasseditctrl cruntimeclass pruntimeclassbutton dwitemdata bsuccess addeditbox hitem pruntimeclasseditctrl dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_pruntimeclass1 pitemdata m_pruntimeclass2 pruntimeclassbutton pitemdata m_pruntimeclass2 pruntimeclassbutton pitemdata m_type ctreeoptionsitemdata filebrowser bsuccess c string c tree options ctrl get file edit text htreeitem h item const just call the edit box version as currently there is no difference return get edit text h item cstring ctreeoptionsctrl getfileedittext hitem getedittext hitem void c tree options ctrl set file edit text htreeitem h item const c string s edit text just call the edit box version as currently there is no difference set edit text h item s edit text ctreeoptionsctrl setfileedittext hitem cstring sedittext setedittext hitem sedittext bool c tree options ctrl add folder edit box htreeitem h item c runtime class p runtime class edit ctrl c runtime class p runtime class button dword dw item data let the file edit box code do all the work bool b success add file edit box h item p runtime class edit ctrl p runtime class button dw item data setup the correct edit type in the item data c tree options item data p item data c tree options item data get item data h item p item data m type c tree options item data folder browser return b success ctreeoptionsctrl addfoldereditbox hitem cruntimeclass pruntimeclasseditctrl cruntimeclass pruntimeclassbutton dwitemdata bsuccess addfileeditbox hitem pruntimeclasseditctrl pruntimeclassbutton dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata m_type ctreeoptionsitemdata folderbrowser bsuccess c string c tree options ctrl get folder edit text htreeitem h item const just call the edit box version as currently there is no difference return get edit text h item cstring ctreeoptionsctrl getfolderedittext hitem getedittext hitem void c tree options ctrl set folder edit text htreeitem h item const c string s edit text just call the edit box version as currently there is no difference set edit text h item s edit text ctreeoptionsctrl setfolderedittext hitem cstring sedittext setedittext hitem sedittext bool c tree options ctrl add color selector htreeitem h item c runtime class p runtime class button dword dw item data bool b draw color for icon add the browse button as the primary control bool b success add edit box h item p runtime class button dw item data setup the browser type c tree options item data p item data c tree options item data get item data h item assert p item data p item data m type c tree options item data color browser p item data m bdrawcolorforicon b draw color for icon return b success ctreeoptionsctrl addcolorselector hitem cruntimeclass pruntimeclassbutton dwitemdata bdrawcolorforicon bsuccess addeditbox hitem pruntimeclassbutton dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata colorbrowser pitemdata m_bdrawcolorforicon bdrawcolorforicon bsuccess colorref c tree options ctrl get color htreeitem h item const c tree options item data p item data c tree options item data get item data h item assert p item data return p item data m color ctreeoptionsctrl getcolor hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_color void c tree options ctrl set color htreeitem h item colorref color c tree options item data p item data c tree options item data get item data h item assert p item data p item data m color color also update the text while we are at it c string s color s color format t 02x 02x 02x getr value color getg value color getb value color s color make upper set edit text h item s color ctreeoptionsctrl setcolor hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_color cstring scolor scolor _t getrvalue getgvalue getbvalue scolor makeupper setedittext hitem scolor bool c tree options ctrl add font selector htreeitem h item c runtime class p runtime class button dword dw item data add the browse button as the primary control bool b success add edit box h item p runtime class button dw item data setup the browser type c tree options item data p item data c tree options item data get item data h item assert p item data p item data m type c tree options item data font browser return b success ctreeoptionsctrl addfontselector hitem cruntimeclass pruntimeclassbutton dwitemdata bsuccess addeditbox hitem pruntimeclassbutton dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata fontbrowser bsuccess void c tree options ctrl get font item htreeitem h item logfont p log font const assert p log font c tree options item data p item data c tree options item data get item data h item assert p item data copy memory p log font p item data m font sizeof logfont ctreeoptionsctrl getfontitem hitem plogfont plogfont ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata copymemory plogfont pitemdata m_font void c tree options ctrl set font item htreeitem h item const logfont p log font assert p log font c tree options item data p item data c tree options item data get item data h item assert p item data copy memory p item data m font p log font sizeof logfont also update the text while we are at it set edit text h item p log font lf face name ctreeoptionsctrl setfontitem hitem plogfont plogfont ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata copymemory pitemdata m_font plogfont setedittext hitem plogfont lffacename bool c tree options ctrl add date time htreeitem h item c runtime class p runtime class date time dword dw item data add the date time control as the primary control bool b success add combo box h item p runtime class date time dw item data setup the item type c tree options item data p item data c tree options item data get item data h item assert p item data p item data m type c tree options item data date time ctrl return b success ctreeoptionsctrl adddatetime hitem cruntimeclass pruntimeclassdatetime dwitemdata bsuccess addcombobox hitem pruntimeclassdatetime dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata datetimectrl bsuccess void c tree options ctrl get date time htreeitem h item systemtime st const c tree options item data p item data c tree options item data get item data h item assert p item data copy memory st p item data m datetime sizeof systemtime ctreeoptionsctrl getdatetime hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata copymemory pitemdata m_datetime void c tree options ctrl set date time htreeitem h item const systemtime st c tree options item data p item data c tree options item data get item data h item assert p item data copy memory p item data m datetime st sizeof systemtime also update the text while we are at it c tree options date ctrl p temp date time c tree options date ctrl p item data m pruntimeclass1 create object assert p temp date time assert p temp date time is kind of runtime class c tree options date ctrl your class must be derived from c tree options date ctrl c string s date time p temp date time get display text st set edit text h item s date time delete p temp date time ctreeoptionsctrl setdatetime hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata copymemory pitemdata m_datetime ctreeoptionsdatectrl ptempdatetime ctreeoptionsdatectrl pitemdata m_pruntimeclass1 createobject ptempdatetime ptempdatetime iskindof runtime_class ctreeoptionsdatectrl ctreeoptionsdatectrl cstring sdatetime ptempdatetime getdisplaytext setedittext hitem sdatetime ptempdatetime bool c tree options ctrl addip address htreeitem h item c runtime class p runtime class date time dword dw item data add the date time control as the primary control bool b success add combo box h item p runtime class date time dw item data setup the item type c tree options item data p item data c tree options item data get item data h item assert p item data p item data m type c tree options item data ip address ctrl return b success ctreeoptionsctrl addipaddress hitem cruntimeclass pruntimeclassdatetime dwitemdata bsuccess addcombobox hitem pruntimeclassdatetime dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata ipaddressctrl bsuccess dword c tree options ctrl getip address htreeitem h item const c tree options item data p item data c tree options item data get item data h item assert p item data return p item data m dwipaddress ctreeoptionsctrl getipaddress hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwipaddress void c tree options ctrl setip address htreeitem h item dword dw address c tree options item data p item data c tree options item data get item data h item assert p item data p item data m dwipaddress dw address also update the text while we are at it c tree optionsip address ctrl p tempip address c tree optionsip address ctrl p item data m pruntimeclass1 create object assert p tempip address assert p tempip address is kind of runtime class c tree optionsip address ctrl your class must be derived from c tree optionsip address ctrl c string sip address p tempip address get display text dw address set edit text h item sip address delete p tempip address ctreeoptionsctrl setipaddress hitem dwaddress ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwipaddress dwaddress ctreeoptionsipaddressctrl ptempipaddress ctreeoptionsipaddressctrl pitemdata m_pruntimeclass1 createobject ptempipaddress ptempipaddress iskindof runtime_class ctreeoptionsipaddressctrl ctreeoptionsipaddressctrl cstring sipaddress ptempipaddress getdisplaytext dwaddress setedittext hitem sipaddress ptempipaddress bool c tree options ctrl add opaque htreeitem h item c runtime class p runtime class1 c runtime class p runtime class2 dword dw item data add the first class bool b success add combo box h item p runtime class1 dw item data add the second class c tree options item data p item data c tree options item data get item data h item assert p item data assert p item data m pruntimeclass1 assert p item data m pruntimeclass2 null p item data m pruntimeclass2 p runtime class2 setup the browser type p item data m type c tree options item data opaque browser return b success ctreeoptionsctrl addopaque hitem cruntimeclass pruntimeclass1 cruntimeclass pruntimeclass2 dwitemdata bsuccess addcombobox hitem pruntimeclass1 dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_pruntimeclass1 pitemdata m_pruntimeclass2 pitemdata m_pruntimeclass2 pruntimeclass2 pitemdata m_type ctreeoptionsitemdata opaquebrowser bsuccess dword c tree options ctrl get opaque htreeitem h item const c tree options item data p item data c tree options item data get item data h item assert p item data return p item data m dwitemdata ctreeoptionsctrl getopaque hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwitemdata void c tree options ctrl set opaque htreeitem h item dword dw item data c tree options item data p item data c tree options item data get item data h item assert p item data p item data m dwitemdata dw item data ctreeoptionsctrl setopaque hitem dwitemdata ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_dwitemdata dwitemdata void c tree options ctrl on create image list loadup the image list verify m iltree create m nilid 16 1 rgb 255 0 255 ctreeoptionsctrl oncreateimagelist m_iltree m_nilid htreeitem c tree options ctrl copy item htreeitem h item htreeitem hti new parent htreeitem hti after get the details of the item to copy tv insertstruct tvstruct tvstruct item h item h item tvstruct item mask tvif children tvif handle tvif image tvif selectedimage tvif param get item tvstruct item c string s text get item text h item tvstruct item cch text max s text get length tvstruct item psz text s text get buffer tvstruct item cch text max if tvstruct item l param tvstruct item l param lparam new c tree options item data c tree options item data tvstruct item l param insert the item at the proper location tvstruct h parent hti new parent tvstruct h insert after hti after tvstruct item mask tvif text htreeitem h new item insert item tvstruct don t forget to release the c string buffer s text release buffer return h new item ctreeoptionsctrl copyitem hitem htinewparent htiafter tv_insertstruct hitem hitem tvif_children tvif_handle tvif_image tvif_selectedimage tvif_param getitem cstring stext getitemtext hitem cchtextmax stext getlength psztext stext getbuffer cchtextmax lparam lparam ctreeoptionsitemdata ctreeoptionsitemdata lparam hparent htinewparent hinsertafter htiafter tvif_text hnewitem insertitem cstring stext releasebuffer hnewitem htreeitem c tree options ctrl copy branch htreeitem hti branch htreeitem hti new parent htreeitem hti after htreeitem h new item copy item hti branch hti new parent hti after htreeitem h child get child item hti branch while h child null recursively transfer all the items copy branch h child h new item h child get next sibling item h child return h new item ctreeoptionsctrl copybranch htibranch htinewparent htiafter hnewitem copyitem htibranch htinewparent htiafter hchild getchilditem htibranch hchild copybranch hchild hnewitem hchild getnextsiblingitem hchild hnewitem void c tree options ctrl destroy old child control if m pcombo m pcombo destroy window delete m pcombo m pcombo null if m pedit m pedit destroy window delete m pedit m pedit null if m pspin m pspin destroy window delete m pspin m pspin null if m pbutton m pbutton destroy window delete m pbutton m pbutton null if m pdatetime m pdatetime destroy window delete m pdatetime m pdatetime null if m pipaddress m pipaddress destroy window delete m pipaddress m pipaddress null free up the font object we have been using m font delete object m hcontrolitem null ctreeoptionsctrl destroyoldchildcontrol m_pcombo m_pcombo destroywindow m_pcombo m_pcombo m_pedit m_pedit destroywindow m_pedit m_pedit m_pspin m_pspin destroywindow m_pspin m_pspin m_pbutton m_pbutton destroywindow m_pbutton m_pbutton m_pdatetime m_pdatetime destroywindow m_pdatetime m_pdatetime m_pipaddress m_pipaddress destroywindow m_pipaddress m_pipaddress m_font deleteobject m_hcontrolitem void c tree options ctrl remove child control text htreeitem h item c string s text get item text h item int n separator s text find m sseparator if n separator 1 s text s text left n separator set item text h item s text ctreeoptionsctrl removechildcontroltext hitem cstring stext getitemtext hitem nseparator stext m_sseparator nseparator stext stext nseparator setitemtext hitem stext void c tree options ctrl create new child control htreeitem h item assert h item m hcontrolitem h item c tree options item data p item data c tree options item data get item data h item assert p item data make a copy of the current font being used by the control assert m font m hobject null c font p font get font logfont lf p font get log font lf verify m font create font indirect lf allocate the main control assert p item data m pruntimeclass1 c string s combo text c string s edit text if p item data m pruntimeclass1 is derived from runtime class c tree options combo get the current text in the combo item s combo text get combo text h item now that we have the current text remove it from the tree control text remove child control text h item create the new combo box m pcombo c tree options combo p item data m pruntimeclass1 create object assert m pcombo assert m pcombo is kind of runtime class c tree options combo your class must be derived from c tree options combo m pcombo set tree buddy this m pcombo set tree item h item else if p item data m pruntimeclass1 is derived from runtime class c tree options edit get the current text in the edit box item s edit text get edit text h item now that we have the current text remove it from the tree control text remove child control text h item create the new edit box m pedit c tree options edit p item data m pruntimeclass1 create object assert m pedit assert m pedit is kind of runtime class c tree options edit your class must be derived from c tree options edit m pedit set tree buddy this m pedit set tree item h item else if p item data m pruntimeclass1 is derived from runtime class c tree options date ctrl get the current text in the edit box item s edit text get edit text h item now that we have the current text remove it from the tree control text remove child control text h item create the new edit box m pdatetime c tree options date ctrl p item data m pruntimeclass1 create object assert m pdatetime assert m pdatetime is kind of runtime class c tree options date ctrl your class must be derived from c tree options date ctrl m pdatetime set tree buddy this m pdatetime set tree item h item else if p item data m pruntimeclass1 is derived from runtime class c tree optionsip address ctrl get the current text in the edit box item s edit text get edit text h item now that we have the current text remove it from the tree control text remove child control text h item create the new edit box m pipaddress c tree optionsip address ctrl p item data m pruntimeclass1 create object assert m pipaddress assert m pipaddress is kind of runtime class c tree optionsip address ctrl your class must be derived from c tree optionsip address ctrl m pipaddress set tree buddy this m pipaddress set tree item h item else if p item data m pruntimeclass1 is derived from runtime class c tree options browse button work out the rects for item c rect r text get item rect h item r text true c rect r line get item rect h item r line false create the new static m pbutton c tree options browse button p item data m pruntimeclass1 create object assert m pbutton assert m pbutton is kind of runtime class c tree options browse button your class must be derived from c tree options static m pbutton set tree buddy this m pbutton set tree item h item if p item data m type c tree options item data color browser get the current color from the control and let the button know about it colorref color get color h item m pbutton set color color else if p item data m type c tree options item data font browser logfont lf get font item h item lf m pbutton set font item lf else assert p item data m type c tree options item data opaque browser else assert false your class must be derived from one of the classes in the previous statements allocate the secondary control if p item data m pruntimeclass2 if p item data m pruntimeclass2 is derived from runtime class c tree options spin ctrl m pspin c tree options spin ctrl p item data m pruntimeclass2 create object assert m pspin assert m pspin is kind of runtime class c tree options spin ctrl your class must be derived from c tree options spin ctrl m pspin set tree buddy this m pspin set tree item h item else assert p item data m pruntimeclass2 is derived from runtime class c tree options browse button m pbutton c tree options browse button p item data m pruntimeclass2 create object assert m pbutton assert m pbutton is kind of runtime class c tree options browse button your class must be derived from c tree options browse button m pbutton set tree buddy this m pbutton set tree item h item update the rects for item c rect r text get item rect h item r text true c rect r line get item rect h item r line false c rect r r top r text top r left r text right 2 now create the main control assert p item data m pruntimeclass1 if p item data m pruntimeclass1 is derived from runtime class c tree options combo if m pbutton r right r line right m pbutton get width else r right r line right r bottom r top m pcombo get drop down height ask the combo box for the height to use m pcombo create m pcombo get window style r this tree options combobox id assert m pcombo get count you forget to add string items to the combo box in your on create message handler set the font the combo box should use based on the font in the tree control m pcombo set font m font also select the right text into the combo box dword dw combo style m pcombo get style bool b combo has edit dw combo style cbs dropdown dw combo style cbs simple 0 if dw combo style cbs dropdownlist cbs dropdownlist b combo has edit false if b combo has edit m pcombo set window text s combo text else m pcombo select string 1 s combo text auto select the control if configured to do so if m bautoselect m pcombo set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options edit if m pbutton r right r line right m pbutton get width else r right r line right r bottom r top m pedit get height r text height verify m pedit create ex ws ex clientedge t edit s edit text m pedit get window style r this tree options editbox id set the font the edit box should use based on the font in the tree control m pedit set font m font auto select the control if configured to do so if m bautoselect m pedit set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options date ctrl r right r line right r bottom r line bottom verify m pdatetime create m pdatetime get window style r this tree options datetimectrl id set the font the date time control should use based on the font in the list control m pdatetime set font m font set the value in the control m pdatetime set time p item data m datetime auto select the control if configured to do so if m bautoselect m pdatetime set focus else if p item data m pruntimeclass1 is derived from runtime class c tree optionsip address ctrl r right r line right r bottom r line bottom verify m pipaddress create m pipaddress get window style r this tree options ipaddressctrl id set the font the ip address control should use based on the font in the list control m pipaddress set font m font dword dw address getip address h item m pipaddress set address dw address auto select the control if configured to do so if m bautoselect m pipaddress set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options browse button create browse button p item data m pruntimeclass1 r line r text else assert false your class must be derived from one of the classes in the statements above actually create the secondary control if p item data m pruntimeclass2 if p item data m pruntimeclass2 is derived from runtime class c tree options spin ctrl create spin ctrl p item data m pruntimeclass2 r line r text r else assert p item data m pruntimeclass2 is derived from runtime class c tree options browse button create browse button p item data m pruntimeclass2 r line r text if m pedit m pedit set button buddy m pbutton else assert m pcombo m pcombo set button buddy m pbutton ctreeoptionsctrl createnewchildcontrol hitem hitem m_hcontrolitem hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata m_font m_hobject cfont pfont getfont pfont getlogfont m_font createfontindirect pitemdata m_pruntimeclass1 cstring scombotext cstring sedittext pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionscombo scombotext getcombotext hitem removechildcontroltext hitem m_pcombo ctreeoptionscombo pitemdata m_pruntimeclass1 createobject m_pcombo m_pcombo iskindof runtime_class ctreeoptionscombo ctreeoptionscombo m_pcombo settreebuddy m_pcombo settreeitem hitem pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsedit sedittext getedittext hitem removechildcontroltext hitem m_pedit ctreeoptionsedit pitemdata m_pruntimeclass1 createobject m_pedit m_pedit iskindof runtime_class ctreeoptionsedit ctreeoptionsedit m_pedit settreebuddy m_pedit settreeitem hitem pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsdatectrl sedittext getedittext hitem removechildcontroltext hitem m_pdatetime ctreeoptionsdatectrl pitemdata m_pruntimeclass1 createobject m_pdatetime m_pdatetime iskindof runtime_class ctreeoptionsdatectrl ctreeoptionsdatectrl m_pdatetime settreebuddy m_pdatetime settreeitem hitem pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsipaddressctrl sedittext getedittext hitem removechildcontroltext hitem m_pipaddress ctreeoptionsipaddressctrl pitemdata m_pruntimeclass1 createobject m_pipaddress m_pipaddress iskindof runtime_class ctreeoptionsipaddressctrl ctreeoptionsipaddressctrl m_pipaddress settreebuddy m_pipaddress settreeitem hitem pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsbrowsebutton crect rtext getitemrect hitem rtext crect rline getitemrect hitem rline m_pbutton ctreeoptionsbrowsebutton pitemdata m_pruntimeclass1 createobject m_pbutton m_pbutton iskindof runtime_class ctreeoptionsbrowsebutton ctreeoptionsstatic m_pbutton settreebuddy m_pbutton settreeitem hitem pitemdata m_type ctreeoptionsitemdata colorbrowser getcolor hitem m_pbutton setcolor pitemdata m_type ctreeoptionsitemdata fontbrowser getfontitem hitem m_pbutton setfontitem pitemdata m_type ctreeoptionsitemdata opaquebrowser pitemdata m_pruntimeclass2 pitemdata m_pruntimeclass2 isderivedfrom runtime_class ctreeoptionsspinctrl m_pspin ctreeoptionsspinctrl pitemdata m_pruntimeclass2 createobject m_pspin m_pspin iskindof runtime_class ctreeoptionsspinctrl ctreeoptionsspinctrl m_pspin settreebuddy m_pspin settreeitem hitem pitemdata m_pruntimeclass2 isderivedfrom runtime_class ctreeoptionsbrowsebutton m_pbutton ctreeoptionsbrowsebutton pitemdata m_pruntimeclass2 createobject m_pbutton m_pbutton iskindof runtime_class ctreeoptionsbrowsebutton ctreeoptionsbrowsebutton m_pbutton settreebuddy m_pbutton settreeitem hitem crect rtext getitemrect hitem rtext crect rline getitemrect hitem rline crect rtext rtext pitemdata m_pruntimeclass1 pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionscombo m_pbutton rline m_pbutton getwidth rline m_pcombo getdropdownheight m_pcombo m_pcombo getwindowstyle tree_options_combobox_id m_pcombo getcount oncreate m_pcombo setfont m_font dwcombostyle m_pcombo getstyle bcombohasedit dwcombostyle cbs_dropdown dwcombostyle cbs_simple dwcombostyle cbs_dropdownlist cbs_dropdownlist bcombohasedit bcombohasedit m_pcombo setwindowtext scombotext m_pcombo selectstring scombotext m_bautoselect m_pcombo setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsedit m_pbutton rline m_pbutton getwidth rline m_pedit getheight rtext m_pedit createex ws_ex_clientedge _t sedittext m_pedit getwindowstyle tree_options_editbox_id m_pedit setfont m_font m_bautoselect m_pedit setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsdatectrl rline rline m_pdatetime m_pdatetime getwindowstyle tree_options_datetimectrl_id m_pdatetime setfont m_font m_pdatetime settime pitemdata m_datetime m_bautoselect m_pdatetime setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsipaddressctrl rline rline m_pipaddress m_pipaddress getwindowstyle tree_options_ipaddressctrl_id m_pipaddress setfont m_font dwaddress getipaddress hitem m_pipaddress setaddress dwaddress m_bautoselect m_pipaddress setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsbrowsebutton createbrowsebutton pitemdata m_pruntimeclass1 rline rtext pitemdata m_pruntimeclass2 pitemdata m_pruntimeclass2 isderivedfrom runtime_class ctreeoptionsspinctrl createspinctrl pitemdata m_pruntimeclass2 rline rtext pitemdata m_pruntimeclass2 isderivedfrom runtime_class ctreeoptionsbrowsebutton createbrowsebutton pitemdata m_pruntimeclass2 rline rtext m_pedit m_pedit setbuttonbuddy m_pbutton m_pcombo m_pcombo setbuttonbuddy m_pbutton void c tree options ctrl create spin ctrl c runtime class p runtime class spin ctrl c rect r item c rect r text c rect r primary control assert p runtime class spin ctrl if p runtime class spin ctrl is derived from runtime class c tree options spin ctrl work out the rect this secondary control c rect r r top r primary control top r bottom r primary control bottom r left r primary control right r right r item right create the new spin control assert m pspin m pspin set edit buddy m pedit create the spin control verify m pspin create m pspin get window style r this tree options spinctrl id setup the buddy and the default range m pspin set buddy m pedit int n lower 0 int n upper 0 m pspin get default range n lower n upper m pspin set range short n lower short n upper set the font the edit box should use based on the font in the tree control m pspin set font m font else assert false your class must be derived from c tree options spin ctrl ctreeoptionsctrl createspinctrl cruntimeclass pruntimeclassspinctrl crect ritem crect rtext crect rprimarycontrol pruntimeclassspinctrl pruntimeclassspinctrl isderivedfrom runtime_class ctreeoptionsspinctrl crect rprimarycontrol rprimarycontrol rprimarycontrol ritem m_pspin m_pspin seteditbuddy m_pedit m_pspin m_pspin getwindowstyle tree_options_spinctrl_id m_pspin setbuddy m_pedit nlower nupper m_pspin getdefaultrange nlower nupper m_pspin setrange nlower nupper m_pspin setfont m_font ctreeoptionsspinctrl void c tree options ctrl create browse button c runtime class p runtime class browse button c rect r item c rect r text assert p runtime class browse button if p runtime class browse button is derived from runtime class c tree options browse button if m pedit work out the rect for the button c rect r edit m pedit get window rect r edit screen to client r edit c rect r r top r item top r bottom r edit bottom r right r item right r left r right m pbutton get width ask the browse button for the width to use create the new browse button assert m pbutton m pbutton set edit buddy m pedit verify m pbutton create m pbutton get caption m pbutton get window style r this tree options browsebuttonctrl id m pbutton set owner m pedit else if m pcombo work out the rect for the button c rect r combo m pcombo get window rect r combo screen to client r combo c rect r r top r item top r bottom r combo bottom r right r item right r left r right m pbutton get width ask the browse button for the width to use create the new browse button assert m pbutton m pbutton set combo buddy m pcombo verify m pbutton create m pbutton get caption m pbutton get window style r this tree options browsebuttonctrl id m pbutton set owner m pcombo else work out the rect for the button c rect r r top r text top r bottom r text bottom r right r item right r left r right m pbutton get width ask the browse button for the width to use create the browse button assert m pbutton verify m pbutton create m pbutton get caption m pbutton get window style r this tree options browsebuttonctrl id set the font the edit box should use based on the font in the tree control m pbutton set font m font else assert false your class must be derived from c tree options browse button ctreeoptionsctrl createbrowsebutton cruntimeclass pruntimeclassbrowsebutton crect ritem crect rtext pruntimeclassbrowsebutton pruntimeclassbrowsebutton isderivedfrom runtime_class ctreeoptionsbrowsebutton m_pedit crect redit m_pedit getwindowrect redit screentoclient redit crect ritem redit ritem m_pbutton getwidth m_pbutton m_pbutton seteditbuddy m_pedit m_pbutton m_pbutton getcaption m_pbutton getwindowstyle tree_options_browsebuttonctrl_id m_pbutton setowner m_pedit m_pcombo crect rcombo m_pcombo getwindowrect rcombo screentoclient rcombo crect ritem rcombo ritem m_pbutton getwidth m_pbutton m_pbutton setcombobuddy m_pcombo m_pbutton m_pbutton getcaption m_pbutton getwindowstyle tree_options_browsebuttonctrl_id m_pbutton setowner m_pcombo crect rtext rtext ritem m_pbutton getwidth m_pbutton m_pbutton m_pbutton getcaption m_pbutton getwindowstyle tree_options_browsebuttonctrl_id m_pbutton setfont m_font ctreeoptionsbrowsebutton void c tree options ctrl update tree control value from child control htreeitem h item if m pcombo c string s text m pcombo get window text s text set combo text m hcontrolitem s text else if m pedit c string s text m pedit get window text s text set edit text m hcontrolitem s text else if m pdatetime systemtime st1 if m pdatetime get time st1 gdt valid m pdatetime set date time st1 systemtime st2 m pdatetime get date time st2 set date time m hcontrolitem st2 set edit text m hcontrolitem m pdatetime get display text st2 else if m pipaddress dword dw address if m pipaddress get address dw address 4 setip address m hcontrolitem dw address set edit text m hcontrolitem m pipaddress get display text dw address else if m pbutton c tree options item data p item data c tree options item data get item data h item assert p item data if p item data m type c tree options item data color browser colorref color m pbutton get color set color m hcontrolitem color else if p item data m type c tree options item data font browser logfont lf get font item h item lf m pbutton set font item lf ctreeoptionsctrl updatetreecontrolvaluefromchildcontrol hitem m_pcombo cstring stext m_pcombo getwindowtext stext setcombotext m_hcontrolitem stext m_pedit cstring stext m_pedit getwindowtext stext setedittext m_hcontrolitem stext m_pdatetime m_pdatetime gettime gdt_valid m_pdatetime setdatetime m_pdatetime getdatetime setdatetime m_hcontrolitem setedittext m_hcontrolitem m_pdatetime getdisplaytext m_pipaddress dwaddress m_pipaddress getaddress dwaddress setipaddress m_hcontrolitem dwaddress setedittext m_hcontrolitem m_pipaddress getdisplaytext dwaddress m_pbutton ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata colorbrowser m_pbutton getcolor setcolor m_hcontrolitem pitemdata m_type ctreeoptionsitemdata fontbrowser getfontitem hitem m_pbutton setfontitem void c tree options ctrl handle child control losing focus clean up any controls currently open we used if we are losing focus to something else update tree control value from child control get selected item destroy old child control ctreeoptionsctrl handlechildcontrollosingfocus updatetreecontrolvaluefromchildcontrol getselecteditem destroyoldchildcontrol void c tree options ctrl handle check box htreeitem h item bool b check turn of redraw to q all the changes we re going to make here set redraw false toggle the state verify set check box h item b check if the item has children then iterate through them and for all items which are check boxes set their state to be the same as the parent htreeitem h child get next item h item tvgn child while h child if is check box h child set check box h child b check move on to the next item h child get next item h child tvgn next get the parent item and if it is a checkbox then iterate through all its children and if all the checkboxes are checked then also automatically check the parent if no checkboxes are checked then also automatically uncheck the parent htreeitem h parent get next item h item tvgn parent if h parent is check box h parent bool b no check boxes checked true bool b all check boxes checked true h child get next item h parent tvgn child while h child if is check box h child bool b this checked verify get check box h child b this checked b no check boxes checked b no check boxes checked b this checked b all check boxes checked b all check boxes checked b this checked move on to the next item h child get next item h child tvgn next if b no check boxes checked set check box h parent false else if b all check boxes checked set check box h parent false gets rid of the semi state set check box h parent true else bool b enable verify get check box enable h parent b enable set enabled semi check box h parent b enable reset the redraw flag set redraw true ctreeoptionsctrl handlecheckbox hitem bcheck setredraw setcheckbox hitem bcheck hchild getnextitem hitem tvgn_child hchild ischeckbox hchild setcheckbox hchild bcheck hchild getnextitem hchild tvgn_next hparent getnextitem hitem tvgn_parent hparent ischeckbox hparent bnocheckboxeschecked ballcheckboxeschecked hchild getnextitem hparent tvgn_child hchild ischeckbox hchild bthischecked getcheckbox hchild bthischecked bnocheckboxeschecked bnocheckboxeschecked bthischecked ballcheckboxeschecked ballcheckboxeschecked bthischecked hchild getnextitem hchild tvgn_next bnocheckboxeschecked setcheckbox hparent ballcheckboxeschecked setcheckbox hparent setcheckbox hparent benable getcheckboxenable hparent benable setenabledsemicheckbox hparent benable setredraw bool c tree options ctrl set enabled semi check box htreeitem h item bool b semi validate our parameters assert is check box h item must be a check box to check it if b semi return set item image h item 8 8 else return set item image h item 9 9 ctreeoptionsctrl setenabledsemicheckbox hitem bsemi ischeckbox hitem bsemi setitemimage hitem setitemimage hitem bool c tree options ctrl get semi check box htreeitem h item bool b semi const assert is check box h item must be a check box int n image int n selected image bool b success get item image h item n image n selected image assert b success b semi n image 8 n image 9 return b success ctreeoptionsctrl getsemicheckbox hitem bsemi ischeckbox hitem nimage nselectedimage bsuccess getitemimage hitem nimage nselectedimage bsuccess bsemi nimage nimage bsuccess int c tree options ctrl get indent postion htreeitem h item const uint u indent get indent int n ancestors 1 while h item h item get parent item h item n ancestors return n ancestors u indent ctreeoptionsctrl getindentpostion hitem uindent getindent nancestors hitem hitem getparentitem hitem nancestors nancestors uindent void c tree options ctrl mem delete all items htreeitem h parent htreeitem h item h parent while h item htreeitem h next item c tree ctrl get next item h item tvgn next if item has children h item mem delete all items get child item h item c tree options item data p item c tree options item data c tree ctrl get item data h item delete p item set item data h item 0 let the base class do its thing c tree ctrl delete item h item move on to the next item h item h next item ctreeoptionsctrl memdeleteallitems hparent hitem hparent hitem hnextitem ctreectrl getnextitem hitem tvgn_next itemhaschildren hitem memdeleteallitems getchilditem hitem ctreeoptionsitemdata pitem ctreeoptionsitemdata ctreectrl getitemdata hitem pitem setitemdata hitem ctreectrl deleteitem hitem hitem hnextitem void c tree options ctrl pre subclass window let the parent class do its thing c tree ctrl pre subclass window call the virtual function to setup the image list on create image list hook it up to the tree control set image list m iltree tvsil normal ctreeoptionsctrl presubclasswindow ctreectrl presubclasswindow oncreateimagelist setimagelist m_iltree tvsil_normal void c tree options ctrl onl button down uint n flags c point point uint u flags 0 htreeitem h item hit test point u flags if the mouse was over the label icon or to the left or right of the item bool b hit false if m btoggleovericononly b hit u flags tvht onitemicon else b hit u flags tvht onitem u flags tvht onitemindent u flags tvht onitemright if b hit if is check box h item bool b enable verify get check box enable h item b enable if b enable turn of redraw to q all the changes we re going to make here set redraw false toggle the state of check items bool b check verify get check box h item b check handle check box h item b check else if is radio button h item bool b enable verify get radio button enable h item b enable if b enable check the radio button if not already checked bool b check verify get radio button h item b check if b check verify set radio button h item pass on to the parent now that we that we have done our stuff c tree ctrl onl button down n flags point else pass on to the parent since we didn t handle it c tree ctrl onl button down n flags point ctreeoptionsctrl onlbuttondown nflags cpoint uflags hitem hittest uflags bhit m_btoggleovericononly bhit uflags tvht_onitemicon bhit uflags tvht_onitem uflags tvht_onitemindent uflags tvht_onitemright bhit ischeckbox hitem benable getcheckboxenable hitem benable benable setredraw bcheck getcheckbox hitem bcheck handlecheckbox hitem bcheck isradiobutton hitem benable getradiobuttonenable hitem benable benable bcheck getradiobutton hitem bcheck bcheck setradiobutton hitem ctreectrl onlbuttondown nflags ctreectrl onlbuttondown nflags void c tree options ctrl on char uint n char uint n rep cnt uint n flags if n char vk space htreeitem h item get selected item if the space key is hit and the item is a combo item then toggle the check value if is check box h item bool b enable verify get check box enable h item b enable if b enable turn of redraw to q all the changes we re going to make here set redraw false bool b check verify get check box h item b check handle check box h item b check else pass on to the parent since we didn t handle it c tree ctrl on char n char n rep cnt n flags else if is radio button h item if the item is a radio item then check it and uncheck all other items bool b enable verify get radio button enable h item b enable if b enable check the radio button if not already checked bool b check verify get radio button h item b check if b check verify set radio button h item else pass on to the parent since we didn t handle it c tree ctrl on char n char n rep cnt n flags else pass on to the parent since we didn t handle it c tree ctrl on char n char n rep cnt n flags else pass on to the parent since we didn t handle it c tree ctrl on char n char n rep cnt n flags ctreeoptionsctrl onchar nchar nrepcnt nflags nchar vk_space hitem getselecteditem ischeckbox hitem benable getcheckboxenable hitem benable benable setredraw bcheck getcheckbox hitem bcheck handlecheckbox hitem bcheck ctreectrl onchar nchar nrepcnt nflags isradiobutton hitem benable getradiobuttonenable hitem benable benable bcheck getradiobutton hitem bcheck bcheck setradiobutton hitem ctreectrl onchar nchar nrepcnt nflags ctreectrl onchar nchar nrepcnt nflags ctreectrl onchar nchar nrepcnt nflags void c tree options ctrl on destroy destroy the old combo or edit box if need be destroy old child control delete all the items ourselves rather than calling c tree ctrl delete all items clear let the parent class do its thing c tree ctrl on destroy ctreeoptionsctrl ondestroy destroyoldchildcontrol ctreectrl deleteallitems ctreectrl ondestroy void c tree options ctrl onv scroll uint nsb code uint n pos c scroll bar p scroll bar if p scroll bar p scroll bar is kind of runtime class c tree options spin ctrl clean up any controls currently open we used assuming it is a standard scroll message and not from one of our spin controls if m hcontrolitem update tree control value from child control m hcontrolitem destroy old child control let the parent class do its thing c tree ctrl onv scroll nsb code n pos p scroll bar ctreeoptionsctrl onvscroll nsbcode npos cscrollbar pscrollbar pscrollbar pscrollbar iskindof runtime_class ctreeoptionsspinctrl m_hcontrolitem updatetreecontrolvaluefromchildcontrol m_hcontrolitem destroyoldchildcontrol ctreectrl onvscroll nsbcode npos pscrollbar void c tree options ctrl onh scroll uint nsb code uint n pos c scroll bar p scroll bar clean up any controls currently open we used if m hcontrolitem update tree control value from child control m hcontrolitem destroy old child control let the parent class do its thing c tree ctrl onh scroll nsb code n pos p scroll bar ctreeoptionsctrl onhscroll nsbcode npos cscrollbar pscrollbar m_hcontrolitem updatetreecontrolvaluefromchildcontrol m_hcontrolitem destroyoldchildcontrol ctreectrl onhscroll nsbcode npos pscrollbar void c tree options ctrl on key down uint n char uint n rep cnt uint n flags if n char vk right htreeitem h item get selected item if get item data h item m hcontrolitem null if we have a children and vk right focus on it c tree options item data p item data c tree options item data get item data h item if p item data m pruntimeclass1 is derived from runtime class c tree options combo if m pcombo is window visible m pcombo set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options edit if m pedit is window visible m pedit set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options date ctrl if m pdatetime is window visible m pdatetime set focus else if p item data m pruntimeclass1 is derived from runtime class c tree optionsip address ctrl if m pipaddress is window visible m pipaddress set focus else if p item data m pruntimeclass1 is derived from runtime class c tree options browse button if m pbutton is window visible m pbutton set focus else pass on to the parent since we didn t handle it c tree ctrl on key down n char n rep cnt n flags else pass on to the parent since we didn t handle it c tree ctrl on key down n char n rep cnt n flags else pass on to the parent since we didn t handle it c tree ctrl on key down n char n rep cnt n flags ctreeoptionsctrl onkeydown nchar nrepcnt nflags nchar vk_right hitem getselecteditem getitemdata hitem m_hcontrolitem vk_right ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionscombo m_pcombo iswindowvisible m_pcombo setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsedit m_pedit iswindowvisible m_pedit setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsdatectrl m_pdatetime iswindowvisible m_pdatetime setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsipaddressctrl m_pipaddress iswindowvisible m_pipaddress setfocus pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsbrowsebutton m_pbutton iswindowvisible m_pbutton setfocus ctreectrl onkeydown nchar nrepcnt nflags ctreectrl onkeydown nchar nrepcnt nflags ctreectrl onkeydown nchar nrepcnt nflags void c tree options ctrl on kill focus c wnd p new wnd clean up any controls currently open if we are losing focus to something else bool b foreign wnd m hcontrolitem p new wnd m pcombo p new wnd m pedit p new wnd m pdatetime p new wnd m pipaddress p new wnd m pbutton if b foreign wnd m pcombo b foreign wnd m pcombo is related wnd p new wnd if b foreign wnd m pdatetime b foreign wnd m pdatetime is related wnd p new wnd if b foreign wnd m pipaddress b foreign wnd m pipaddress is related wnd p new wnd if b foreign wnd update tree control value from child control get selected item destroy old child control let the parent class do its thing c tree ctrl on kill focus p new wnd ctreeoptionsctrl onkillfocus cwnd pnewwnd bforeignwnd m_hcontrolitem pnewwnd m_pcombo pnewwnd m_pedit pnewwnd m_pdatetime pnewwnd m_pipaddress pnewwnd m_pbutton bforeignwnd m_pcombo bforeignwnd m_pcombo isrelatedwnd pnewwnd bforeignwnd m_pdatetime bforeignwnd m_pdatetime isrelatedwnd pnewwnd bforeignwnd m_pipaddress bforeignwnd m_pipaddress isrelatedwnd pnewwnd bforeignwnd updatetreecontrolvaluefromchildcontrol getselecteditem destroyoldchildcontrol ctreectrl onkillfocus pnewwnd bool c tree options ctrl on click nmhdr pnmhdr lresult p result if the mouse was over the label or icon and the item is a combo box or edit box and editing is currently not active then create the new control uint u flags 0 c point point get current message pt screen to client point htreeitem h item hit test point u flags if h item c tree options item data p item data c tree options item data get item data h item if u flags tvht onitem p item data p item data m pruntimeclass1 m hcontrolitem null create new child control h item auto select the control if configured to do so if m bautoselect post message wm toc setfocus to child p result 0 return false ctreeoptionsctrl onclick presult uflags cpoint getcurrentmessage screentoclient hitem hittest uflags hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem uflags tvht_onitem pitemdata pitemdata m_pruntimeclass1 m_hcontrolitem createnewchildcontrol hitem m_bautoselect postmessage wm_toc_setfocus_to_child presult bool c tree options ctrl on selchanged nmhdr pnmhdr lresult p result nm treeview pnm tree view nm treeview pnmhdr if m bbeingcleared destroy the old combo or edit box if need be if m hcontrolitem update tree control value from child control m hcontrolitem destroy old child control m hcontrolitem null create the new control if need be if pnm tree view item new h item null c tree options item data p item data c tree options item data get item data pnm tree view item new h item if p item data p item data m pruntimeclass1 create new child control pnm tree view item new h item p result 0 return false ctreeoptionsctrl onselchanged presult nm_treeview pnmtreeview nm_treeview m_bbeingcleared m_hcontrolitem updatetreecontrolvaluefromchildcontrol m_hcontrolitem destroyoldchildcontrol m_hcontrolitem pnmtreeview itemnew hitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata pnmtreeview itemnew hitem pitemdata pitemdata m_pruntimeclass1 createnewchildcontrol pnmtreeview itemnew hitem presult bool c tree options ctrl on delete item nmhdr pnmhdr lresult p result nm treeview pnm tree view nm treeview pnmhdr p result 0 free up the memory we had allocated in the item data if needed c tree options item data p item data c tree options item data get item data pnm tree view item old h item delete p item data return false ctreeoptionsctrl ondeleteitem presult nm_treeview pnmtreeview nm_treeview presult ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata pnmtreeview itemold hitem pitemdata bool c tree options ctrl on mouse wheel uint n flags short z delta c point pt clean up any controls currently open we used if m hcontrolitem update tree control value from child control m hcontrolitem destroy old child control let the parent class do its thing return c tree ctrl on mouse wheel n flags z delta pt ctreeoptionsctrl onmousewheel nflags zdelta cpoint m_hcontrolitem updatetreecontrolvaluefromchildcontrol m_hcontrolitem destroyoldchildcontrol ctreectrl onmousewheel nflags zdelta lresult c tree options ctrl on set focus to child wparam w param lparam l param if m pcombo m pcombo set focus else if m pedit m pedit set focus else if m pdatetime m pdatetime set focus else if m pipaddress m pipaddress set focus return 0l ctreeoptionsctrl onsetfocustochild wparam lparam m_pcombo m_pcombo setfocus m_pedit m_pedit setfocus m_pdatetime m_pdatetime setfocus m_pipaddress m_pipaddress setfocus lresult c tree options ctrl on reposition child wparam w param lparam l param htreeitem h item get selected item if h item update tree control value from child control h item destroy old child control create new child control h item return 0l ctreeoptionsctrl onrepositionchild wparam lparam hitem getselecteditem hitem updatetreecontrolvaluefromchildcontrol hitem destroyoldchildcontrol createnewchildcontrol hitem bool c tree options ctrl on custom draw nmhdr pnmhdr lresult p result nmtvcustomdraw p custom draw nmtvcustomdraw pnmhdr switch p custom draw nmcd dw draw stage case cdds prepaint p result cdrf notifyitemdraw tell the control that we are interested in item notifications break case cdds itemprepaint just let me know about post painting p result cdrf notifypostpaint break case cdds itempostpaint htreeitem h item htreeitem p custom draw nmcd dw item spec bool b draw color false c tree options item data p item data c tree options item data get item data h item if p item data p item data m type c tree options item data color browser p item data m bdrawcolorforicon b draw color true if b draw color draw the icon of the tree view item using the specified color cdc dc dc attach p custom draw nmcd hdc c rect r r top p custom draw nmcd rc top r bottom p custom draw nmcd rc bottom r left p custom draw nmcd rc left allow for the indent r left get indent postion h item r right r left 16 dc fill solid rect r get color h item dc detach p result cdrf dodefault break default break return true allow the message to be reflected again ctreeoptionsctrl oncustomdraw presult pcustomdraw pcustomdraw dwdrawstage cdds_prepaint presult cdrf_notifyitemdraw cdds_itemprepaint presult cdrf_notifypostpaint cdds_itempostpaint hitem pcustomdraw dwitemspec bdrawcolor ctreeoptionsitemdata pitemdata ctreeoptionsitemdata getitemdata hitem pitemdata pitemdata m_type ctreeoptionsitemdata colorbrowser pitemdata m_bdrawcolorforicon bdrawcolor bdrawcolor pcustomdraw crect pcustomdraw pcustomdraw pcustomdraw getindentpostion hitem fillsolidrect getcolor hitem presult cdrf_dodefault bool c tree options ctrl on item expanding nmhdr pnmhdr lresult p result clean up any controls currently open we used assuming it is a standard scroll message and not from one of our spin controls if m hcontrolitem update tree control value from child control m hcontrolitem destroy old child control p result 0 return false ctreeoptionsctrl onitemexpanding presult m_hcontrolitem updatetreecontrolvaluefromchildcontrol m_hcontrolitem destroyoldchildcontrol presult c tree options browse button c tree options browse button m ptreectrl null m pedit null m pcombo null m htreectrlitem null ctreeoptionsbrowsebutton ctreeoptionsbrowsebutton m_ptreectrl m_pedit m_pcombo m_htreectrlitem c tree options browse button c tree options browse button ctreeoptionsbrowsebutton ctreeoptionsbrowsebutton void c tree options browse button set tree buddy c tree options ctrl p tree ctrl m ptreectrl p tree ctrl ctreeoptionsbrowsebutton settreebuddy ctreeoptionsctrl ptreectrl m_ptreectrl ptreectrl void c tree options browse button set edit buddy c tree options edit p edit m pedit p edit ctreeoptionsbrowsebutton seteditbuddy ctreeoptionsedit pedit m_pedit pedit void c tree options browse button set combo buddy c tree options combo p combo m pcombo p combo ctreeoptionsbrowsebutton setcombobuddy ctreeoptionscombo pcombo m_pcombo pcombo dword c tree options browse button get window style return ws visible ws child bs pushbutton ctreeoptionsbrowsebutton getwindowstyle ws_visible ws_child bs_pushbutton int c tree options browse button get width assert m ptreectrl cdc pdc m ptreectrl getdc int n button width 0 if pdc get the button width c size size text pdc get text extent t 4 we add space around text button pdc l ptodp size text n button width size text cx c string s text get caption size text pdc get text extent s text s text get length pdc l ptodp size text n button width size text cx m ptreectrl releasedc pdc else n button width 20 return n button width ctreeoptionsbrowsebutton getwidth m_ptreectrl m_ptreectrl nbuttonwidth csize sizetext gettextextent _t lptodp sizetext nbuttonwidth sizetext cstring stext getcaption sizetext gettextextent stext stext getlength lptodp sizetext nbuttonwidth sizetext m_ptreectrl nbuttonwidth nbuttonwidth c string c tree options browse button get caption return t cstring ctreeoptionsbrowsebutton getcaption _t void c tree options browse button set color colorref color m color color ctreeoptionsbrowsebutton setcolor m_color void c tree options browse button get font item logfont p log font assert p log font copy memory p log font m font sizeof logfont ctreeoptionsbrowsebutton getfontitem plogfont plogfont copymemory plogfont m_font void c tree options browse button set font item const logfont p log font assert p log font copy memory m font p log font sizeof logfont ctreeoptionsbrowsebutton setfontitem plogfont plogfont copymemory m_font plogfont void c tree options browse button browse for color assert m ptreectrl bring up a standard color selector dialog c color dialog dialog get color dialog m cc flags cc fullopen if dialog do modal idok set color dialog get color m ptreectrl set color m ptreectrl get selected item m color ask the tree control to reposition the button if need be m ptreectrl post message wm toc reposition child control ctreeoptionsbrowsebutton browseforcolor m_ptreectrl ccolordialog getcolor m_cc cc_fullopen domodal setcolor getcolor m_ptreectrl setcolor m_ptreectrl getselecteditem m_color m_ptreectrl postmessage wm_toc_reposition_child_control void c tree options browse button browse for font assert m ptreectrl bring up a standard color selector dialog c font dialog dialog m font if dialog do modal idok dialog get current font m font m ptreectrl set font item m ptreectrl get selected item m font ask the tree control to reposition the button if need be m ptreectrl post message wm toc reposition child control ctreeoptionsbrowsebutton browseforfont m_ptreectrl cfontdialog m_font domodal getcurrentfont m_font m_ptreectrl setfontitem m_ptreectrl getselecteditem m_font m_ptreectrl postmessage wm_toc_reposition_child_control void c tree options browse button browse for opaque assert false derived classes must implement this function if we are editing an opaque item the code which normally display some c dialog derived class to allow the item to be edited and then hive the data away somehow so that it can show the new value when the dialog is brought up again following is some pseudo code which would do this assert m ptreectrl bring up a our custom opaque editor dialog c my opaque p qpaque c my opaque m ptreectrl get opaque m htreectrlitem c my opaque dialog dialog dialog set opaque p opaque if dialog do modal idok p opaque dialog get opaque m ptreectrl set opaque m htreectrlitem dword p opaque m ptreectrl set edit text m htreectrlitem p opaque m ssomename ctreeoptionsbrowsebutton browseforopaque cdialog m_ptreectrl cmyopaque pqpaque cmyopaque m_ptreectrl getopaque m_htreectrlitem cmyopaquedialog setopaque popaque domodal popaque getopaque m_ptreectrl setopaque m_htreectrlitem popaque m_ptreectrl setedittext m_htreectrlitem popaque m_ssomename void c tree options browse button on kill focus c wnd p new wnd let the parent class do its thing c button on kill focus p new wnd update the tree control and close this window assert m ptreectrl if m pedit if p new wnd m ptreectrl m pedit m pedit m bdonotdestroyuponlosefocus assert m ptreectrl m ptreectrl handle child control losing focus ctreeoptionsbrowsebutton onkillfocus cwnd pnewwnd cbutton onkillfocus pnewwnd m_ptreectrl m_pedit pnewwnd m_ptreectrl m_pedit m_pedit m_bdonotdestroyuponlosefocus m_ptreectrl m_ptreectrl handlechildcontrollosingfocus void c tree options browse button on clicked assert m ptreectrl get the text currently in the control htreeitem h sel item m ptreectrl get selected item assert h sel item pull out the item data associated with the selected item c tree options item data p item data c tree options item data m ptreectrl get item data h sel item assert p item data if p item data m pruntimeclass1 is derived from runtime class c tree options edit assert m pedit decide on what dialog to bring up and call the appropiate virtual function if p item data m type c tree options item data file browser m pedit m bdonotdestroyuponlosefocus true c string s text m pedit get window text s text m pedit browse for file s text m pedit m bdonotdestroyuponlosefocus false else if p item data m type c tree options item data folder browser m pedit m bdonotdestroyuponlosefocus true c string s text m pedit get window text s text m pedit browse for folder s text m pedit m bdonotdestroyuponlosefocus false else if p item data m type c tree options item data opaque browser browse for opaque else assert false else if p item data m pruntimeclass1 is derived from runtime class c tree options combo assert m pcombo if p item data m type c tree options item data opaque browser browse for opaque else assert p item data m pruntimeclass1 is derived from runtime class c tree options browse button if p item data m type c tree options item data color browser browse for color else if p item data m type c tree options item data font browser browse for font else if p item data m type c tree options item data opaque browser browse for opaque else assert false ctreeoptionsbrowsebutton onclicked m_ptreectrl hselitem m_ptreectrl getselecteditem hselitem ctreeoptionsitemdata pitemdata ctreeoptionsitemdata m_ptreectrl getitemdata hselitem pitemdata pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsedit m_pedit pitemdata m_type ctreeoptionsitemdata filebrowser m_pedit m_bdonotdestroyuponlosefocus cstring stext m_pedit getwindowtext stext m_pedit browseforfile stext m_pedit m_bdonotdestroyuponlosefocus pitemdata m_type ctreeoptionsitemdata folderbrowser m_pedit m_bdonotdestroyuponlosefocus cstring stext m_pedit getwindowtext stext m_pedit browseforfolder stext m_pedit m_bdonotdestroyuponlosefocus pitemdata m_type ctreeoptionsitemdata opaquebrowser browseforopaque pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionscombo m_pcombo pitemdata m_type ctreeoptionsitemdata opaquebrowser browseforopaque pitemdata m_pruntimeclass1 isderivedfrom runtime_class ctreeoptionsbrowsebutton pitemdata m_type ctreeoptionsitemdata colorbrowser browseforcolor pitemdata m_type ctreeoptionsitemdata fontbrowser browseforfont pitemdata m_type ctreeoptionsitemdata opaquebrowser browseforopaque c tree options combo c tree options combo m ptreectrl null m pbuttonctrl null m htreectrlitem null ctreeoptionscombo ctreeoptionscombo m_ptreectrl m_pbuttonctrl m_htreectrlitem c tree options combo c tree options combo ctreeoptionscombo ctreeoptionscombo dword c tree options combo get window style return ws child ws visible ws vscroll cbs dropdownlist ctreeoptionscombo getwindowstyle ws_child ws_visible ws_vscroll cbs_dropdownlist int c tree options combo get drop down height return 100 ctreeoptionscombo getdropdownheight bool c tree options combo is related wnd c wnd p child bool b related false if p child c wnd p wnd p child while p wnd b related p wnd p wnd get parent b related p wnd this if b related assert m ptreectrl b related p child m ptreectrl m pbutton if b related b related p child m ptreectrl m pspin return b related ctreeoptionscombo isrelatedwnd cwnd pchild brelated pchild cwnd pwnd pchild pwnd brelated pwnd pwnd getparent brelated pwnd brelated m_ptreectrl brelated pchild m_ptreectrl m_pbutton brelated brelated pchild m_ptreectrl m_pspin brelated void c tree options combo on char uint n char uint n rep cnt uint n flags if n char vk tab assert m ptreectrl m ptreectrl set focus else pass on to the parent since we didn t handle it c combo box on char n char n rep cnt n flags ctreeoptionscombo onchar nchar nrepcnt nflags nchar vk_tab m_ptreectrl m_ptreectrl setfocus ccombobox onchar nchar nrepcnt nflags uint c tree options combo on get dlg code return c combo box on get dlg code dlgc wanttab ctreeoptionscombo ongetdlgcode ccombobox ongetdlgcode dlgc_wanttab void c tree options combo on kill focus c wnd p new wnd let the parent class do its thing c combo box on kill focus p new wnd if is related wnd p new wnd update the tree control and close this window assert m ptreectrl m ptreectrl handle child control losing focus ctreeoptionscombo onkillfocus cwnd pnewwnd ccombobox onkillfocus pnewwnd isrelatedwnd pnewwnd m_ptreectrl m_ptreectrl handlechildcontrollosingfocus c tree options font name combo c tree options font name combo ctreeoptionsfontnamecombo ctreeoptionsfontnamecombo c tree options font name combo c tree options font name combo ctreeoptionsfontnamecombo ctreeoptionsfontnamecombo int c tree options font name combo on create lpcreatestruct lp create struct let the parent class do its thing if c tree options combo on create lp create struct 1 return 1 enumerate all the fonts cdc pdc getdc assert pdc enum fonts pdc m hdc null enumfontproc lparam this releasedc pdc return 0 ctreeoptionsfontnamecombo oncreate lpcreatestruct ctreeoptionscombo oncreate lpcreatestruct enumfonts m_hdc _enumfontproc dword c tree options font name combo get window style return ws child ws visible ws vscroll cbs dropdownlist cbs sort ctreeoptionsfontnamecombo getwindowstyle ws_child ws_visible ws_vscroll cbs_dropdownlist cbs_sort dword dw type add the font name to the combo box add string lplf lf face name return 1 to continue enumeration dwtype addstring lffacename dword dw type lparam lp data convert from the sdk world to the c world c tree options font name combo p this c tree options font name combo lp data assert p this return p this enum font proc lplf lptm dw type dwtype lpdata ctreeoptionsfontnamecombo pthis ctreeoptionsfontnamecombo lpdata pthis pthis enumfontproc dwtype c tree options boolean combo c tree options boolean combo ctreeoptionsbooleancombo ctreeoptionsbooleancombo c tree options boolean combo c tree options boolean combo ctreeoptionsbooleancombo ctreeoptionsbooleancombo int c tree options boolean combo on create lpcreatestruct lp create struct let the parent class do its thing if c tree options combo on create lp create struct 1 return 1 add the two boolean strings c string s text verify s text load string ids treeoptions true add string s text verify s text load string ids treeoptions false add string s text return 0 ctreeoptionsbooleancombo oncreate lpcreatestruct ctreeoptionscombo oncreate lpcreatestruct cstring stext stext loadstring ids_treeoptions_true addstring stext stext loadstring ids_treeoptions_false addstring stext c tree options edit c tree options edit m ptreectrl null m bdonotdestroyuponlosefocus false m pbuttonctrl null m htreectrlitem null ctreeoptionsedit ctreeoptionsedit m_ptreectrl m_bdonotdestroyuponlosefocus m_pbuttonctrl m_htreectrlitem c tree options edit c tree options edit ctreeoptionsedit ctreeoptionsedit dword c tree options edit get window style return ws visible ws child es left es autohscroll ctreeoptionsedit getwindowstyle ws_visible ws_child es_left es_autohscroll int c tree options edit get height int n item height return max n item height 20 ctreeoptionsedit getheight nitemheight nitemheight void c tree options edit browse for folder const c string s initial folder assert m ptreectrl bring up a standard directory chooser dialog tchar s display name max path browseinfo bi bi hwnd owner m ptreectrl get safe hwnd bi pidl root null c string s caption get browse for folder caption bi lpsz title s caption bi psz display name s display name bi ul flags bif returnonlyfsdirs bi lpfn sh browse set sel proc bi l param lparam lpctstr s initial folder lpitemidlist p itemid list sh browse for folder bi if p itemid list retreive the path and update on screen tchar s path max path if sh get path fromid list p itemid list s path set window text s path avoid memory leaks by deleting the pidl using the shells task allocator i malloc p malloc if succeeded sh get malloc p malloc p malloc free p itemid list p malloc release ctreeoptionsedit browseforfolder cstring sinitialfolder m_ptreectrl sdisplayname _max_path hwndowner m_ptreectrl getsafehwnd pidlroot cstring scaption getbrowseforfoldercaption lpsztitle scaption pszdisplayname sdisplayname ulflags bif_returnonlyfsdirs shbrowsesetselproc lparam sinitialfolder pitemidlist shbrowseforfolder pitemidlist spath _max_path shgetpathfromidlist pitemidlist spath setwindowtext spath imalloc pmalloc shgetmalloc pmalloc pmalloc pitemidlist pmalloc void c tree options edit browse for file const c string s initial file assert m ptreectrl create the special file save dialog c tree options file dialog dlg true null s initial file ofn hidereadonly ofn overwriteprompt get file extension filter m ptreectrl modify the title to the desired value c string s caption get browse for file caption dlg m ofn lpstr title s caption bring up the dialog and if hit ok set the text in this control to the new filename if dlg do modal idok set window text dlg get path name ctreeoptionsedit browseforfile cstring sinitialfile m_ptreectrl ctreeoptionsfiledialog sinitialfile ofn_hidereadonly ofn_overwriteprompt getfileextensionfilter m_ptreectrl cstring scaption getbrowseforfilecaption m_ofn lpstrtitle scaption domodal setwindowtext getpathname c string c tree options edit get browse for folder caption return t please specify a folder cstring ctreeoptionsedit getbrowseforfoldercaption _t c string c tree options edit get browse for file caption return t please specify a file cstring ctreeoptionsedit getbrowseforfilecaption _t c string c tree options edit get file extension filter return t all files cstring ctreeoptionsedit getfileextensionfilter _t void c tree options edit on char uint n char uint n rep cnt uint n flags if n char vk tab assert m ptreectrl if m ptreectrl m pbutton m ptreectrl m pbutton set focus else m ptreectrl set focus else pass on to the parent since we didn t handle it c edit on char n char n rep cnt n flags ctreeoptionsedit onchar nchar nrepcnt nflags nchar vk_tab m_ptreectrl m_ptreectrl m_pbutton m_ptreectrl m_pbutton setfocus m_ptreectrl setfocus cedit onchar nchar nrepcnt nflags uint c tree options edit on get dlg code return c edit on get dlg code dlgc wanttab ctreeoptionsedit ongetdlgcode cedit ongetdlgcode dlgc_wanttab void c tree options edit on kill focus c wnd p new wnd let the parent class do its thing c edit on kill focus p new wnd update the tree control and close this window assert m ptreectrl if p new wnd m pbuttonctrl assert m ptreectrl m ptreectrl handle child control losing focus ctreeoptionsedit onkillfocus cwnd pnewwnd cedit onkillfocus pnewwnd m_ptreectrl pnewwnd m_pbuttonctrl m_ptreectrl m_ptreectrl handlechildcontrollosingfocus int callback c tree options edit sh browse set sel proc hwnd h wnd uint u msg lparam l param lparam lp data if u msg bffm initialized send message h wnd bffm setselection true lp data return 0 ctreeoptionsedit shbrowsesetselproc hwnd umsg lparam lpdata umsg bffm_initialized sendmessage hwnd bffm_setselection lpdata c tree options spin ctrl c tree options spin ctrl m ptreectrl null m pedit null m htreectrlitem null ctreeoptionsspinctrl ctreeoptionsspinctrl m_ptreectrl m_pedit m_htreectrlitem c tree options spin ctrl c tree options spin ctrl ctreeoptionsspinctrl ctreeoptionsspinctrl void c tree options spin ctrl set tree buddy c tree options ctrl p tree ctrl m ptreectrl p tree ctrl ctreeoptionsspinctrl settreebuddy ctreeoptionsctrl ptreectrl m_ptreectrl ptreectrl void c tree options spin ctrl set edit buddy c tree options edit p edit m pedit p edit ctreeoptionsspinctrl seteditbuddy ctreeoptionsedit pedit m_pedit pedit dword c tree options spin ctrl get window style return ws visible ws child uds arrowkeys uds setbuddyint uds nothousands uds alignright ctreeoptionsspinctrl getwindowstyle ws_visible ws_child uds_arrowkeys uds_setbuddyint uds_nothousands uds_alignright void c tree options spin ctrl get default range int lower int upper lower 0 upper 100 ctreeoptionsspinctrl getdefaultrange void c tree options spin ctrl on kill focus c wnd p new wnd let the parent class do its thing c spin button ctrl on kill focus p new wnd update the tree control and close this window assert m ptreectrl if p new wnd m pedit m ptreectrl handle child control losing focus ctreeoptionsspinctrl onkillfocus cwnd pnewwnd cspinbuttonctrl onkillfocus pnewwnd m_ptreectrl pnewwnd m_pedit m_ptreectrl handlechildcontrollosingfocus c tree options file dialog c tree options file dialog bool b open file dialog lpctstr lpsz def ext lpctstr lpsz file name dword dw flags lpctstr lpsz filter c wnd p parent wnd c file dialog b open file dialog lpsz def ext lpsz file name dw flags lpsz filter p parent wnd ctreeoptionsfiledialog ctreeoptionsfiledialog bopenfiledialog lpszdefext lpszfilename dwflags lpszfilter cwnd pparentwnd cfiledialog bopenfiledialog lpszdefext lpszfilename dwflags lpszfilter pparentwnd void c tree options file dialog on init done c string s text if s text load string ids treeoptions ok assert false lptstr psz buffer s text get buffer s text get length modify the text on the idok button to ok commdlg opensave setcontroltext get parent m hwnd idok psz buffer s text release buffer ctreeoptionsfiledialog oninitdone cstring stext stext loadstring ids_treeoptions_ok pszbuffer stext getbuffer stext getlength commdlg_opensave_setcontroltext getparent m_hwnd pszbuffer stext releasebuffer c tree options date ctrl c tree options date ctrl m ptreectrl null m bdonotdestroyuponlosefocus false m htreectrlitem null ctreeoptionsdatectrl ctreeoptionsdatectrl m_ptreectrl m_bdonotdestroyuponlosefocus m_htreectrlitem c tree options date ctrl c tree options date ctrl ctreeoptionsdatectrl ctreeoptionsdatectrl c string c tree options date ctrl get display text const systemtime st tchar s date 100 s date 0 t 0 get date format locale user default date shortdate st null s date 100 return s date cstring ctreeoptionsdatectrl getdisplaytext sdate sdate _t getdateformat locale_user_default date_shortdate sdate sdate dword c tree options date ctrl get window style return ws child ws visible dts shortdateformat ctreeoptionsdatectrl getwindowstyle ws_child ws_visible dts_shortdateformat bool c tree options date ctrl is related wnd c wnd p child return get month cal ctrl p child ctreeoptionsdatectrl isrelatedwnd cwnd pchild getmonthcalctrl pchild void c tree options date ctrl on char uint n char uint n rep cnt uint n flags if n char vk tab assert m ptreectrl m ptreectrl set focus else pass on to the parent since we didn t handle it c date time ctrl on char n char n rep cnt n flags ctreeoptionsdatectrl onchar nchar nrepcnt nflags nchar vk_tab m_ptreectrl m_ptreectrl setfocus cdatetimectrl onchar nchar nrepcnt nflags uint c tree options date ctrl on get dlg code return c date time ctrl on get dlg code dlgc wanttab ctreeoptionsdatectrl ongetdlgcode cdatetimectrl ongetdlgcode dlgc_wanttab void c tree options date ctrl on kill focus c wnd p new wnd let the parent class do its thing c date time ctrl on kill focus p new wnd update the list control and close this window if is related wnd p new wnd assert m ptreectrl m ptreectrl handle child control losing focus ctreeoptionsdatectrl onkillfocus cwnd pnewwnd cdatetimectrl onkillfocus pnewwnd isrelatedwnd pnewwnd m_ptreectrl m_ptreectrl handlechildcontrollosingfocus c tree options time ctrl c tree options time ctrl ctreeoptionstimectrl ctreeoptionstimectrl c tree options time ctrl c tree options time ctrl ctreeoptionstimectrl ctreeoptionstimectrl c string c tree options time ctrl get display text const systemtime st tchar s time 100 s time 0 t 0 get time format locale user default 0 st null s time 100 return s time cstring ctreeoptionstimectrl getdisplaytext stime stime _t gettimeformat locale_user_default stime stime dword c tree options time ctrl get window style return ws child ws visible dts timeformat ctreeoptionstimectrl getwindowstyle ws_child ws_visible dts_timeformat c tree optionsip address ctrl c tree optionsip address ctrl m ptreectrl null m bdonotdestroyuponlosefocus false m htreectrlitem null ctreeoptionsipaddressctrl ctreeoptionsipaddressctrl m_ptreectrl m_bdonotdestroyuponlosefocus m_htreectrlitem c tree optionsip address ctrl c tree optionsip address ctrl ctreeoptionsipaddressctrl ctreeoptionsipaddressctrl c string c tree optionsip address ctrl get display text dword dw address c string s address s address format t d d d d dw address 0xff000000 24 dw address 0xff0000 16 dw address 0xff00 8 dw address 0xff return s address cstring ctreeoptionsipaddressctrl getdisplaytext dwaddress cstring saddress saddress _t dwaddress dwaddress dwaddress dwaddress saddress dword c tree optionsip address ctrl get window style return ws child ws visible ctreeoptionsipaddressctrl getwindowstyle ws_child ws_visible bool c tree optionsip address ctrl is related wnd c wnd p child bool b ancestor false if p child c wnd p wnd p child while p wnd b ancestor p wnd p wnd get parent b ancestor p wnd this return b ancestor ctreeoptionsipaddressctrl isrelatedwnd cwnd pchild bancestor pchild cwnd pwnd pchild pwnd bancestor pwnd pwnd getparent bancestor pwnd bancestor void c tree optionsip address ctrl on char uint n char uint n rep cnt uint n flags if n char vk tab assert m ptreectrl m ptreectrl set focus else pass on to the parent since we didn t handle it cip address ctrl on char n char n rep cnt n flags ctreeoptionsipaddressctrl onchar nchar nrepcnt nflags nchar vk_tab m_ptreectrl m_ptreectrl setfocus cipaddressctrl onchar nchar nrepcnt nflags uint c tree optionsip address ctrl on get dlg code return cip address ctrl on get dlg code dlgc wanttab ctreeoptionsipaddressctrl ongetdlgcode cipaddressctrl ongetdlgcode dlgc_wanttab void c tree optionsip address ctrl on kill focus c wnd p new wnd let the parent class do its thing cip address ctrl on kill focus p new wnd if is related wnd p new wnd update the list control and close this window assert m ptreectrl m ptreectrl handle child control losing focus ctreeoptionsipaddressctrl onkillfocus cwnd pnewwnd cipaddressctrl onkillfocus pnewwnd isrelatedwnd pnewwnd m_ptreectrl m_ptreectrl handlechildcontrollosingfocus c tree options item data m type unknown m pruntimeclass1 null m pruntimeclass2 null m dwitemdata dword 1 m color rgb 255 0 0 zero memory m font sizeof logfont zero memory m datetime sizeof systemtime m dwipaddress 0 m bdrawcolorforicon true ctreeoptionsitemdata m_type m_pruntimeclass1 m_pruntimeclass2 m_dwitemdata m_color zeromemory m_font zeromemory m_datetime m_dwipaddress m_bdrawcolorforicon c tree options ctrl ex c tree options ctrl ex uint u image list color flags m uimagelistcolorflags u image list color flags set auto select true does not work set toggle over icon only true ctreeoptionsctrlex ctreeoptionsctrlex uimagelistcolorflags m_uimagelistcolorflags uimagelistcolorflags setautoselect settoggleovericononly c tree options ctrl ex c tree options ctrl ex void ctreeoptionsctrlex ctreeoptionsctrlex void c tree options ctrl ex set edit label htreeitem h item const c string rstr label const c string rstr sep get text separator c string str item text get item text h item int n separator str item text find rstr sep c string str data if n separator 1 str data str item text mid n separator rstr sep get length set item text h item rstr label rstr sep str data ctreeoptionsctrlex seteditlabel hitem cstring rstrlabel cstring rstrsep gettextseparator cstring stritemtext getitemtext hitem nseparator stritemtext rstrsep cstring strdata nseparator strdata stritemtext nseparator rstrsep getlength setitemtext hitem rstrlabel rstrsep strdata void c tree options ctrl ex update check box group htreeitem h item set redraw false iterate through all children and if all the checkboxes are checked then also automatically check the item if no checkboxes are checked then also automatically uncheck the item htreeitem h parent h item if h parent is check box h parent bool b no check boxes checked true bool b all check boxes checked true htreeitem h child get next item h parent tvgn child while h child if is check box h child bool b this checked verify get check box h child b this checked b no check boxes checked b no check boxes checked b this checked b all check boxes checked b all check boxes checked b this checked move on to the next item h child get next item h child tvgn next if b no check boxes checked bool b old state get check box h parent b old state set check box h parent false if b old state false notify parent bn clicked h parent else if b all check boxes checked bool b old state get check box h parent b old state set check box h parent false gets rid of the semi state set check box h parent true if b old state true notify parent bn clicked h parent else bool b enable verify get check box enable h parent b enable set enabled semi check box h parent b enable reset the redraw flag set redraw true ctreeoptionsctrlex updatecheckboxgroup hitem setredraw hparent hitem hparent ischeckbox hparent bnocheckboxeschecked ballcheckboxeschecked hchild getnextitem hparent tvgn_child hchild ischeckbox hchild bthischecked getcheckbox hchild bthischecked bnocheckboxeschecked bnocheckboxeschecked bthischecked ballcheckboxeschecked ballcheckboxeschecked bthischecked hchild getnextitem hchild tvgn_next bnocheckboxeschecked boldstate getcheckbox hparent boldstate setcheckbox hparent boldstate notifyparent bn_clicked hparent ballcheckboxeschecked boldstate getcheckbox hparent boldstate setcheckbox hparent setcheckbox hparent boldstate notifyparent bn_clicked hparent benable getcheckboxenable hparent benable setenabledsemicheckbox hparent benable setredraw void c tree options ctrl ex set image list color flags uint u image list color flags m uimagelistcolorflags u image list color flags ctreeoptionsctrlex setimagelistcolorflags uimagelistcolorflags m_uimagelistcolorflags uimagelistcolorflags void c tree options ctrl ex on create image list cdc pdc screen cdc from handle getdc hwnd desktop explicitly use screen dc for proper rtl support if pdc screen const int i bmp width 16 const int i bmp height 16 const int i bitmaps 13 c bitmap bmp controls if bmp controls create compatible bitmap pdc screen i bmp width i bitmaps i bmp height if m iltree create i bmp width i bmp height m uimagelistcolorflags ilc mask 0 1 cdc dc mem if dc mem create compatibledc pdc screen htheme h theme g xpstyle is theme active g xpstyle is app themed g xpstyle open theme data null l button null c bitmap p old bmp dc mem select object bmp controls dc mem fill solid rect 0 0 i bmp width i bitmaps i bmp height get sys color color window int i ctrl width i bmp width 2 int i ctrl height i bmp height 2 int i ctrl width 16 3 int i ctrl height 16 3 int i ctrl left i bmp width i ctrl width 2 int i ctrl top i bmp height i ctrl height 2 checkbox c rect rc bmp 0 0 0 i bmp width 0 i bmp height c rect rc ctrl i ctrl left i ctrl top i ctrl left i ctrl width i ctrl top i ctrl height if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs uncheckednormal rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs uncheckednormal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttoncheck dfcs flat checkbox checked rc ctrl move tox i ctrl left i bmp width 1 if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs checkednormal rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs checkednormal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttoncheck dfcs checked dfcs flat radio rc ctrl move tox i ctrl left i bmp width 2 if h theme g xpstyle draw theme background h theme dc mem bp radiobutton rbs uncheckednormal rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox rbs uncheckednormal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttonradio dfcs flat radio checked rc ctrl move tox i ctrl left i bmp width 3 if h theme g xpstyle draw theme background h theme dc mem bp radiobutton rbs checkednormal rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox rbs checkednormal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttonradio dfcs checked dfcs flat checkbox disabled rc ctrl move tox i ctrl left i bmp width 4 if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs uncheckeddisabled rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs uncheckeddisabled rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttoncheck dfcs inactive dfcs flat checkbox checked disabled rc ctrl move tox i ctrl left i bmp width 5 if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs checkeddisabled rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs checkeddisabled rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttoncheck dfcs checked dfcs inactive dfcs flat radio disabled rc ctrl move tox i ctrl left i bmp width 6 if h theme g xpstyle draw theme background h theme dc mem bp radiobutton rbs uncheckeddisabled rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox rbs uncheckeddisabled rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttonradio dfcs inactive dfcs flat radio checked disabled rc ctrl move tox i ctrl left i bmp width 7 if h theme g xpstyle draw theme background h theme dc mem bp radiobutton rbs checkeddisabled rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox rbs checkeddisabled rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs buttonradio dfcs checked dfcs inactive dfcs flat checkbox checked tri state rc ctrl move tox i ctrl left i bmp width 8 if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs mixednormal rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs mixednormal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs button3state dfcs checked dfcs flat checkbox checked tri state disabled rc ctrl move tox i ctrl left i bmp width 9 if h theme g xpstyle draw theme background h theme dc mem bp checkbox cbs mixeddisabled rc ctrl null g xpstyle draw theme edge h theme dc mem bp checkbox cbs mixeddisabled rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc button dfcs button3state dfcs checked dfcs inactive dfcs flat assert treeoptsctrlimg edit 11 rc bmp move tox i bmp width 11 rc ctrl move tox i ctrl left i bmp width 11 c font font if font create point font 10 t courier c font p old font dc mem select object font dc mem text out rc ctrl left 2 rc ctrl top t i dc mem select object p old font c rect rc edge rc bmp rc edge top 1 rc edge bottom 1 dc mem draw edge rc edge edge etched bf rect if h theme g xpstyle close theme data h theme h theme null h theme g xpstyle is theme active g xpstyle is app themed g xpstyle open theme data null l combobox null rc ctrl move tox i ctrl left i bmp width 12 if h theme g xpstyle draw theme background h theme dc mem cp dropdownbutton cbxs normal rc ctrl null g xpstyle draw theme edge h theme dc mem cp dropdownbutton cbxs normal rc ctrl 0 0 null else dc mem draw frame control rc ctrl dfc scroll dfcs scrollcombobox dfcs flat dc mem select object p old bmp m iltree add bmp controls rgb 255 0 255 if h theme g xpstyle close theme data h theme releasedc hwnd desktop pdc screen ctreeoptionsctrlex oncreateimagelist pdcscreen fromhandle hwnd_desktop pdcscreen ibmpwidth ibmpheight ibitmaps cbitmap bmpcontrols bmpcontrols createcompatiblebitmap pdcscreen ibmpwidth ibitmaps ibmpheight m_iltree ibmpwidth ibmpheight m_uimagelistcolorflags ilc_mask dcmem dcmem createcompatibledc pdcscreen htheme g_xpstyle isthemeactive g_xpstyle isappthemed g_xpstyle openthemedata cbitmap poldbmp dcmem selectobject bmpcontrols dcmem fillsolidrect ibmpwidth ibitmaps ibmpheight getsyscolor color_window ictrlwidth ibmpwidth ictrlheight ibmpheight ictrlwidth ictrlheight ictrlleft ibmpwidth ictrlwidth ictrltop ibmpheight ictrlheight crect rcbmp ibmpwidth ibmpheight crect rcctrl ictrlleft ictrltop ictrlleft ictrlwidth ictrltop ictrlheight htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_uncheckednormal rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_uncheckednormal rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttoncheck dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_checkednormal rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_checkednormal rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttoncheck dfcs_checked dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_radiobutton rbs_uncheckednormal rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox rbs_uncheckednormal rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttonradio dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_radiobutton rbs_checkednormal rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox rbs_checkednormal rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttonradio dfcs_checked dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_uncheckeddisabled rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_uncheckeddisabled rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttoncheck dfcs_inactive dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_checkeddisabled rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_checkeddisabled rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttoncheck dfcs_checked dfcs_inactive dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_radiobutton rbs_uncheckeddisabled rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox rbs_uncheckeddisabled rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttonradio dfcs_inactive dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_radiobutton rbs_checkeddisabled rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox rbs_checkeddisabled rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_buttonradio dfcs_checked dfcs_inactive dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_mixednormal rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_mixednormal rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_button3state dfcs_checked dfcs_flat rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem bp_checkbox cbs_mixeddisabled rcctrl g_xpstyle drawthemeedge htheme dcmem bp_checkbox cbs_mixeddisabled rcctrl dcmem drawframecontrol rcctrl dfc_button dfcs_button3state dfcs_checked dfcs_inactive dfcs_flat treeoptsctrlimg_edit rcbmp movetox ibmpwidth rcctrl movetox ictrlleft ibmpwidth cfont createpointfont _t cfont poldfont dcmem selectobject dcmem textout rcctrl rcctrl _t dcmem selectobject poldfont crect rcedge rcbmp rcedge rcedge dcmem drawedge rcedge edge_etched bf_rect htheme g_xpstyle closethemedata htheme htheme htheme g_xpstyle isthemeactive g_xpstyle isappthemed g_xpstyle openthemedata rcctrl movetox ictrlleft ibmpwidth htheme g_xpstyle drawthemebackground htheme dcmem cp_dropdownbutton cbxs_normal rcctrl g_xpstyle drawthemeedge htheme dcmem cp_dropdownbutton cbxs_normal rcctrl dcmem drawframecontrol rcctrl dfc_scroll dfcs_scrollcombobox dfcs_flat dcmem selectobject poldbmp m_iltree bmpcontrols htheme g_xpstyle closethemedata htheme hwnd_desktop pdcscreen void c tree options ctrl ex handle child control losing focus c tree options ctrl handle child control losing focus ctreeoptionsctrlex handlechildcontrollosingfocus ctreeoptionsctrl handlechildcontrollosingfocus bool c tree options ctrl ex notify parent uint u code htreeitem h item c wnd p wnd get parent if p wnd return false treeoptsctrlnotify ton ton nmhdr hwnd from m hwnd ton nmhdr id from get window long m hwnd gwl id ton nmhdr code u code ton h item h item return p wnd send message um treeoptsctrl notify get window long m hwnd gwl id lparam ton ctreeoptionsctrlex notifyparent ucode hitem cwnd pwnd getparent pwnd hwndfrom m_hwnd idfrom getwindowlong m_hwnd gwl_id ucode hitem hitem pwnd sendmessage um_treeoptsctrl_notify getwindowlong m_hwnd gwl_id void c tree options ctrl ex handle check box htreeitem h item bool b check turn of redraw to q all the changes we re going to make here set redraw false toggle the state bool b old state get check box h item b old state verify set check box h item b check if b old state b check notify parent bn clicked h item if the item has children then iterate through them and for all items which are check boxes set their state to be the same as the parent htreeitem h child get next item h item tvgn child while h child if is check box h child bool b this checked get check box h child b this checked set check box h child b check if b this checked b check notify parent bn clicked h child move on to the next item h child get next item h child tvgn next get the parent item and if it is a checkbox then iterate through all its children and if all the checkboxes are checked then also automatically check the parent if no checkboxes are checked then also automatically uncheck the parent htreeitem h parent get next item h item tvgn parent update check box group h parent reset the redraw flag set redraw true ctreeoptionsctrlex handlecheckbox hitem bcheck setredraw boldstate getcheckbox hitem boldstate setcheckbox hitem bcheck boldstate bcheck notifyparent bn_clicked hitem hchild getnextitem hitem tvgn_child hchild ischeckbox hchild bthischecked getcheckbox hchild bthischecked setcheckbox hchild bcheck bthischecked bcheck notifyparent bn_clicked hchild hchild getnextitem hchild tvgn_next hparent getnextitem hitem tvgn_parent updatecheckboxgroup hparent setredraw bool c tree options ctrl ex set radio button htreeitem h parent int n index validate our parameters assert is group h parent parent item must be a group item iterate through the child items and turn on the specified one and turn off all the other ones htreeitem h child get next item h parent tvgn child turn of redraw to q all the changes we re going to make here set redraw false int i 0 bool b checked some item false while h child if we reach a non radio button then break out of the loop if is radio button h child break if i n index turn this item on bool b old state get radio button h child b old state verify set item image h child 3 3 b checked some item true if b old state notify parent bn clicked h child else bool b enable verify get radio button enable h child b enable turn this item off if b enable verify set item image h child 2 2 else verify set item image h child 4 4 move on to the next item h child get next item h child tvgn next i assert b checked some item you specified an index which does not exist reset the redraw flag set redraw true return true ctreeoptionsctrlex setradiobutton hparent nindex isgroup hparent hchild getnextitem hparent tvgn_child setredraw bcheckedsomeitem hchild isradiobutton hchild nindex boldstate getradiobutton hchild boldstate setitemimage hchild bcheckedsomeitem boldstate notifyparent bn_clicked hchild benable getradiobuttonenable hchild benable benable setitemimage hchild setitemimage hchild hchild getnextitem hchild tvgn_next bcheckedsomeitem setredraw bool c tree options ctrl ex set radio button htreeitem h item validate our parameters assert is radio button h item must be a radio item to check it iterate through the sibling items and turn them all off except this one htreeitem h parent get next item h item tvgn parent assert is group h parent parent item must be a group item iterate through the child items and turn on the specified one and turn off all the other ones htreeitem h child get next item h parent tvgn child turn of redraw to q all the changes we re going to make here set redraw false while h child if we reach a non radio button then break out of the loop if is radio button h child break if h child h item turn this item on bool b old state get radio button h child b old state verify set item image h child 3 3 if b old state notify parent bn clicked h child else bool b enable verify get radio button enable h child b enable turn this item off if b enable verify set item image h child 2 2 else verify set item image h child 6 6 move on to the next item h child get next item h child tvgn next reset the redraw flag set redraw true return true ctreeoptionsctrlex setradiobutton hitem isradiobutton hitem hparent getnextitem hitem tvgn_parent isgroup hparent hchild getnextitem hparent tvgn_child setredraw hchild isradiobutton hchild hchild hitem boldstate getradiobutton hchild boldstate setitemimage hchild boldstate notifyparent bn_clicked hchild benable getradiobuttonenable hchild benable benable setitemimage hchild setitemimage hchild hchild getnextitem hchild tvgn_next setredraw void c tree options ctrl ex on destroy c tree options ctrl on destroy m iltree delete image list ctreeoptionsctrlex ondestroy ctreeoptionsctrl ondestroy m_iltree deleteimagelist int c num tree options edit on create lpcreatestruct lp create struct m bself true if c tree options edit on create lp create struct 1 return 1 m bself false return 0 cnumtreeoptionsedit oncreate lpcreatestruct m_bself ctreeoptionsedit oncreate lpcreatestruct m_bself void c num tree options edit on en change if m bself c tree options ctrl ex m ptreectrl notify parent en change m htreectrlitem cnumtreeoptionsedit onenchange m_bself ctreeoptionsctrlex m_ptreectrl notifyparent en_change m_htreectrlitem int c tree options edit ex on create lpcreatestruct lp create struct m bself true if c tree options edit on create lp create struct 1 return 1 m bself false return 0 ctreeoptionseditex oncreate lpcreatestruct m_bself ctreeoptionsedit oncreate lpcreatestruct m_bself void c tree options edit ex on en change if m bself c tree options ctrl ex m ptreectrl notify parent en change m htreectrlitem ctreeoptionseditex onenchange m_bself ctreeoptionsctrlex m_ptreectrl notifyparent en_change m_htreectrlitem m ctrltreeoptions the app m idfltimagelistcolorflags m btimestamp false m bsoundevents false m bmiscmessage false m bjoinmessage false m bpartmessage false m bquitmessage false m bemuleallowaddfriend false m bemuleaddfriend false m bemulesendlink false m bacceptlinks false m bacceptlinksfriends false m bhelpchannel false m bchannelsonconnect false m binitializedtreeopts false m htitimestamp null m htisoundevents null m htiinfomessage null m htimiscmessage null m htijoinmessage null m htipartmessage null m htiquitmessage null m htiemuleproto null m htiemuleaddfriend null m htiemuleallowaddfriend null m htiemulesendlink null m htiacceptlinks null m htiacceptlinksfriends null m htihelpchannel null m htichannelsonconnect null m_ctrltreeoptions theapp m_idfltimagelistcolorflags m_btimestamp m_bsoundevents m_bmiscmessage m_bjoinmessage m_bpartmessage m_bquitmessage m_bemuleallowaddfriend m_bemuleaddfriend m_bemulesendlink m_bacceptlinks m_bacceptlinksfriends m_bhelpchannel m_bchannelsonconnect m_binitializedtreeopts m_htitimestamp m_htisoundevents m_htiinfomessage m_htimiscmessage m_htijoinmessage m_htipartmessage m_htiquitmessage m_htiemuleproto m_htiemuleaddfriend m_htiemuleallowaddfriend m_htiemulesendlink m_htiacceptlinks m_htiacceptlinksfriends m_htihelpchannel m_htichannelsonconnect cp pgirc cp pgirc cppgirc cppgirc type void cp pgirc localize void if m hwnd get dlg item idc irc server frm set window text get res string ids pw server get dlg item idc irc misc frm set window text get res string ids pw misc get dlg item idc irc nick frm set window text get res string ids pw nick get dlg item idc irc name text set window text get res string ids irc name get dlg item idc irc minuser text set window text get res string ids uusers get dlg item idc irc filter frm set window text get res string ids irc channellist get dlg item idc irc usechanfilter set window text get res string ids irc usefilter get dlg item idc irc perform frm set window text get res string ids irc perform get dlg item idc irc useperform set window text get res string ids irc useperform if m htisoundevents m ctrltreeoptions set item text m htisoundevents get res string ids irc soundevents if m htitimestamp m ctrltreeoptions set item text m htitimestamp get res string ids irc addtimestamp if m htiinfomessage m ctrltreeoptions set item text m htiinfomessage get res string ids irc ignoreinfomessage if m htimiscmessage m ctrltreeoptions set item text m htimiscmessage get res string ids irc ignoremiscmessage if m htijoinmessage m ctrltreeoptions set item text m htijoinmessage get res string ids irc ignorejoinmessage if m htipartmessage m ctrltreeoptions set item text m htipartmessage get res string ids irc ignorepartmessage if m htiquitmessage m ctrltreeoptions set item text m htiquitmessage get res string ids irc ignorequitmessage if m htiemuleproto m ctrltreeoptions set item text m htiemuleproto get res string ids irc emuleproto ignoreinfomessage if m htiemuleaddfriend m ctrltreeoptions set item text m htiemuleaddfriend get res string ids irc emuleproto ignoreaddfriend if m htiemuleallowaddfriend m ctrltreeoptions set item text m htiemuleallowaddfriend get res string ids irc emuleproto allowaddfriend if m htiemulesendlink m ctrltreeoptions set item text m htiemulesendlink get res string ids irc emuleproto ignoresendlink if m htiacceptlinks m ctrltreeoptions set item text m htiacceptlinks get res string ids irc acceptlinks if m htiacceptlinksfriends m ctrltreeoptions set item text m htiacceptlinksfriends get res string ids irc acceptlinksfriends if m htihelpchannel m ctrltreeoptions set item text m htihelpchannel get res string ids irc helpchannel if m htichannelsonconnect m ctrltreeoptions set item text m htichannelsonconnect get res string ids irc loadchannellistoncon cppgirc m_hwnd getdlgitem idc_irc_server_frm setwindowtext getresstring ids_pw_server getdlgitem idc_irc_misc_frm setwindowtext getresstring ids_pw_misc getdlgitem idc_irc_nick_frm setwindowtext getresstring ids_pw_nick getdlgitem idc_irc_name_text setwindowtext getresstring ids_irc_name getdlgitem idc_irc_minuser_text setwindowtext getresstring ids_uusers getdlgitem idc_irc_filter_frm setwindowtext getresstring ids_irc_channellist getdlgitem idc_irc_usechanfilter setwindowtext getresstring ids_irc_usefilter getdlgitem idc_irc_perform_frm setwindowtext getresstring ids_irc_perform getdlgitem idc_irc_useperform setwindowtext getresstring ids_irc_useperform m_htisoundevents m_ctrltreeoptions setitemtext m_htisoundevents getresstring ids_irc_soundevents m_htitimestamp m_ctrltreeoptions setitemtext m_htitimestamp getresstring ids_irc_addtimestamp m_htiinfomessage m_ctrltreeoptions setitemtext m_htiinfomessage getresstring ids_irc_ignoreinfomessage m_htimiscmessage m_ctrltreeoptions setitemtext m_htimiscmessage getresstring ids_irc_ignoremiscmessage m_htijoinmessage m_ctrltreeoptions setitemtext m_htijoinmessage getresstring ids_irc_ignorejoinmessage m_htipartmessage m_ctrltreeoptions setitemtext m_htipartmessage getresstring ids_irc_ignorepartmessage m_htiquitmessage m_ctrltreeoptions setitemtext m_htiquitmessage getresstring ids_irc_ignorequitmessage m_htiemuleproto m_ctrltreeoptions setitemtext m_htiemuleproto getresstring ids_irc_emuleproto_ignoreinfomessage m_htiemuleaddfriend m_ctrltreeoptions setitemtext m_htiemuleaddfriend getresstring ids_irc_emuleproto_ignoreaddfriend m_htiemuleallowaddfriend m_ctrltreeoptions setitemtext m_htiemuleallowaddfriend getresstring ids_irc_emuleproto_allowaddfriend m_htiemulesendlink m_ctrltreeoptions setitemtext m_htiemulesendlink getresstring ids_irc_emuleproto_ignoresendlink m_htiacceptlinks m_ctrltreeoptions setitemtext m_htiacceptlinks getresstring ids_irc_acceptlinks m_htiacceptlinksfriends m_ctrltreeoptions setitemtext m_htiacceptlinksfriends getresstring ids_irc_acceptlinksfriends m_htihelpchannel m_ctrltreeoptions setitemtext m_htihelpchannel getresstring ids_irc_helpchannel m_htichannelsonconnect m_ctrltreeoptions setitemtext m_htichannelsonconnect getresstring ids_irc_loadchannellistoncon void cp pgirc load settings void if the prefs m bircusechanfilter check dlg button idc irc usechanfilter 1 else check dlg button idc irc usechanfilter 0 if the prefs m bircuseperform check dlg button idc irc useperform 1 else check dlg button idc irc useperform 0 get dlg item idc irc server box set window text the prefs m sircserver get dlg item idc irc nick box set window text the prefs m sircnick get dlg item idc irc name box set window text the prefs m sircchannamefilter get dlg item idc irc perform box set window text the prefs m sircperformstring c string str buffer str buffer format t d the prefs m iircchanneluserfilter get dlg item idc irc minuser box set window text str buffer cppgirc loadsettings theprefs m_bircusechanfilter checkdlgbutton idc_irc_usechanfilter checkdlgbutton idc_irc_usechanfilter theprefs m_bircuseperform checkdlgbutton idc_irc_useperform checkdlgbutton idc_irc_useperform getdlgitem idc_irc_server_box setwindowtext theprefs m_sircserver getdlgitem idc_irc_nick_box setwindowtext theprefs m_sircnick getdlgitem idc_irc_name_box setwindowtext theprefs m_sircchannamefilter getdlgitem idc_irc_perform_box setwindowtext theprefs m_sircperformstring cstring strbuffer strbuffer _t theprefs m_iircchanneluserfilter getdlgitem idc_irc_minuser_box setwindowtext strbuffer void cp pgirc update controls get dlg item idc irc perform box enable window is dlg button checked idc irc useperform get dlg item idc irc name box enable window is dlg button checked idc irc usechanfilter get dlg item idc irc minuser box enable window is dlg button checked idc irc usechanfilter cppgirc updatecontrols getdlgitem idc_irc_perform_box enablewindow isdlgbuttonchecked idc_irc_useperform getdlgitem idc_irc_name_box enablewindow isdlgbuttonchecked idc_irc_usechanfilter getdlgitem idc_irc_minuser_box enablewindow isdlgbuttonchecked idc_irc_usechanfilter void cp pgirc do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc misc irc m ctrltreeoptions if m binitializedtreeopts m htisoundevents m ctrltreeoptions insert check box get res string ids irc soundevents tvi root m bsoundevents m htihelpchannel m ctrltreeoptions insert check box get res string ids irc helpchannel tvi root m bhelpchannel m htichannelsonconnect m ctrltreeoptions insert check box get res string ids irc loadchannellistoncon tvi root m bchannelsonconnect m htitimestamp m ctrltreeoptions insert check box get res string ids irc addtimestamp tvi root m btimestamp m htiinfomessage m ctrltreeoptions insert check box get res string ids irc ignoreinfomessage tvi root false m htimiscmessage m ctrltreeoptions insert check box get res string ids irc ignoremiscmessage m htiinfomessage m bmiscmessage m htijoinmessage m ctrltreeoptions insert check box get res string ids irc ignorejoinmessage m htiinfomessage m bjoinmessage m htipartmessage m ctrltreeoptions insert check box get res string ids irc ignorepartmessage m htiinfomessage m bpartmessage m htiquitmessage m ctrltreeoptions insert check box get res string ids irc ignorequitmessage m htiinfomessage m bquitmessage m htiemuleproto m ctrltreeoptions insert check box get res string ids irc emuleproto ignoreinfomessage tvi root false m htiemuleaddfriend m ctrltreeoptions insert check box get res string ids irc emuleproto ignoreaddfriend m htiemuleproto m bemuleaddfriend m htiemulesendlink m ctrltreeoptions insert check box get res string ids irc emuleproto ignoresendlink m htiemuleproto m bemulesendlink m htiemuleallowaddfriend m ctrltreeoptions insert check box get res string ids irc emuleproto allowaddfriend tvi root m bemuleallowaddfriend m htiacceptlinks m ctrltreeoptions insert check box get res string ids irc acceptlinks tvi root m bacceptlinks m htiacceptlinksfriends m ctrltreeoptions insert check box get res string ids irc acceptlinksfriends tvi root m bacceptlinksfriends m ctrltreeoptions expand m htiinfomessage tve expand m ctrltreeoptions expand m htiemuleproto tve expand m ctrltreeoptions send message wm vscroll sb top m binitializedtreeopts true ddx treecheck pdx idc misc irc m htitimestamp m btimestamp ddx treecheck pdx idc misc irc m htisoundevents m bsoundevents ddx treecheck pdx idc misc irc m htimiscmessage m bmiscmessage ddx treecheck pdx idc misc irc m htijoinmessage m bjoinmessage ddx treecheck pdx idc misc irc m htipartmessage m bpartmessage ddx treecheck pdx idc misc irc m htiquitmessage m bquitmessage ddx treecheck pdx idc misc irc m htiemuleaddfriend m bemuleaddfriend ddx treecheck pdx idc misc irc m htiemuleallowaddfriend m bemuleallowaddfriend ddx treecheck pdx idc misc irc m htiemulesendlink m bemulesendlink ddx treecheck pdx idc misc irc m htiacceptlinks m bacceptlinks ddx treecheck pdx idc misc irc m htiacceptlinksfriends m bacceptlinksfriends ddx treecheck pdx idc misc irc m htihelpchannel m bhelpchannel ddx treecheck pdx idc misc irc m htichannelsonconnect m bchannelsonconnect m ctrltreeoptions update check box group m htiemuleproto m ctrltreeoptions update check box group m htiinfomessage m ctrltreeoptions set check box enable m htiacceptlinksfriends m bacceptlinks cppgirc dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_misc_irc m_ctrltreeoptions m_binitializedtreeopts m_htisoundevents m_ctrltreeoptions insertcheckbox getresstring ids_irc_soundevents tvi_root m_bsoundevents m_htihelpchannel m_ctrltreeoptions insertcheckbox getresstring ids_irc_helpchannel tvi_root m_bhelpchannel m_htichannelsonconnect m_ctrltreeoptions insertcheckbox getresstring ids_irc_loadchannellistoncon tvi_root m_bchannelsonconnect m_htitimestamp m_ctrltreeoptions insertcheckbox getresstring ids_irc_addtimestamp tvi_root m_btimestamp m_htiinfomessage m_ctrltreeoptions insertcheckbox getresstring ids_irc_ignoreinfomessage tvi_root m_htimiscmessage m_ctrltreeoptions insertcheckbox getresstring ids_irc_ignoremiscmessage m_htiinfomessage m_bmiscmessage m_htijoinmessage m_ctrltreeoptions insertcheckbox getresstring ids_irc_ignorejoinmessage m_htiinfomessage m_bjoinmessage m_htipartmessage m_ctrltreeoptions insertcheckbox getresstring ids_irc_ignorepartmessage m_htiinfomessage m_bpartmessage m_htiquitmessage m_ctrltreeoptions insertcheckbox getresstring ids_irc_ignorequitmessage m_htiinfomessage m_bquitmessage m_htiemuleproto m_ctrltreeoptions insertcheckbox getresstring ids_irc_emuleproto_ignoreinfomessage tvi_root m_htiemuleaddfriend m_ctrltreeoptions insertcheckbox getresstring ids_irc_emuleproto_ignoreaddfriend m_htiemuleproto m_bemuleaddfriend m_htiemulesendlink m_ctrltreeoptions insertcheckbox getresstring ids_irc_emuleproto_ignoresendlink m_htiemuleproto m_bemulesendlink m_htiemuleallowaddfriend m_ctrltreeoptions insertcheckbox getresstring ids_irc_emuleproto_allowaddfriend tvi_root m_bemuleallowaddfriend m_htiacceptlinks m_ctrltreeoptions insertcheckbox getresstring ids_irc_acceptlinks tvi_root m_bacceptlinks m_htiacceptlinksfriends m_ctrltreeoptions insertcheckbox getresstring ids_irc_acceptlinksfriends tvi_root m_bacceptlinksfriends m_ctrltreeoptions m_htiinfomessage tve_expand m_ctrltreeoptions m_htiemuleproto tve_expand m_ctrltreeoptions sendmessage wm_vscroll sb_top m_binitializedtreeopts ddx_treecheck idc_misc_irc m_htitimestamp m_btimestamp ddx_treecheck idc_misc_irc m_htisoundevents m_bsoundevents ddx_treecheck idc_misc_irc m_htimiscmessage m_bmiscmessage ddx_treecheck idc_misc_irc m_htijoinmessage m_bjoinmessage ddx_treecheck idc_misc_irc m_htipartmessage m_bpartmessage ddx_treecheck idc_misc_irc m_htiquitmessage m_bquitmessage ddx_treecheck idc_misc_irc m_htiemuleaddfriend m_bemuleaddfriend ddx_treecheck idc_misc_irc m_htiemuleallowaddfriend m_bemuleallowaddfriend ddx_treecheck idc_misc_irc m_htiemulesendlink m_bemulesendlink ddx_treecheck idc_misc_irc m_htiacceptlinks m_bacceptlinks ddx_treecheck idc_misc_irc m_htiacceptlinksfriends m_bacceptlinksfriends ddx_treecheck idc_misc_irc m_htihelpchannel m_bhelpchannel ddx_treecheck idc_misc_irc m_htichannelsonconnect m_bchannelsonconnect m_ctrltreeoptions updatecheckboxgroup m_htiemuleproto m_ctrltreeoptions updatecheckboxgroup m_htiinfomessage m_ctrltreeoptions setcheckboxenable m_htiacceptlinksfriends m_bacceptlinks bool cp pgirc on init dialog m btimestamp the prefs getirc add timestamp m bsoundevents the prefs get irc sound events m bmiscmessage the prefs get irc ignore misc message m bjoinmessage the prefs get irc ignore join message m bpartmessage the prefs get irc ignore part message m bquitmessage the prefs get irc ignore quit message m bemuleaddfriend the prefs get irc ignore emule proto add friend m bemuleallowaddfriend the prefs get irc allow emule proto add friend m bemulesendlink the prefs get irc ignore emule proto send link m bacceptlinks the prefs get irc accept links m bacceptlinksfriends the prefs get irc accept links friends m bhelpchannel the prefs get irc help channel m bchannelsonconnect the prefs getirc list on connect m ctrltreeoptions set image list color flags the app m idfltimagelistcolorflags c property page on init dialog init window styles this c edit get dlg item idc irc nick box set limit text 20 c edit get dlg item idc irc minuser box set limit text 6 c edit get dlg item idc irc server box set limit text 40 c edit get dlg item idc irc name box set limit text 40 c edit get dlg item idc irc perform box set limit text 250 load settings localize update controls return true return true unless you set the focus to a control exception ocx property pages should return false cppgirc oninitdialog m_btimestamp theprefs getircaddtimestamp m_bsoundevents theprefs getircsoundevents m_bmiscmessage theprefs getircignoremiscmessage m_bjoinmessage theprefs getircignorejoinmessage m_bpartmessage theprefs getircignorepartmessage m_bquitmessage theprefs getircignorequitmessage m_bemuleaddfriend theprefs getircignoreemuleprotoaddfriend m_bemuleallowaddfriend theprefs getircallowemuleprotoaddfriend m_bemulesendlink theprefs getircignoreemuleprotosendlink m_bacceptlinks theprefs getircacceptlinks m_bacceptlinksfriends theprefs getircacceptlinksfriends m_bhelpchannel theprefs getirchelpchannel m_bchannelsonconnect theprefs getirclistonconnect m_ctrltreeoptions setimagelistcolorflags theapp m_idfltimagelistcolorflags cpropertypage oninitdialog initwindowstyles cedit getdlgitem idc_irc_nick_box setlimittext cedit getdlgitem idc_irc_minuser_box setlimittext cedit getdlgitem idc_irc_server_box setlimittext cedit getdlgitem idc_irc_name_box setlimittext cedit getdlgitem idc_irc_perform_box setlimittext loadsettings updatecontrols bool cp pgirc on apply if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus if update data return false the prefs m bircaddtimestamp m btimestamp the prefs m bircsoundevents m bsoundevents the prefs m bircignoremiscmessage m bmiscmessage the prefs m bircignorejoinmessage m bjoinmessage the prefs m bircignorepartmessage m bpartmessage the prefs m bircignorequitmessage m bquitmessage the prefs m bircignoreemuleprotoaddfriend m bemuleaddfriend the prefs m bircallowemuleprotoaddfriend m bemuleallowaddfriend the prefs m bircignoreemuleprotosendlink m bemulesendlink the prefs m bircacceptlinks m bacceptlinks the prefs m bircacceptlinksfriends m bacceptlinksfriends the prefs m birchelpchannel m bhelpchannel the prefs m birclistonconnect m bchannelsonconnect if is dlg button checked idc irc usechanfilter the prefs m bircusechanfilter true else the prefs m bircusechanfilter false if is dlg button checked idc irc useperform the prefs m bircuseperform true else the prefs m bircuseperform false tchar buffer 510 if get dlg item idc irc nick box get window text length get dlg item idc irc nick box get window text buffer 20 if tcscmp buffer the prefs m sircnick c string input input format t s buffer input trim input input span excluding t if input the app emuledlg ircwnd send string c string t nick input tcscpy the prefs m sircnick input if get dlg item idc irc server box get window text length get dlg item idc irc server box get window text buffer 40 tcscpy the prefs m sircserver buffer get dlg item idc irc name box get window text buffer 40 tcscpy the prefs m sircchannamefilter buffer get dlg item idc irc perform box get window text buffer 250 tcscpy the prefs m sircperformstring buffer if get dlg item idc irc minuser box get window text length get dlg item idc irc minuser box get window text buffer 6 the prefs m iircchanneluserfilter tstoi buffer else the prefs m iircchanneluserfilter 0 load settings set modified false return c property page on apply cppgirc onapply m_ctrltreeoptions handlechildcontrollosingfocus updatedata theprefs m_bircaddtimestamp m_btimestamp theprefs m_bircsoundevents m_bsoundevents theprefs m_bircignoremiscmessage m_bmiscmessage theprefs m_bircignorejoinmessage m_bjoinmessage theprefs m_bircignorepartmessage m_bpartmessage theprefs m_bircignorequitmessage m_bquitmessage theprefs m_bircignoreemuleprotoaddfriend m_bemuleaddfriend theprefs m_bircallowemuleprotoaddfriend m_bemuleallowaddfriend theprefs m_bircignoreemuleprotosendlink m_bemulesendlink theprefs m_bircacceptlinks m_bacceptlinks theprefs m_bircacceptlinksfriends m_bacceptlinksfriends theprefs m_birchelpchannel m_bhelpchannel theprefs m_birclistonconnect m_bchannelsonconnect isdlgbuttonchecked idc_irc_usechanfilter theprefs m_bircusechanfilter theprefs m_bircusechanfilter isdlgbuttonchecked idc_irc_useperform theprefs m_bircuseperform theprefs m_bircuseperform getdlgitem idc_irc_nick_box getwindowtextlength getdlgitem idc_irc_nick_box getwindowtext _tcscmp theprefs m_sircnick cstring _t spanexcluding _t theapp sendstring cstring _t _tcscpy theprefs m_sircnick getdlgitem idc_irc_server_box getwindowtextlength getdlgitem idc_irc_server_box getwindowtext _tcscpy theprefs m_sircserver getdlgitem idc_irc_name_box getwindowtext _tcscpy theprefs m_sircchannamefilter getdlgitem idc_irc_perform_box getwindowtext _tcscpy theprefs m_sircperformstring getdlgitem idc_irc_minuser_box getwindowtextlength getdlgitem idc_irc_minuser_box getwindowtext theprefs m_iircchanneluserfilter _tstoi theprefs m_iircchanneluserfilter loadsettings setmodified cpropertypage onapply bool cp pgirc on kill active if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus return c property page on kill active cppgirc onkillactive m_ctrltreeoptions handlechildcontrollosingfocus cpropertypage onkillactive bool cp pgirc on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgirc oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pgirc on destroy m ctrltreeoptions delete all items m ctrltreeoptions destroy window m binitializedtreeopts false m htiacceptlinks null m htiacceptlinksfriends null m htiemuleproto null m htiemuleaddfriend null m htiemuleallowaddfriend null m htiemulesendlink null m htihelpchannel null m htichannelsonconnect null m htisoundevents null m htiinfomessage null m htimiscmessage null m htijoinmessage null m htipartmessage null m htiquitmessage null m htitimestamp null c property page on destroy cppgirc ondestroy m_ctrltreeoptions deleteallitems m_ctrltreeoptions destroywindow m_binitializedtreeopts m_htiacceptlinks m_htiacceptlinksfriends m_htiemuleproto m_htiemuleaddfriend m_htiemuleallowaddfriend m_htiemulesendlink m_htihelpchannel m_htichannelsonconnect m_htisoundevents m_htiinfomessage m_htimiscmessage m_htijoinmessage m_htipartmessage m_htiquitmessage m_htitimestamp cpropertypage ondestroy void cp pgirc on btn click perform set modified update controls cppgirc onbtnclickperform setmodified updatecontrols lresult cp pgirc on tree opts ctrl notify wparam w param lparam l param if w param idc misc irc treeoptsctrlnotify pton treeoptsctrlnotify l param if pton h item m htiacceptlinks bool b check if m ctrltreeoptions get check box m htiacceptlinks b check m ctrltreeoptions set check box enable m htiacceptlinksfriends b check set modified return 0 cppgirc ontreeoptsctrlnotify wparam lparam wparam idc_misc_irc lparam hitem m_htiacceptlinks bcheck m_ctrltreeoptions getcheckbox m_htiacceptlinks bcheck m_ctrltreeoptions setcheckboxenable m_htiacceptlinksfriends bcheck setmodified void cp pgirc on help the app show help emule faq preferences irc cppgirc onhelp theapp showhelp emule_faq_preferences_irc bool cp pgirc on help info helpinfo p help info on help return true cppgirc onhelpinfo phelpinfo onhelp m ctrltreeoptions the app m idfltimagelistcolorflags m ifilebuffersize 0 m iqueuesize 0 m imaxconnperfive 0 m imaxhalfopen 0 m bconditionaltcpaccept false m bautotakeed2klinks false m bverbose false m bdebugsourceexchange false m blogbannedclients false m blogratingdescreceived false m blogsecureident false m blogfilteredips false m blogfilesaving false m bloga4af false m bloguldlevents false m bcreditsystem false m blog2disk false m bdebug2disk false m icommitfiles 0 m bfilterlanips false m bextcontrols false m userverkeepalivetimeout 0 m bsparsepartfiles false m bfullalloc false m bcheckdiskspace false m fminfreediskspacemb 0 0f void m syourhostname m bfirewallstartup false m iloglevel 0 m bdisablepeercache false m bdynupenabled false m idynupminupload 0 m idynuppingtolerance 0 m idynupgoingupdivider 0 m idynupgoingdowndivider 0 m idynupnumberofpings 0 m ba4afsavecpu false m iextractmetadata 0 m binitializedtreeopts false m htitcpgroup null m htimaxcon5sec null m htimaxhalfopen null m hticonditionaltcpaccept null m htiautotakeed2klinks null m htiverbosegroup null m htiverbose null m htidebugsourceexchange null m htilogbannedclients null m htilogratingdescreceived null m htilogsecureident null m htilogfilteredips null m htilogfilesaving null m htiloguldlevents null m hticreditsystem null m htilog2disk null m htidebug2disk null m hticommit null m hticommitnever null m hticommitonshutdown null m hticommitalways null m htifilterlanips null m htiextcontrols null m htiserverkeepalivetimeout null m htisparsepartfiles null m htifullalloc null m hticheckdiskspace null m htiminfreediskspace null m htiyourhostname null m htifirewallstartup null m htiloglevel null m htidisablepeercache null m htidynup null m htidynupenabled null m htidynupminupload null m htidynuppingtolerance null m htidynuppingtolerancemilliseconds null m htidynuppingtolerancegroup null m htidynupradiopingtolerance null m htidynupradiopingtolerancemilliseconds null m htidynupgoingupdivider null m htidynupgoingdowndivider null m htidynupnumberofpings null m htia4afsavecpu null m htiloga4af null m htiextractmetadata null m_ctrltreeoptions theapp m_idfltimagelistcolorflags m_ifilebuffersize m_iqueuesize m_imaxconnperfive m_imaxhalfopen m_bconditionaltcpaccept m_bautotakeed2klinks m_bverbose m_bdebugsourceexchange m_blogbannedclients m_blogratingdescreceived m_blogsecureident m_blogfilteredips m_blogfilesaving m_bloga4af m_bloguldlevents m_bcreditsystem m_blog2disk m_bdebug2disk m_icommitfiles m_bfilterlanips m_bextcontrols m_userverkeepalivetimeout m_bsparsepartfiles m_bfullalloc m_bcheckdiskspace m_fminfreediskspacemb m_syourhostname m_bfirewallstartup m_iloglevel m_bdisablepeercache m_bdynupenabled m_idynupminupload m_idynuppingtolerance m_idynupgoingupdivider m_idynupgoingdowndivider m_idynupnumberofpings m_ba4afsavecpu m_iextractmetadata m_binitializedtreeopts m_htitcpgroup m_htimaxcon5sec m_htimaxhalfopen m_hticonditionaltcpaccept m_htiautotakeed2klinks m_htiverbosegroup m_htiverbose m_htidebugsourceexchange m_htilogbannedclients m_htilogratingdescreceived m_htilogsecureident m_htilogfilteredips m_htilogfilesaving m_htiloguldlevents m_hticreditsystem m_htilog2disk m_htidebug2disk m_hticommit m_hticommitnever m_hticommitonshutdown m_hticommitalways m_htifilterlanips m_htiextcontrols m_htiserverkeepalivetimeout m_htisparsepartfiles m_htifullalloc m_hticheckdiskspace m_htiminfreediskspace m_htiyourhostname m_htifirewallstartup m_htiloglevel m_htidisablepeercache m_htidynup m_htidynupenabled m_htidynupminupload m_htidynuppingtolerance m_htidynuppingtolerancemilliseconds m_htidynuppingtolerancegroup m_htidynupradiopingtolerance m_htidynupradiopingtolerancemilliseconds m_htidynupgoingupdivider m_htidynupgoingdowndivider m_htidynupnumberofpings m_htia4afsavecpu m_htiloga4af m_htiextractmetadata cp pg tweaks cp pg tweaks cppgtweaks cppgtweaks void cp pg tweaks localize void if m hwnd set window text get res string ids pw tweak get dlg item idc warning set window text get res string ids tweaks warning if m htitcpgroup m ctrltreeoptions set item text m htitcpgroup get res string ids tcpip conns if m htimaxcon5sec m ctrltreeoptions set edit label m htimaxcon5sec get res string ids maxcon5seclabel if m htimaxhalfopen m ctrltreeoptions set edit label m htimaxhalfopen get res string ids maxhalfopencons if m hticonditionaltcpaccept m ctrltreeoptions set item text m hticonditionaltcpaccept get res string ids condtcpaccept if m htiautotakeed2klinks m ctrltreeoptions set item text m htiautotakeed2klinks get res string ids autotakeed2klinks if m hticreditsystem m ctrltreeoptions set item text m hticreditsystem get res string ids usecreditsystem if m htilog2disk m ctrltreeoptions set item text m htilog2disk get res string ids log2disk if m htiverbosegroup m ctrltreeoptions set item text m htiverbosegroup get res string ids verbose if m htiverbose m ctrltreeoptions set item text m htiverbose get res string ids enabled if m htidebug2disk m ctrltreeoptions set item text m htidebug2disk get res string ids log2disk if m htidebugsourceexchange m ctrltreeoptions set item text m htidebugsourceexchange get res string ids debug source exchange if m htilogbannedclients m ctrltreeoptions set item text m htilogbannedclients get res string ids log banned clients if m htilogratingdescreceived m ctrltreeoptions set item text m htilogratingdescreceived get res string ids log rating recv if m htilogsecureident m ctrltreeoptions set item text m htilogsecureident get res string ids log secure ident if m htilogfilteredips m ctrltreeoptions set item text m htilogfilteredips get res string ids log filtered ips if m htilogfilesaving m ctrltreeoptions set item text m htilogfilesaving get res string ids log file saving if m htiloglevel m ctrltreeoptions set edit label m htiloglevel get res string ids log level if m htiloga4af m ctrltreeoptions set item text m htiloga4af get res string ids log a4af if m htiloguldlevents m ctrltreeoptions set item text m htiloguldlevents get res string ids log uldl events if m hticommit m ctrltreeoptions set item text m hticommit get res string ids commitfiles if m hticommitnever m ctrltreeoptions set item text m hticommitnever get res string ids never if m hticommitonshutdown m ctrltreeoptions set item text m hticommitonshutdown get res string ids onshutdown if m hticommitalways m ctrltreeoptions set item text m hticommitalways get res string ids always if m htiextractmetadata m ctrltreeoptions set item text m htiextractmetadata get res string ids extract meta data if m htiextractmetadatanever m ctrltreeoptions set item text m htiextractmetadatanever get res string ids never if m htiextractmetadataid3lib m ctrltreeoptions set item text m htiextractmetadataid3lib get res string ids meta data id3lib if m htiextractmetadatamediadet m ctrltreeoptions set item text m htiextractmetadatamediadet get res string ids meta data mediadet if m htifilterlanips m ctrltreeoptions set item text m htifilterlanips get res string ids pw filter if m htiextcontrols m ctrltreeoptions set item text m htiextcontrols get res string ids showextsettings if m htiserverkeepalivetimeout m ctrltreeoptions set edit label m htiserverkeepalivetimeout get res string ids serverkeepalivetimeout if m htisparsepartfiles m ctrltreeoptions set item text m htisparsepartfiles get res string ids sparsepartfiles if m hticheckdiskspace m ctrltreeoptions set item text m hticheckdiskspace get res string ids checkdiskspace if m htiminfreediskspace m ctrltreeoptions set edit label m htiminfreediskspace get res string ids minfreediskspace if m htiyourhostname m ctrltreeoptions set edit label m htiyourhostname get res string ids yourhostname itsonlyme hostname source if m htifirewallstartup m ctrltreeoptions set item text m htifirewallstartup get res string ids fo pref startup if m htidisablepeercache m ctrltreeoptions set item text m htidisablepeercache get res string ids disablepeerache if m htidynup m ctrltreeoptions set item text m htidynup get res string ids dynup if m htidynupenabled m ctrltreeoptions set item text m htidynupenabled get res string ids dynupenabled if m htidynupminupload m ctrltreeoptions set edit label m htidynupminupload get res string ids dynup minupload if m htidynuppingtolerance m ctrltreeoptions set edit label m htidynuppingtolerance get res string ids dynup pingtolerance if m htidynupgoingupdivider m ctrltreeoptions set edit label m htidynupgoingupdivider get res string ids dynup goingupdivider if m htidynupgoingdowndivider m ctrltreeoptions set edit label m htidynupgoingdowndivider get res string ids dynup goingdowndivider if m htidynupnumberofpings m ctrltreeoptions set edit label m htidynupnumberofpings get res string ids dynup numberofpings if m htia4afsavecpu m ctrltreeoptions set item text m htia4afsavecpu get res string ids a4af save cpu if m htifullalloc m ctrltreeoptions set item text m htifullalloc get res string ids fullalloc c string temp temp format t s s get res string ids filebuffersize cast itox bytes m ifilebuffersize false false get dlg item idc filebuffersize static set window text temp temp format t s s get res string ids queuesize get formatedu int m iqueuesize get dlg item idc queuesize static set window text temp cppgtweaks m_hwnd setwindowtext getresstring ids_pw_tweak getdlgitem idc_warning setwindowtext getresstring ids_tweaks_warning m_htitcpgroup m_ctrltreeoptions setitemtext m_htitcpgroup getresstring ids_tcpip_conns m_htimaxcon5sec m_ctrltreeoptions seteditlabel m_htimaxcon5sec getresstring ids_maxcon5seclabel m_htimaxhalfopen m_ctrltreeoptions seteditlabel m_htimaxhalfopen getresstring ids_maxhalfopencons m_hticonditionaltcpaccept m_ctrltreeoptions setitemtext m_hticonditionaltcpaccept getresstring ids_condtcpaccept m_htiautotakeed2klinks m_ctrltreeoptions setitemtext m_htiautotakeed2klinks getresstring ids_autotakeed2klinks m_hticreditsystem m_ctrltreeoptions setitemtext m_hticreditsystem getresstring ids_usecreditsystem m_htilog2disk m_ctrltreeoptions setitemtext m_htilog2disk getresstring ids_log2disk m_htiverbosegroup m_ctrltreeoptions setitemtext m_htiverbosegroup getresstring ids_verbose m_htiverbose m_ctrltreeoptions setitemtext m_htiverbose getresstring ids_enabled m_htidebug2disk m_ctrltreeoptions setitemtext m_htidebug2disk getresstring ids_log2disk m_htidebugsourceexchange m_ctrltreeoptions setitemtext m_htidebugsourceexchange getresstring ids_debug_source_exchange m_htilogbannedclients m_ctrltreeoptions setitemtext m_htilogbannedclients getresstring ids_log_banned_clients m_htilogratingdescreceived m_ctrltreeoptions setitemtext m_htilogratingdescreceived getresstring ids_log_rating_recv m_htilogsecureident m_ctrltreeoptions setitemtext m_htilogsecureident getresstring ids_log_secure_ident m_htilogfilteredips m_ctrltreeoptions setitemtext m_htilogfilteredips getresstring ids_log_filtered_ips m_htilogfilesaving m_ctrltreeoptions setitemtext m_htilogfilesaving getresstring ids_log_file_saving m_htiloglevel m_ctrltreeoptions seteditlabel m_htiloglevel getresstring ids_log_level m_htiloga4af m_ctrltreeoptions setitemtext m_htiloga4af getresstring ids_log_a4af m_htiloguldlevents m_ctrltreeoptions setitemtext m_htiloguldlevents getresstring ids_log_uldl_events m_hticommit m_ctrltreeoptions setitemtext m_hticommit getresstring ids_commitfiles m_hticommitnever m_ctrltreeoptions setitemtext m_hticommitnever getresstring ids_never m_hticommitonshutdown m_ctrltreeoptions setitemtext m_hticommitonshutdown getresstring ids_onshutdown m_hticommitalways m_ctrltreeoptions setitemtext m_hticommitalways getresstring ids_always m_htiextractmetadata m_ctrltreeoptions setitemtext m_htiextractmetadata getresstring ids_extract_meta_data m_htiextractmetadatanever m_ctrltreeoptions setitemtext m_htiextractmetadatanever getresstring ids_never m_htiextractmetadataid3lib m_ctrltreeoptions setitemtext m_htiextractmetadataid3lib getresstring ids_meta_data_id3lib m_htiextractmetadatamediadet m_ctrltreeoptions setitemtext m_htiextractmetadatamediadet getresstring ids_meta_data_mediadet m_htifilterlanips m_ctrltreeoptions setitemtext m_htifilterlanips getresstring ids_pw_filter m_htiextcontrols m_ctrltreeoptions setitemtext m_htiextcontrols getresstring ids_showextsettings m_htiserverkeepalivetimeout m_ctrltreeoptions seteditlabel m_htiserverkeepalivetimeout getresstring ids_serverkeepalivetimeout m_htisparsepartfiles m_ctrltreeoptions setitemtext m_htisparsepartfiles getresstring ids_sparsepartfiles m_hticheckdiskspace m_ctrltreeoptions setitemtext m_hticheckdiskspace getresstring ids_checkdiskspace m_htiminfreediskspace m_ctrltreeoptions seteditlabel m_htiminfreediskspace getresstring ids_minfreediskspace m_htiyourhostname m_ctrltreeoptions seteditlabel m_htiyourhostname getresstring ids_yourhostname hostnamesource m_htifirewallstartup m_ctrltreeoptions setitemtext m_htifirewallstartup getresstring ids_fo_pref_startup m_htidisablepeercache m_ctrltreeoptions setitemtext m_htidisablepeercache getresstring ids_disablepeerache m_htidynup m_ctrltreeoptions setitemtext m_htidynup getresstring ids_dynup m_htidynupenabled m_ctrltreeoptions setitemtext m_htidynupenabled getresstring ids_dynupenabled m_htidynupminupload m_ctrltreeoptions seteditlabel m_htidynupminupload getresstring ids_dynup_minupload m_htidynuppingtolerance m_ctrltreeoptions seteditlabel m_htidynuppingtolerance getresstring ids_dynup_pingtolerance m_htidynupgoingupdivider m_ctrltreeoptions seteditlabel m_htidynupgoingupdivider getresstring ids_dynup_goingupdivider m_htidynupgoingdowndivider m_ctrltreeoptions seteditlabel m_htidynupgoingdowndivider getresstring ids_dynup_goingdowndivider m_htidynupnumberofpings m_ctrltreeoptions seteditlabel m_htidynupnumberofpings getresstring ids_dynup_numberofpings m_htia4afsavecpu m_ctrltreeoptions setitemtext m_htia4afsavecpu getresstring ids_a4af_save_cpu m_htifullalloc m_ctrltreeoptions setitemtext m_htifullalloc getresstring ids_fullalloc cstring _t getresstring ids_filebuffersize castitoxbytes m_ifilebuffersize getdlgitem idc_filebuffersize_static setwindowtext _t getresstring ids_queuesize getformateduint m_iqueuesize getdlgitem idc_queuesize_static setwindowtext void cp pg tweaks do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc filebuffersize m ctlfilebuffsize ddx control pdx idc queuesize m ctlqueuesize ddx control pdx idc ext opts m ctrltreeoptions if m binitializedtreeopts int i img backup 8 default icon int i img log 8 int i img dynyp 8 int i img connection 8 int i imga4af 8 int i img meta data 8 c image list piml m ctrltreeoptions get image list tvsil normal if piml i img backup piml add c temp icon loader t harddisk i img log piml add c temp icon loader t log i img dynyp piml add c temp icon loader t upload i img connection piml add c temp icon loader t connection i imga4af piml add c temp icon loader t download i img meta data piml add c temp icon loader t media info tcp ip group m htitcpgroup m ctrltreeoptions insert group get res string ids tcpip conns i img connection tvi root m htimaxcon5sec m ctrltreeoptions insert item get res string ids maxcon5seclabel treeoptsctrlimg edit treeoptsctrlimg edit m htitcpgroup m ctrltreeoptions add edit box m htimaxcon5sec runtime class c num tree options edit m htimaxhalfopen m ctrltreeoptions insert item get res string ids maxhalfopencons treeoptsctrlimg edit treeoptsctrlimg edit m htitcpgroup m ctrltreeoptions add edit box m htimaxhalfopen runtime class c num tree options edit m hticonditionaltcpaccept m ctrltreeoptions insert check box get res string ids condtcpaccept m htitcpgroup m bconditionaltcpaccept m htiserverkeepalivetimeout m ctrltreeoptions insert item get res string ids serverkeepalivetimeout treeoptsctrlimg edit treeoptsctrlimg edit m htitcpgroup m ctrltreeoptions add edit box m htiserverkeepalivetimeout runtime class c num tree options edit miscellaneous group m htiautotakeed2klinks m ctrltreeoptions insert check box get res string ids autotakeed2klinks tvi root m bautotakeed2klinks m hticreditsystem m ctrltreeoptions insert check box get res string ids usecreditsystem tvi root m bcreditsystem m htifirewallstartup m ctrltreeoptions insert check box get res string ids fo pref startup tvi root m bfirewallstartup m htifilterlanips m ctrltreeoptions insert check box get res string ids pw filter tvi root m bfilterlanips m htiextcontrols m ctrltreeoptions insert check box get res string ids showextsettings tvi root m bextcontrols m htia4afsavecpu m ctrltreeoptions insert check box get res string ids a4af save cpu tvi root m ba4afsavecpu zz download manager m htiyourhostname m ctrltreeoptions insert item get res string ids yourhostname treeoptsctrlimg edit treeoptsctrlimg edit tvi root m ctrltreeoptions add edit box m htiyourhostname runtime class c tree options edit ex m htidisablepeercache m ctrltreeoptions insert check box get res string ids disablepeerache tvi root m bdisablepeercache file related group m htisparsepartfiles m ctrltreeoptions insert check box get res string ids sparsepartfiles tvi root m bsparsepartfiles m htifullalloc m ctrltreeoptions insert check box get res string ids fullalloc tvi root m bfullalloc m hticheckdiskspace m ctrltreeoptions insert check box get res string ids checkdiskspace tvi root m bcheckdiskspace m htiminfreediskspace m ctrltreeoptions insert item get res string ids minfreediskspace treeoptsctrlimg edit treeoptsctrlimg edit m hticheckdiskspace m ctrltreeoptions add edit box m htiminfreediskspace runtime class c num tree options edit m hticommit m ctrltreeoptions insert group get res string ids commitfiles i img backup tvi root m hticommitnever m ctrltreeoptions insert radio button get res string ids never m hticommit m icommitfiles 0 m hticommitonshutdown m ctrltreeoptions insert radio button get res string ids onshutdown m hticommit m icommitfiles 1 m hticommitalways m ctrltreeoptions insert radio button get res string ids always m hticommit m icommitfiles 2 m htiextractmetadata m ctrltreeoptions insert group get res string ids extract meta data i img meta data tvi root m htiextractmetadatanever m ctrltreeoptions insert radio button get res string ids never m htiextractmetadata m iextractmetadata 0 m htiextractmetadataid3lib m ctrltreeoptions insert radio button get res string ids meta data id3lib m htiextractmetadata m iextractmetadata 1 m htiextractmetadatamediadet m ctrltreeoptions insert radio button get res string ids meta data mediadet m htiextractmetadata m iextractmetadata 2 logging group m htilog2disk m ctrltreeoptions insert check box get res string ids log2disk tvi root m blog2disk if the prefs get enable verbose options m htiverbosegroup m ctrltreeoptions insert group get res string ids verbose i img log tvi root m htiverbose m ctrltreeoptions insert check box get res string ids enabled m htiverbosegroup m bverbose m htiloglevel m ctrltreeoptions insert item get res string ids log level treeoptsctrlimg edit treeoptsctrlimg edit m htiverbosegroup m ctrltreeoptions add edit box m htiloglevel runtime class c num tree options edit m htidebug2disk m ctrltreeoptions insert check box get res string ids log2disk m htiverbosegroup m bdebug2disk m htidebugsourceexchange m ctrltreeoptions insert check box get res string ids debug source exchange m htiverbosegroup m bdebugsourceexchange m htilogbannedclients m ctrltreeoptions insert check box get res string ids log banned clients m htiverbosegroup m blogbannedclients m htilogratingdescreceived m ctrltreeoptions insert check box get res string ids log rating recv m htiverbosegroup m blogratingdescreceived m htilogsecureident m ctrltreeoptions insert check box get res string ids log secure ident m htiverbosegroup m blogsecureident m htilogfilteredips m ctrltreeoptions insert check box get res string ids log filtered ips m htiverbosegroup m blogfilteredips m htilogfilesaving m ctrltreeoptions insert check box get res string ids log file saving m htiverbosegroup m blogfilesaving m htiloga4af m ctrltreeoptions insert check box get res string ids log a4af m htiverbosegroup m bloga4af zz download manager m htiloguldlevents m ctrltreeoptions insert check box get res string ids log uldl events m htiverbosegroup m bloguldlevents uss group m htidynup m ctrltreeoptions insert group get res string ids dynup i img dynyp tvi root m htidynupenabled m ctrltreeoptions insert check box get res string ids dynupenabled m htidynup m bdynupenabled m htidynupminupload m ctrltreeoptions insert item get res string ids dynup minupload treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynupminupload runtime class c num tree options edit m htidynuppingtolerance m ctrltreeoptions insert item get res string ids dynup pingtolerance treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynuppingtolerance runtime class c num tree options edit m htidynuppingtolerancemilliseconds m ctrltreeoptions insert item get res string ids dynup pingtolerance ms treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynuppingtolerancemilliseconds runtime class c num tree options edit m htidynuppingtolerancegroup m ctrltreeoptions insert group get res string ids dynup radio pingtolerance header i img dynyp m htidynup m htidynupradiopingtolerance m ctrltreeoptions insert radio button get res string ids dynup radio pingtolerance percent m htidynuppingtolerancegroup m idynupradiopingtolerance 0 m htidynupradiopingtolerancemilliseconds m ctrltreeoptions insert radio button get res string ids dynup radio pingtolerance ms m htidynuppingtolerancegroup m idynupradiopingtolerance 1 m htidynupgoingupdivider m ctrltreeoptions insert item get res string ids dynup goingupdivider treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynupgoingupdivider runtime class c num tree options edit m htidynupgoingdowndivider m ctrltreeoptions insert item get res string ids dynup goingdowndivider treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynupgoingdowndivider runtime class c num tree options edit m htidynupnumberofpings m ctrltreeoptions insert item get res string ids dynup numberofpings treeoptsctrlimg edit treeoptsctrlimg edit m htidynup m ctrltreeoptions add edit box m htidynupnumberofpings runtime class c num tree options edit m ctrltreeoptions expand m htitcpgroup tve expand if m htiverbosegroup m ctrltreeoptions expand m htiverbosegroup tve expand m ctrltreeoptions expand m hticommit tve expand m ctrltreeoptions expand m hticheckdiskspace tve expand m ctrltreeoptions expand m htidynup tve expand m ctrltreeoptions expand m htidynuppingtolerancegroup tve expand m ctrltreeoptions expand m htiextractmetadata tve expand m ctrltreeoptions send message wm vscroll sb top m binitializedtreeopts true tcp ip group ddx treeedit pdx idc ext opts m htimaxcon5sec m imaxconnperfive ddv minmaxint pdx m imaxconnperfive 1 int max ddx treeedit cppgtweaks dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_filebuffersize m_ctlfilebuffsize ddx_control idc_queuesize m_ctlqueuesize ddx_control idc_ext_opts m_ctrltreeoptions m_binitializedtreeopts iimgbackup iimglog iimgdynyp iimgconnection iimga4af iimgmetadata cimagelist m_ctrltreeoptions getimagelist tvsil_normal iimgbackup ctempiconloader _t iimglog ctempiconloader _t iimgdynyp ctempiconloader _t iimgconnection ctempiconloader _t iimga4af ctempiconloader _t iimgmetadata ctempiconloader _t mediainfo m_htitcpgroup m_ctrltreeoptions insertgroup getresstring ids_tcpip_conns iimgconnection tvi_root m_htimaxcon5sec m_ctrltreeoptions insertitem getresstring ids_maxcon5seclabel treeoptsctrlimg_edit treeoptsctrlimg_edit m_htitcpgroup m_ctrltreeoptions addeditbox m_htimaxcon5sec runtime_class cnumtreeoptionsedit m_htimaxhalfopen m_ctrltreeoptions insertitem getresstring ids_maxhalfopencons treeoptsctrlimg_edit treeoptsctrlimg_edit m_htitcpgroup m_ctrltreeoptions addeditbox m_htimaxhalfopen runtime_class cnumtreeoptionsedit m_hticonditionaltcpaccept m_ctrltreeoptions insertcheckbox getresstring ids_condtcpaccept m_htitcpgroup m_bconditionaltcpaccept m_htiserverkeepalivetimeout m_ctrltreeoptions insertitem getresstring ids_serverkeepalivetimeout treeoptsctrlimg_edit treeoptsctrlimg_edit m_htitcpgroup m_ctrltreeoptions addeditbox m_htiserverkeepalivetimeout runtime_class cnumtreeoptionsedit m_htiautotakeed2klinks m_ctrltreeoptions insertcheckbox getresstring ids_autotakeed2klinks tvi_root m_bautotakeed2klinks m_hticreditsystem m_ctrltreeoptions insertcheckbox getresstring ids_usecreditsystem tvi_root m_bcreditsystem m_htifirewallstartup m_ctrltreeoptions insertcheckbox getresstring ids_fo_pref_startup tvi_root m_bfirewallstartup m_htifilterlanips m_ctrltreeoptions insertcheckbox getresstring ids_pw_filter tvi_root m_bfilterlanips m_htiextcontrols m_ctrltreeoptions insertcheckbox getresstring ids_showextsettings tvi_root m_bextcontrols m_htia4afsavecpu m_ctrltreeoptions insertcheckbox getresstring ids_a4af_save_cpu tvi_root m_ba4afsavecpu downloadmanager m_htiyourhostname m_ctrltreeoptions insertitem getresstring ids_yourhostname treeoptsctrlimg_edit treeoptsctrlimg_edit tvi_root m_ctrltreeoptions addeditbox m_htiyourhostname runtime_class ctreeoptionseditex m_htidisablepeercache m_ctrltreeoptions insertcheckbox getresstring ids_disablepeerache tvi_root m_bdisablepeercache m_htisparsepartfiles m_ctrltreeoptions insertcheckbox getresstring ids_sparsepartfiles tvi_root m_bsparsepartfiles m_htifullalloc m_ctrltreeoptions insertcheckbox getresstring ids_fullalloc tvi_root m_bfullalloc m_hticheckdiskspace m_ctrltreeoptions insertcheckbox getresstring ids_checkdiskspace tvi_root m_bcheckdiskspace m_htiminfreediskspace m_ctrltreeoptions insertitem getresstring ids_minfreediskspace treeoptsctrlimg_edit treeoptsctrlimg_edit m_hticheckdiskspace m_ctrltreeoptions addeditbox m_htiminfreediskspace runtime_class cnumtreeoptionsedit m_hticommit m_ctrltreeoptions insertgroup getresstring ids_commitfiles iimgbackup tvi_root m_hticommitnever m_ctrltreeoptions insertradiobutton getresstring ids_never m_hticommit m_icommitfiles m_hticommitonshutdown m_ctrltreeoptions insertradiobutton getresstring ids_onshutdown m_hticommit m_icommitfiles m_hticommitalways m_ctrltreeoptions insertradiobutton getresstring ids_always m_hticommit m_icommitfiles m_htiextractmetadata m_ctrltreeoptions insertgroup getresstring ids_extract_meta_data iimgmetadata tvi_root m_htiextractmetadatanever m_ctrltreeoptions insertradiobutton getresstring ids_never m_htiextractmetadata m_iextractmetadata m_htiextractmetadataid3lib m_ctrltreeoptions insertradiobutton getresstring ids_meta_data_id3lib m_htiextractmetadata m_iextractmetadata m_htiextractmetadatamediadet m_ctrltreeoptions insertradiobutton getresstring ids_meta_data_mediadet m_htiextractmetadata m_iextractmetadata m_htilog2disk m_ctrltreeoptions insertcheckbox getresstring ids_log2disk tvi_root m_blog2disk theprefs getenableverboseoptions m_htiverbosegroup m_ctrltreeoptions insertgroup getresstring ids_verbose iimglog tvi_root m_htiverbose m_ctrltreeoptions insertcheckbox getresstring ids_enabled m_htiverbosegroup m_bverbose m_htiloglevel m_ctrltreeoptions insertitem getresstring ids_log_level treeoptsctrlimg_edit treeoptsctrlimg_edit m_htiverbosegroup m_ctrltreeoptions addeditbox m_htiloglevel runtime_class cnumtreeoptionsedit m_htidebug2disk m_ctrltreeoptions insertcheckbox getresstring ids_log2disk m_htiverbosegroup m_bdebug2disk m_htidebugsourceexchange m_ctrltreeoptions insertcheckbox getresstring ids_debug_source_exchange m_htiverbosegroup m_bdebugsourceexchange m_htilogbannedclients m_ctrltreeoptions insertcheckbox getresstring ids_log_banned_clients m_htiverbosegroup m_blogbannedclients m_htilogratingdescreceived m_ctrltreeoptions insertcheckbox getresstring ids_log_rating_recv m_htiverbosegroup m_blogratingdescreceived m_htilogsecureident m_ctrltreeoptions insertcheckbox getresstring ids_log_secure_ident m_htiverbosegroup m_blogsecureident m_htilogfilteredips m_ctrltreeoptions insertcheckbox getresstring ids_log_filtered_ips m_htiverbosegroup m_blogfilteredips m_htilogfilesaving m_ctrltreeoptions insertcheckbox getresstring ids_log_file_saving m_htiverbosegroup m_blogfilesaving m_htiloga4af m_ctrltreeoptions insertcheckbox getresstring ids_log_a4af m_htiverbosegroup m_bloga4af downloadmanager m_htiloguldlevents m_ctrltreeoptions insertcheckbox getresstring ids_log_uldl_events m_htiverbosegroup m_bloguldlevents m_htidynup m_ctrltreeoptions insertgroup getresstring ids_dynup iimgdynyp tvi_root m_htidynupenabled m_ctrltreeoptions insertcheckbox getresstring ids_dynupenabled m_htidynup m_bdynupenabled m_htidynupminupload m_ctrltreeoptions insertitem getresstring ids_dynup_minupload treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynupminupload runtime_class cnumtreeoptionsedit m_htidynuppingtolerance m_ctrltreeoptions insertitem getresstring ids_dynup_pingtolerance treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynuppingtolerance runtime_class cnumtreeoptionsedit m_htidynuppingtolerancemilliseconds m_ctrltreeoptions insertitem getresstring ids_dynup_pingtolerance_ms treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynuppingtolerancemilliseconds runtime_class cnumtreeoptionsedit m_htidynuppingtolerancegroup m_ctrltreeoptions insertgroup getresstring ids_dynup_radio_pingtolerance_header iimgdynyp m_htidynup m_htidynupradiopingtolerance m_ctrltreeoptions insertradiobutton getresstring ids_dynup_radio_pingtolerance_percent m_htidynuppingtolerancegroup m_idynupradiopingtolerance m_htidynupradiopingtolerancemilliseconds m_ctrltreeoptions insertradiobutton getresstring ids_dynup_radio_pingtolerance_ms m_htidynuppingtolerancegroup m_idynupradiopingtolerance m_htidynupgoingupdivider m_ctrltreeoptions insertitem getresstring ids_dynup_goingupdivider treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynupgoingupdivider runtime_class cnumtreeoptionsedit m_htidynupgoingdowndivider m_ctrltreeoptions insertitem getresstring ids_dynup_goingdowndivider treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynupgoingdowndivider runtime_class cnumtreeoptionsedit m_htidynupnumberofpings m_ctrltreeoptions insertitem getresstring ids_dynup_numberofpings treeoptsctrlimg_edit treeoptsctrlimg_edit m_htidynup m_ctrltreeoptions addeditbox m_htidynupnumberofpings runtime_class cnumtreeoptionsedit m_ctrltreeoptions m_htitcpgroup tve_expand m_htiverbosegroup m_ctrltreeoptions m_htiverbosegroup tve_expand m_ctrltreeoptions m_hticommit tve_expand m_ctrltreeoptions m_hticheckdiskspace tve_expand m_ctrltreeoptions m_htidynup tve_expand m_ctrltreeoptions m_htidynuppingtolerancegroup tve_expand m_ctrltreeoptions m_htiextractmetadata tve_expand m_ctrltreeoptions sendmessage wm_vscroll sb_top m_binitializedtreeopts ddx_treeedit idc_ext_opts m_htimaxcon5sec m_imaxconnperfive ddv_minmaxint m_imaxconnperfive int_max ddx_treeedit bool cp pg tweaks on init dialog m imaxconnperfive the prefs get max conper five m imaxhalfopen the prefs get max half connections m bconditionaltcpaccept the prefs get conditionaltcp accept m bautotakeed2klinks have ed2k reg access the prefs auto takeed2k links 0 if the prefs get enable verbose options m bverbose the prefs m bverbose m bdebug2disk the prefs debug2disk do not use the according get function here m bdebugsourceexchange the prefs m bdebugsourceexchange do not use the according get function here m blogbannedclients the prefs m blogbannedclients do not use the according get function here m blogratingdescreceived the prefs m blogratingdescreceived do not use the according get function here m blogsecureident the prefs m blogsecureident do not use the according get function here m blogfilteredips the prefs m blogfilteredips do not use the according get function here m blogfilesaving the prefs m blogfilesaving do not use the according get function here m bloga4af the prefs m bloga4af do not use the according get function here zz download manager m bloguldlevents the prefs m bloguldlevents m iloglevel 5 the prefs m byloglevel m blog2disk the prefs log2disk m bcreditsystem the prefs m bcreditsystem m icommitfiles the prefs m icommitfiles m iextractmetadata the prefs m iextractmetadata m bfilterlanips the prefs filterlani ps m bextcontrols the prefs m bextcontrols m userverkeepalivetimeout the prefs m dwserverkeepalivetimeout 60000 m bsparsepartfiles the prefs m bsparsepartfiles m bfullalloc the prefs m ballocfull m bcheckdiskspace the prefs check diskspace m fminfreediskspacemb float the prefs m uminfreediskspace 1024 0 1024 0 m syourhostname the prefs get your hostname m bfirewallstartup the prefs get windows version winver xp the prefs m bopenportsonstartup 0 m bdisablepeercache the prefs m bpeercacheenabled m bdynupenabled the prefs m bdynupenabled m idynupminupload the prefs get min upload m idynuppingtolerance the prefs get dyn up ping tolerance m idynuppingtolerancemilliseconds the prefs get dyn up ping tolerance milliseconds m idynupradiopingtolerance the prefs is dyn up use millisecond ping tolerance 1 0 m idynupgoingupdivider the prefs get dyn up going up divider m idynupgoingdowndivider the prefs get dyn up going down divider m idynupnumberofpings the prefs get dyn up number of pings m ba4afsavecpu the prefs geta4af save cpu m ctrltreeoptions set image list color flags the app m idfltimagelistcolorflags c property page on init dialog init window styles this m ctrltreeoptions set item height m ctrltreeoptions get item height 2 m ifilebuffersize the prefs m ifilebuffersize m ctlfilebuffsize set range 16 1024 512 true int i min i max m ctlfilebuffsize get range i min i max m ctlfilebuffsize set pos m ifilebuffersize 1024 int i page 128 for int i i min i page 1 i page i page i i max i i page m ctlfilebuffsize set tic i m ctlfilebuffsize set page size i page m iqueuesize the prefs m iqueuesize m ctlqueuesize set range 20 100 true m ctlqueuesize set pos m iqueuesize 100 m ctlqueuesize set tic freq 10 m ctlqueuesize set page size 10 localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgtweaks oninitdialog m_imaxconnperfive theprefs getmaxconperfive m_imaxhalfopen theprefs getmaxhalfconnections m_bconditionaltcpaccept theprefs getconditionaltcpaccept m_bautotakeed2klinks haveed2kregaccess theprefs autotakeed2klinks theprefs getenableverboseoptions m_bverbose theprefs m_bverbose m_bdebug2disk theprefs m_bdebugsourceexchange theprefs m_bdebugsourceexchange m_blogbannedclients theprefs m_blogbannedclients m_blogratingdescreceived theprefs m_blogratingdescreceived m_blogsecureident theprefs m_blogsecureident m_blogfilteredips theprefs m_blogfilteredips m_blogfilesaving theprefs m_blogfilesaving m_bloga4af theprefs m_bloga4af downloadmanager m_bloguldlevents theprefs m_bloguldlevents m_iloglevel theprefs m_byloglevel m_blog2disk theprefs m_bcreditsystem theprefs m_bcreditsystem m_icommitfiles theprefs m_icommitfiles m_iextractmetadata theprefs m_iextractmetadata m_bfilterlanips theprefs filterlanips m_bextcontrols theprefs m_bextcontrols m_userverkeepalivetimeout theprefs m_dwserverkeepalivetimeout m_bsparsepartfiles theprefs m_bsparsepartfiles m_bfullalloc theprefs m_ballocfull m_bcheckdiskspace theprefs checkdiskspace m_fminfreediskspacemb theprefs m_uminfreediskspace m_syourhostname theprefs getyourhostname m_bfirewallstartup theprefs getwindowsversion _winver_xp_ theprefs m_bopenportsonstartup m_bdisablepeercache theprefs m_bpeercacheenabled m_bdynupenabled theprefs m_bdynupenabled m_idynupminupload theprefs getminupload m_idynuppingtolerance theprefs getdynuppingtolerance m_idynuppingtolerancemilliseconds theprefs getdynuppingtolerancemilliseconds m_idynupradiopingtolerance theprefs isdynupusemillisecondpingtolerance m_idynupgoingupdivider theprefs getdynupgoingupdivider m_idynupgoingdowndivider theprefs getdynupgoingdowndivider m_idynupnumberofpings theprefs getdynupnumberofpings m_ba4afsavecpu theprefs geta4afsavecpu m_ctrltreeoptions setimagelistcolorflags theapp m_idfltimagelistcolorflags cpropertypage oninitdialog initwindowstyles m_ctrltreeoptions setitemheight m_ctrltreeoptions getitemheight m_ifilebuffersize theprefs m_ifilebuffersize m_ctlfilebuffsize setrange imin imax m_ctlfilebuffsize getrange imin imax m_ctlfilebuffsize setpos m_ifilebuffersize ipage imin ipage ipage ipage imax ipage m_ctlfilebuffsize settic m_ctlfilebuffsize setpagesize ipage m_iqueuesize theprefs m_iqueuesize m_ctlqueuesize setrange m_ctlqueuesize setpos m_iqueuesize m_ctlqueuesize setticfreq m_ctlqueuesize setpagesize bool cp pg tweaks on apply if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus if update data return false the prefs set max cons per five m imaxconnperfive m imaxconnperfive dflt maxconperfive the app scheduler original cons5s the prefs get max conper five the prefs set max half connections m imaxhalfopen m imaxhalfopen dflt maxhalfopen the prefs m bconditionaltcpaccept m bconditionaltcpaccept if have ed2k reg access the prefs auto takeed2k links m bautotakeed2klinks the prefs autotakeed2klinks m bautotakeed2klinks if the prefs auto takeed2k links ask4 reg fix false true false else revert reg if the prefs log2disk m blog2disk the log open else if the prefs log2disk m blog2disk the log close the prefs log2disk m blog2disk if the prefs get enable verbose options if the prefs get debug2 disk m bverbose m bdebug2disk the verbose log open else if the prefs get debug2 disk m bverbose m bdebug2disk the verbose log close the prefs debug2disk m bdebug2disk the prefs m bdebugsourceexchange m bdebugsourceexchange the prefs m blogbannedclients m blogbannedclients the prefs m blogratingdescreceived m blogratingdescreceived the prefs m blogsecureident m blogsecureident the prefs m blogfilteredips m blogfilteredips the prefs m blogfilesaving m blogfilesaving the prefs m bloga4af m bloga4af the prefs m bloguldlevents m bloguldlevents the prefs m byloglevel 5 m iloglevel the prefs m bverbose m bverbose store after related options were stored the prefs m bcreditsystem m bcreditsystem the prefs m icommitfiles m icommitfiles the prefs m iextractmetadata m iextractmetadata the prefs filterlani ps m bfilterlanips the prefs m ifilebuffersize m ifilebuffersize the prefs m iqueuesize m iqueuesize if the prefs m bextcontrols m bextcontrols the prefs m bextcontrols m bextcontrols the app emuledlg transferwnd downloadlistctrl create menues the app emuledlg searchwnd create menus the app emuledlg sharedfileswnd sharedfilesctrl create menues the prefs m dwserverkeepalivetimeout m userverkeepalivetimeout 60000 the prefs m bsparsepartfiles m bsparsepartfiles the prefs m ballocfull m bfullalloc the prefs check diskspace m bcheckdiskspace the prefs m uminfreediskspace uint m fminfreediskspacemb 1024 1024 if the prefs get your hostname m syourhostname the prefs set your hostname m syourhostname the app emuledlg serverwnd update my info the prefs m bopenportsonstartup m bfirewallstartup the prefs m bpeercacheenabled m bdisablepeercache the prefs m bdynupenabled m bdynupenabled the prefs minupload uint16 m idynupminupload the prefs m idynuppingtolerance m idynuppingtolerance the prefs m idynuppingtolerancemilliseconds m idynuppingtolerancemilliseconds the prefs m bdynupusemillisecondpingtolerance m idynupradiopingtolerance 1 the prefs m idynupgoingupdivider m idynupgoingupdivider the prefs m idynupgoingdowndivider m idynupgoingdowndivider the prefs m idynupnumberofpings m idynupnumberofpings the prefs m ba4afsavecpu m ba4afsavecpu if the prefs get enable verbose options the app emuledlg serverwnd toggle debug window the app emuledlg serverwnd update log tab selection the app downloadqueue check diskspace set modified false return c property page on apply cppgtweaks onapply m_ctrltreeoptions handlechildcontrollosingfocus updatedata theprefs setmaxconsperfive m_imaxconnperfive m_imaxconnperfive dflt_maxconperfive theapp original_cons5s theprefs getmaxconperfive theprefs setmaxhalfconnections m_imaxhalfopen m_imaxhalfopen dflt_maxhalfopen theprefs m_bconditionaltcpaccept m_bconditionaltcpaccept haveed2kregaccess theprefs autotakeed2klinks m_bautotakeed2klinks theprefs m_bautotakeed2klinks theprefs autotakeed2klinks ask4regfix revertreg theprefs m_blog2disk thelog theprefs m_blog2disk thelog theprefs m_blog2disk theprefs getenableverboseoptions theprefs getdebug2disk m_bverbose m_bdebug2disk theverboselog theprefs getdebug2disk m_bverbose m_bdebug2disk theverboselog theprefs m_bdebug2disk theprefs m_bdebugsourceexchange m_bdebugsourceexchange theprefs m_blogbannedclients m_blogbannedclients theprefs m_blogratingdescreceived m_blogratingdescreceived theprefs m_blogsecureident m_blogsecureident theprefs m_blogfilteredips m_blogfilteredips theprefs m_blogfilesaving m_blogfilesaving theprefs m_bloga4af m_bloga4af theprefs m_bloguldlevents m_bloguldlevents theprefs m_byloglevel m_iloglevel theprefs m_bverbose m_bverbose theprefs m_bcreditsystem m_bcreditsystem theprefs m_icommitfiles m_icommitfiles theprefs m_iextractmetadata m_iextractmetadata theprefs filterlanips m_bfilterlanips theprefs m_ifilebuffersize m_ifilebuffersize theprefs m_iqueuesize m_iqueuesize theprefs m_bextcontrols m_bextcontrols theprefs m_bextcontrols m_bextcontrols theapp createmenues theapp createmenus theapp createmenues theprefs m_dwserverkeepalivetimeout m_userverkeepalivetimeout theprefs m_bsparsepartfiles m_bsparsepartfiles theprefs m_ballocfull m_bfullalloc theprefs checkdiskspace m_bcheckdiskspace theprefs m_uminfreediskspace m_fminfreediskspacemb theprefs getyourhostname m_syourhostname theprefs setyourhostname m_syourhostname theapp updatemyinfo theprefs m_bopenportsonstartup m_bfirewallstartup theprefs m_bpeercacheenabled m_bdisablepeercache theprefs m_bdynupenabled m_bdynupenabled theprefs m_idynupminupload theprefs m_idynuppingtolerance m_idynuppingtolerance theprefs m_idynuppingtolerancemilliseconds m_idynuppingtolerancemilliseconds theprefs m_bdynupusemillisecondpingtolerance m_idynupradiopingtolerance theprefs m_idynupgoingupdivider m_idynupgoingupdivider theprefs m_idynupgoingdowndivider m_idynupgoingdowndivider theprefs m_idynupnumberofpings m_idynupnumberofpings theprefs m_ba4afsavecpu m_ba4afsavecpu theprefs getenableverboseoptions theapp toggledebugwindow theapp updatelogtabselection theapp checkdiskspace setmodified cpropertypage onapply bool cp pg tweaks on kill active if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus return c property page on kill active cppgtweaks onkillactive m_ctrltreeoptions handlechildcontrollosingfocus cpropertypage onkillactive bool cp pg tweaks on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgtweaks oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg tweaks onh scroll uint nsb code uint n pos c scroll bar p scroll bar if p scroll bar get safe hwnd m ctlfilebuffsize m hwnd m ifilebuffersize m ctlfilebuffsize get pos 1024 c string temp temp format t s s get res string ids filebuffersize cast itox bytes m ifilebuffersize false false get dlg item idc filebuffersize static set window text temp set modified true else if p scroll bar get safe hwnd m ctlqueuesize m hwnd m iqueuesize c slider ctrl p scroll bar get pos 100 c string temp temp format t s s get res string ids queuesize get formatedu int m iqueuesize get dlg item idc queuesize static set window text temp set modified true cppgtweaks onhscroll nsbcode npos cscrollbar pscrollbar pscrollbar getsafehwnd m_ctlfilebuffsize m_hwnd m_ifilebuffersize m_ctlfilebuffsize getpos cstring _t getresstring ids_filebuffersize castitoxbytes m_ifilebuffersize getdlgitem idc_filebuffersize_static setwindowtext setmodified pscrollbar getsafehwnd m_ctlqueuesize m_hwnd m_iqueuesize csliderctrl pscrollbar getpos cstring _t getresstring ids_queuesize getformateduint m_iqueuesize getdlgitem idc_queuesize_static setwindowtext setmodified void cp pg tweaks on destroy m ctrltreeoptions delete all items m ctrltreeoptions destroy window m binitializedtreeopts false m htitcpgroup null m htimaxcon5sec null m htimaxhalfopen null m hticonditionaltcpaccept null m htiautotakeed2klinks null m htiverbosegroup null m htiverbose null m htidebugsourceexchange null m htilogbannedclients null m htilogratingdescreceived null m htilogsecureident null m htilogfilteredips null m htilogfilesaving null m htiloga4af null m htiloglevel null m htiloguldlevents null m hticreditsystem null m htilog2disk null m htidebug2disk null m hticommit null m hticommitnever null m hticommitonshutdown null m hticommitalways null m htifilterlanips null m htiextcontrols null m htiserverkeepalivetimeout null m htisparsepartfiles null m htifullalloc null m hticheckdiskspace null m htiminfreediskspace null m htiyourhostname null m htifirewallstartup null m htidisablepeercache null m htidynup null m htidynupenabled null m htidynupminupload null m htidynuppingtolerance null m htidynuppingtolerancemilliseconds null m htidynuppingtolerancegroup null m htidynupradiopingtolerance null m htidynupradiopingtolerancemilliseconds null m htidynupgoingupdivider null m htidynupgoingdowndivider null m htidynupnumberofpings null m htia4afsavecpu null m htiextractmetadata null m htiextractmetadatanever null m htiextractmetadataid3lib null m htiextractmetadatamediadet null c property page on destroy cppgtweaks ondestroy m_ctrltreeoptions deleteallitems m_ctrltreeoptions destroywindow m_binitializedtreeopts m_htitcpgroup m_htimaxcon5sec m_htimaxhalfopen m_hticonditionaltcpaccept m_htiautotakeed2klinks m_htiverbosegroup m_htiverbose m_htidebugsourceexchange m_htilogbannedclients m_htilogratingdescreceived m_htilogsecureident m_htilogfilteredips m_htilogfilesaving m_htiloga4af m_htiloglevel m_htiloguldlevents m_hticreditsystem m_htilog2disk m_htidebug2disk m_hticommit m_hticommitnever m_hticommitonshutdown m_hticommitalways m_htifilterlanips m_htiextcontrols m_htiserverkeepalivetimeout m_htisparsepartfiles m_htifullalloc m_hticheckdiskspace m_htiminfreediskspace m_htiyourhostname m_htifirewallstartup m_htidisablepeercache m_htidynup m_htidynupenabled m_htidynupminupload m_htidynuppingtolerance m_htidynuppingtolerancemilliseconds m_htidynuppingtolerancegroup m_htidynupradiopingtolerance m_htidynupradiopingtolerancemilliseconds m_htidynupgoingupdivider m_htidynupgoingdowndivider m_htidynupnumberofpings m_htia4afsavecpu m_htiextractmetadata m_htiextractmetadatanever m_htiextractmetadataid3lib m_htiextractmetadatamediadet cpropertypage ondestroy lresult cp pg tweaks on tree opts ctrl notify wparam w param lparam l param if w param idc ext opts treeoptsctrlnotify pton treeoptsctrlnotify l param if m htiverbose pton h item m htiverbose bool b check if m ctrltreeoptions get check box m htiverbose b check if m htidebug2disk m ctrltreeoptions set check box enable m htidebug2disk b check if m htidebugsourceexchange m ctrltreeoptions set check box enable m htidebugsourceexchange b check if m htilogbannedclients m ctrltreeoptions set check box enable m htilogbannedclients b check if m htilogratingdescreceived m ctrltreeoptions set check box enable m htilogratingdescreceived b check if m htilogsecureident m ctrltreeoptions set check box enable m htilogsecureident b check if m htilogfilteredips m ctrltreeoptions set check box enable m htilogfilteredips b check if m htilogfilesaving m ctrltreeoptions set check box enable m htilogfilesaving b check if m htiloga4af m ctrltreeoptions set check box enable m htiloga4af b check if m htiloguldlevents m ctrltreeoptions set check box enable m htiloguldlevents b check set modified return 0 cppgtweaks ontreeoptsctrlnotify wparam lparam wparam idc_ext_opts lparam m_htiverbose hitem m_htiverbose bcheck m_ctrltreeoptions getcheckbox m_htiverbose bcheck m_htidebug2disk m_ctrltreeoptions setcheckboxenable m_htidebug2disk bcheck m_htidebugsourceexchange m_ctrltreeoptions setcheckboxenable m_htidebugsourceexchange bcheck m_htilogbannedclients m_ctrltreeoptions setcheckboxenable m_htilogbannedclients bcheck m_htilogratingdescreceived m_ctrltreeoptions setcheckboxenable m_htilogratingdescreceived bcheck m_htilogsecureident m_ctrltreeoptions setcheckboxenable m_htilogsecureident bcheck m_htilogfilteredips m_ctrltreeoptions setcheckboxenable m_htilogfilteredips bcheck m_htilogfilesaving m_ctrltreeoptions setcheckboxenable m_htilogfilesaving bcheck m_htiloga4af m_ctrltreeoptions setcheckboxenable m_htiloga4af bcheck m_htiloguldlevents m_ctrltreeoptions setcheckboxenable m_htiloguldlevents bcheck setmodified void cp pg tweaks on help the app show help emule faq preferences extended settings cppgtweaks onhelp theapp showhelp emule_faq_preferences_extended_settings bool cp pg tweaks on help info helpinfo p help info on help return true cppgtweaks onhelpinfo phelpinfo onhelp c property page cp pg display idd m eselectfont sf server cpropertypage cppgdisplay m_eselectfont sfserver cp pg display cp pg display cppgdisplay cppgdisplay void cp pg display localize void if m hwnd set window text get res string ids pw display get dlg item idc mintray set window text get res string ids pw tray get dlg item idc dblclick set window text get res string ids pw dblclick get dlg item idc tooltipdelay lbl set window text get res string ids pw tool get dlg item idc 3ddep set window text get res string ids 3ddep get dlg item idc flat set window text get res string ids flat get dlg item idc round set window text get res string ids round get dlg item idc updatequeue set window text get res string ids updatequeue get dlg item idc showrateontitle set window text get res string ids showrateontitle get dlg item idc indicateratings set window text get res string ids indicateratings get dlg item idc disableknownlist set window text get res string ids disableknownlist get dlg item idc disablequeuelist set window text get res string ids disablequeuelist get dlg item idc static cpumem set window text get res string ids static cpumem get dlg item idc showcatinfo set window text get res string ids showcatinfo get dlg item idc repaint set window text get res string ids repaintgraphs set dlg item text idc hypertext font hint get res string ids hypertext font hint set dlg item text idc select hypertext font get res string ids select font t set dlg item text idc showdwlpercent get res string ids showdwlpercentage get dlg item idc clearcompl set window text get res string ids autoremovefd get dlg item idc resetlabel set window text get res string ids resetlabel get dlg item idc resethist set window text get res string ids pw reset get dlg item idc disablehist set window text get res string ids enabled get dlg item idc showtranstoolbar set window text get res string ids pw showtranstoolbar cppgdisplay m_hwnd setwindowtext getresstring ids_pw_display getdlgitem idc_mintray setwindowtext getresstring ids_pw_tray getdlgitem idc_dblclick setwindowtext getresstring ids_pw_dblclick getdlgitem idc_tooltipdelay_lbl setwindowtext getresstring ids_pw_tool getdlgitem idc_3ddep setwindowtext getresstring ids_3ddep getdlgitem idc_flat setwindowtext getresstring ids_flat getdlgitem idc_round setwindowtext getresstring ids_round getdlgitem idc_updatequeue setwindowtext getresstring ids_updatequeue getdlgitem idc_showrateontitle setwindowtext getresstring ids_showrateontitle getdlgitem idc_indicateratings setwindowtext getresstring ids_indicateratings getdlgitem idc_disableknownlist setwindowtext getresstring ids_disableknownlist getdlgitem idc_disablequeuelist setwindowtext getresstring ids_disablequeuelist getdlgitem idc_static_cpumem setwindowtext getresstring ids_static_cpumem getdlgitem idc_showcatinfo setwindowtext getresstring ids_showcatinfo getdlgitem idc_repaint setwindowtext getresstring ids_repaintgraphs setdlgitemtext idc_hypertext_font_hint getresstring ids_hypertext_font_hint setdlgitemtext idc_select_hypertext_font getresstring ids_select_font _t setdlgitemtext idc_showdwlpercent getresstring ids_showdwlpercentage getdlgitem idc_clearcompl setwindowtext getresstring ids_autoremovefd getdlgitem idc_resetlabel setwindowtext getresstring ids_resetlabel getdlgitem idc_resethist setwindowtext getresstring ids_pw_reset getdlgitem idc_disablehist setwindowtext getresstring ids_enabled getdlgitem idc_showtranstoolbar setwindowtext getresstring ids_pw_showtranstoolbar void cp pg display load settings void if the prefs mintotray check dlg button idc mintray 1 else check dlg button idc mintray 0 if the prefs transfer doubleclick check dlg button idc dblclick 1 else check dlg button idc dblclick 0 if the prefs indicateratings check dlg button idc indicateratings 1 else check dlg button idc indicateratings 0 if the prefs show rates in title check dlg button idc showrateontitle 1 else check dlg button idc showrateontitle 0 if the prefs m bupdatequeuelist check dlg button idc updatequeue 0 else check dlg button idc updatequeue 1 if the prefs m bdisableknownclientlist check dlg button idc disableknownlist 1 else check dlg button idc disableknownlist 0 if the prefs m bdisablequeuelist check dlg button idc disablequeuelist 1 else check dlg button idc disablequeuelist 0 check dlg button idc showcatinfo uint the prefs show cat tab infos check dlg button idc repaint uint the prefs is graph recreate disabled check dlg button idc showdwlpercent uint the prefs get use dwl percentage check dlg button idc clearcompl uint8 the prefs get remove finished downloads check dlg button idc showtranstoolbar uint8 the prefs is trans toolbar enabled check dlg button idc disablehist uint8 the prefs get use autocompletion c string str buffer str buffer format t u the prefs m itooldelaytime get dlg item idc tooltipdelay set window text str buffer cppgdisplay loadsettings theprefs checkdlgbutton idc_mintray checkdlgbutton idc_mintray theprefs transferdoubleclick checkdlgbutton idc_dblclick checkdlgbutton idc_dblclick theprefs checkdlgbutton idc_indicateratings checkdlgbutton idc_indicateratings theprefs showratesintitle checkdlgbutton idc_showrateontitle checkdlgbutton idc_showrateontitle theprefs m_bupdatequeuelist checkdlgbutton idc_updatequeue checkdlgbutton idc_updatequeue theprefs m_bdisableknownclientlist checkdlgbutton idc_disableknownlist checkdlgbutton idc_disableknownlist theprefs m_bdisablequeuelist checkdlgbutton idc_disablequeuelist checkdlgbutton idc_disablequeuelist checkdlgbutton idc_showcatinfo theprefs showcattabinfos checkdlgbutton idc_repaint theprefs isgraphrecreatedisabled checkdlgbutton idc_showdwlpercent theprefs getusedwlpercentage checkdlgbutton idc_clearcompl theprefs getremovefinisheddownloads checkdlgbutton idc_showtranstoolbar theprefs istranstoolbarenabled checkdlgbutton idc_disablehist theprefs getuseautocompletion cstring strbuffer strbuffer _t theprefs m_itooldelaytime getdlgitem idc_tooltipdelay setwindowtext strbuffer void cp pg display draw preview int dep c slider ctrl get dlg item idc 3ddepth get pos m 3dpreview set slider pos dep cppgdisplay drawpreview csliderctrl getdlgitem idc_3ddepth getpos m_3dpreview setsliderpos void cp pg display do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc preview m 3dpreview cppgdisplay dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_preview m_3dpreview bool cp pg display on init dialog c property page on init dialog init window styles this barry controls depth of 3d colour shading c slider ctrl slider3d c slider ctrl get dlg item idc 3ddepth slider3d set range 0 5 true slider3d set pos the prefs get3d depth slider3d set tic freq 1 draw preview load settings localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgdisplay oninitdialog cpropertypage oninitdialog initwindowstyles csliderctrl csliderctrl getdlgitem idc_3ddepth setrange setpos theprefs get3ddepth setticfreq drawpreview loadsettings bool cp pg display on apply tchar buffer 510 bool mintotray old the prefs mintotray the prefs mintotray is dlg button checked idc mintray 0 the prefs transfer doubleclick is dlg button checked idc dblclick 0 the prefs depth3d c slider ctrl get dlg item idc 3ddepth get pos the prefs indicateratings is dlg button checked idc indicateratings 0 the prefs dont recreate graphs is dlg button checked idc repaint 0 the prefs m bshowdwlpercentage is dlg button checked idc showdwlpercent 0 the prefs m bremovefinisheddownloads is dlg button checked idc clearcompl 0 the prefs m buseautocompl is dlg button checked idc disablehist 0 if is dlg button checked idc updatequeue the prefs m bupdatequeuelist false else the prefs m bupdatequeuelist true if is dlg button checked idc showrateontitle the prefs show rates in title true else the prefs show rates in title false bool flag the prefs m bdisableknownclientlist bool b reset toolbar false b reset toolbar is dlg button checked idc disableknownlist 0 the prefs m bdisableknownclientlist if is dlg button checked idc disableknownlist the prefs m bdisableknownclientlist true else the prefs m bdisableknownclientlist false the prefs show cat tab infos is dlg button checked idc showcatinfo 0 if the prefs show cat tab infos the app emuledlg transferwnd update cat tab titles if flag the prefs m bdisableknownclientlist if flag the app emuledlg transferwnd clientlistctrl delete all items the app emuledlg transferwnd switch upload list else the app emuledlg transferwnd clientlistctrl show known clients flag the prefs m bdisablequeuelist b reset toolbar is dlg button checked idc disablequeuelist 0 the prefs m bdisablequeuelist if is dlg button checked idc disablequeuelist the prefs m bdisablequeuelist true else the prefs m bdisablequeuelist false if flag the prefs m bdisablequeuelist if flag the app emuledlg transferwnd queuelistctrl delete all items the app emuledlg transferwnd switch upload list else the app emuledlg transferwnd queuelistctrl show queue clients get dlg item idc tooltipdelay get window text buffer 20 if tstoi buffer 32 the prefs m itooldelaytime 32 else the prefs m itooldelaytime tstoi buffer the app emuledlg transferwnd set tool tips delay the prefs get tool tip delay 1000 the app emuledlg searchwnd set tool tips delay the prefs get tool tip delay 1000 the app emuledlg transferwnd downloadlistctrl set style if is dlg button checked idc showtranstoolbar 0 the prefs is trans toolbar enabled the prefs m bwinatranstoolbar the prefs m bwinatranstoolbar the app emuledlg transferwnd reset trans toolbar the prefs m bwinatranstoolbar else if is dlg button checked idc showtranstoolbar 0 b reset toolbar the app emuledlg transferwnd reset trans toolbar the prefs m bwinatranstoolbar load settings if mintotray old the prefs mintotray the app emuledlg tray minimize to tray change if the prefs show rates on title stprintf buffer t e mule v s the app m strcurversionlong the app emuledlg set window text buffer set modified false return c property page on apply cppgdisplay onapply mintotray_old theprefs theprefs isdlgbuttonchecked idc_mintray theprefs transferdoubleclick isdlgbuttonchecked idc_dblclick theprefs csliderctrl getdlgitem idc_3ddepth getpos theprefs isdlgbuttonchecked idc_indicateratings theprefs dontrecreategraphs isdlgbuttonchecked idc_repaint theprefs m_bshowdwlpercentage isdlgbuttonchecked idc_showdwlpercent theprefs m_bremovefinisheddownloads isdlgbuttonchecked idc_clearcompl theprefs m_buseautocompl isdlgbuttonchecked idc_disablehist isdlgbuttonchecked idc_updatequeue theprefs m_bupdatequeuelist theprefs m_bupdatequeuelist isdlgbuttonchecked idc_showrateontitle theprefs showratesintitle theprefs showratesintitle theprefs m_bdisableknownclientlist bresettoolbar bresettoolbar isdlgbuttonchecked idc_disableknownlist theprefs m_bdisableknownclientlist isdlgbuttonchecked idc_disableknownlist theprefs m_bdisableknownclientlist theprefs m_bdisableknownclientlist theprefs showcattabinfos isdlgbuttonchecked idc_showcatinfo theprefs showcattabinfos theapp updatecattabtitles theprefs m_bdisableknownclientlist theapp deleteallitems theapp switchuploadlist theapp showknownclients theprefs m_bdisablequeuelist bresettoolbar isdlgbuttonchecked idc_disablequeuelist theprefs m_bdisablequeuelist isdlgbuttonchecked idc_disablequeuelist theprefs m_bdisablequeuelist theprefs m_bdisablequeuelist theprefs m_bdisablequeuelist theapp deleteallitems theapp switchuploadlist theapp showqueueclients getdlgitem idc_tooltipdelay getwindowtext _tstoi theprefs m_itooldelaytime theprefs m_itooldelaytime _tstoi theapp settooltipsdelay theprefs gettooltipdelay theapp settooltipsdelay theprefs gettooltipdelay theapp setstyle isdlgbuttonchecked idc_showtranstoolbar theprefs istranstoolbarenabled theprefs m_bwinatranstoolbar theprefs m_bwinatranstoolbar theapp resettranstoolbar theprefs m_bwinatranstoolbar isdlgbuttonchecked idc_showtranstoolbar bresettoolbar theapp resettranstoolbar theprefs m_bwinatranstoolbar loadsettings mintotray_old theprefs theapp trayminimizetotraychange theprefs showratesontitle _stprintf _t emule theapp m_strcurversionlong theapp setwindowtext setmodified cpropertypage onapply bool cp pg display on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgdisplay oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam uint callback cp pg display choose font hook hwnd hdlg uint ui msg wparam w param lparam l param uint u result call mfc s common dialog hook function if pfnchoosefonthook null u result pfnchoosefonthook hdlg ui msg w param l param else u result 0 do our own hook processing switch ui msg case wm command if loword w param psh3 apply hiword w param bn clicked logfont lf c font dialog p dlg c font dialog c wnd from handle hdlg assert p dlg null if p dlg null p dlg get current font lf if pthis m eselectfont sf log the app emuledlg apply log font lf else the app emuledlg apply hyper text font lf break if the hook procedure returns zero the default dialog box procedure processes the message return u result cppgdisplay choosefonthook uimsg wparam lparam uresult _pfnchoosefonthook uresult _pfnchoosefonthook uimsg wparam lparam uresult uimsg wm_command wparam wparam bn_clicked cfontdialog pdlg cfontdialog cwnd fromhandle pdlg pdlg pdlg getcurrentfont _pthis m_eselectfont sflog theapp applylogfont theapp applyhypertextfont uresult void cp pg display onh scroll uint nsb code uint n pos c scroll bar p scroll bar set modified true update data false c property page onh scroll nsb code n pos p scroll bar draw preview cppgdisplay onhscroll nsbcode npos cscrollbar pscrollbar setmodified updatedata cpropertypage onhscroll nsbcode npos pscrollbar drawpreview void cp pg display on bn clicked select hypertext font if get async key state vk control 0 m eselectfont sf log else m eselectfont sf server get current font description c font p font if m eselectfont sf log p font the app m fontlog else p font the app m fonthypertext logfont lf if p font null p font get object sizeof logfont lf else get object get stock object default gui font sizeof logfont lf initialize c font dialog c font dialog dlg lf cf screenfonts cf inittologfontstruct dlg m cf flags cf apply cf enablehook set lpfn hook to our own hook function but save mfc s hook pfnchoosefonthook dlg m cf lpfn hook dlg m cf lpfn hook choose font hook pthis this if dlg do modal idok if m eselectfont sf log the app emuledlg apply log font lf else the app emuledlg apply hyper text font lf pfnchoosefonthook null pthis null cppgdisplay onbnclickedselecthypertextfont getasynckeystate vk_control m_eselectfont sflog m_eselectfont sfserver cfont pfont m_eselectfont sflog pfont theapp m_fontlog pfont theapp m_fonthypertext pfont pfont getobject getobject getstockobject default_gui_font cfontdialog cfontdialog cf_screenfonts cf_inittologfontstruct m_cf cf_apply cf_enablehook lpfnhook _pfnchoosefonthook m_cf lpfnhook m_cf lpfnhook choosefonthook _pthis domodal m_eselectfont sflog theapp applylogfont theapp applyhypertextfont _pfnchoosefonthook _pthis void cp pg display on btn clicked reset hist the app emuledlg searchwnd reset history the app emuledlg serverwnd reset history cppgdisplay onbtnclickedresethist theapp resethistory theapp resethistory void cp pg display on help the app show help emule faq preferences display cppgdisplay onhelp theapp showhelp emule_faq_preferences_display bool cp pg display on help info helpinfo p help info on help return true cppgdisplay onhelpinfo phelpinfo onhelp c property page cp pg security idd m pacipfilterurl null cpropertypage cppgsecurity m_pacipfilterurl cp pg security cp pg security cppgsecurity cppgsecurity void cp pg security localize void if m hwnd set window text get res string ids security get dlg item idc static ipfilter set window text get res string ids ipfilter get dlg item idc reloadfilter set window text get res string ids sf reload get dlg item idc editfilter set window text get res string ids edit get dlg item idc static filterlevel set window text get res string ids filterlevel t get dlg item idc filterserverbyipfilter set window text get res string ids filterserverbyipfilter get dlg item idc filtercommentslabel set window text get res string ids filtercommentslabel get dlg item idc static comments set window text get res string ids comment get dlg item idc filterlabel set window text get res string ids filterlabel get dlg item idc msg set window text get res string ids cw messages get dlg item idc msgonlyfriends set window text get res string ids msgonlyfriends get dlg item idc msgonlysec set window text get res string ids msgonlysec get dlg item idc advspamfilter set window text get res string ids advspamfilter get dlg item idc sec misc set window text get res string ids pw misc get dlg item idc usesecident set window text get res string ids usesecident set dlg item text idc static updatefrom get res string ids updatefrom set dlg item text idc loadurl get res string ids loadurl set dlg item text idc runasuser get res string ids runasuser cppgsecurity m_hwnd setwindowtext getresstring ids_security getdlgitem idc_static_ipfilter setwindowtext getresstring ids_ipfilter getdlgitem idc_reloadfilter setwindowtext getresstring ids_sf_reload getdlgitem idc_editfilter setwindowtext getresstring ids_edit getdlgitem idc_static_filterlevel setwindowtext getresstring ids_filterlevel _t getdlgitem idc_filterserverbyipfilter setwindowtext getresstring ids_filterserverbyipfilter getdlgitem idc_filtercommentslabel setwindowtext getresstring ids_filtercommentslabel getdlgitem idc_static_comments setwindowtext getresstring ids_comment getdlgitem idc_filterlabel setwindowtext getresstring ids_filterlabel getdlgitem idc_msg setwindowtext getresstring ids_cw_messages getdlgitem idc_msgonlyfriends setwindowtext getresstring ids_msgonlyfriends getdlgitem idc_msgonlysec setwindowtext getresstring ids_msgonlysec getdlgitem idc_advspamfilter setwindowtext getresstring ids_advspamfilter getdlgitem idc_sec_misc setwindowtext getresstring ids_pw_misc getdlgitem idc_usesecident setwindowtext getresstring ids_usesecident setdlgitemtext idc_static_updatefrom getresstring ids_updatefrom setdlgitemtext idc_loadurl getresstring ids_loadurl setdlgitemtext idc_runasuser getresstring ids_runasuser void cp pg security deleteddb if m pacipfilterurl m pacipfilterurl save list the prefs get config dir ipfilterupdateurl strings profile m pacipfilterurl unbind m pacipfilterurl release m pacipfilterurl null cppgsecurity m_pacipfilterurl m_pacipfilterurl savelist theprefs getconfigdir ipfilterupdateurl_strings_profile m_pacipfilterurl m_pacipfilterurl m_pacipfilterurl void cp pg security load settings void c string str buffer str buffer format t i the prefs filterlevel get dlg item idc filterlevel set window text str buffer if the prefs filterserverbyip check dlg button idc filterserverbyipfilter 1 else check dlg button idc filterserverbyipfilter 0 if the prefs msgonlyfriends check dlg button idc msgonlyfriends 1 else check dlg button idc msgonlyfriends 0 if the prefs msgsecure check dlg button idc msgonlysec 1 else check dlg button idc msgonlysec 0 if the prefs m badvancedspamfilter check dlg button idc advspamfilter 1 else check dlg button idc advspamfilter 0 if the prefs m busesecureident check dlg button idc usesecident 1 else check dlg button idc usesecident 0 if the prefs get windows version winver xp the prefs get windows version winver 2k get dlg item idc runasuser enable window true else get dlg item idc runasuser enable window false if the prefs is run as user enabled check dlg button idc runasuser 1 else check dlg button idc runasuser 0 get dlg item idc filter set window text the prefs message filter get dlg item idc commentfilter set window text the prefs comment filter cppgsecurity loadsettings cstring strbuffer strbuffer _t theprefs getdlgitem idc_filterlevel setwindowtext strbuffer theprefs checkdlgbutton idc_filterserverbyipfilter checkdlgbutton idc_filterserverbyipfilter theprefs checkdlgbutton idc_msgonlyfriends checkdlgbutton idc_msgonlyfriends theprefs checkdlgbutton idc_msgonlysec checkdlgbutton idc_msgonlysec theprefs m_badvancedspamfilter checkdlgbutton idc_advspamfilter checkdlgbutton idc_advspamfilter theprefs m_busesecureident checkdlgbutton idc_usesecident checkdlgbutton idc_usesecident theprefs getwindowsversion _winver_xp_ theprefs getwindowsversion _winver_2k_ getdlgitem idc_runasuser enablewindow getdlgitem idc_runasuser enablewindow theprefs isrunasuserenabled checkdlgbutton idc_runasuser checkdlgbutton idc_runasuser getdlgitem idc_filter setwindowtext theprefs messagefilter getdlgitem idc_commentfilter setwindowtext theprefs commentfilter void cp pg security do data exchange c data exchange pdx c property page do data exchange pdx cppgsecurity dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg security on init dialog c property page on init dialog init window styles this load settings localize if the prefs get use autocompletion if m pacipfilterurl m pacipfilterurl new c custom auto complete m pacipfilterurl add ref if m pacipfilterurl bind get dlg item m hwnd idc updateurl aco updownkeydropslist aco autosuggest aco filterprefixes m pacipfilterurl load list the prefs get config dir ipfilterupdateurl strings profile set dlg item text idc updateurl m pacipfilterurl get item 0 if the app m fontsymbol m hobject get dlg item idc dd set font the app m fontsymbol get dlg item idc dd set window text t 6 show a down arrow else get dlg item idc dd show window sw hide return true return true unless you set the focus to a control exception ocx property pages should return false cppgsecurity oninitdialog cpropertypage oninitdialog initwindowstyles loadsettings theprefs getuseautocompletion m_pacipfilterurl m_pacipfilterurl ccustomautocomplete m_pacipfilterurl addref m_pacipfilterurl getdlgitem m_hwnd idc_updateurl aco_updownkeydropslist aco_autosuggest aco_filterprefixes m_pacipfilterurl loadlist theprefs getconfigdir ipfilterupdateurl_strings_profile setdlgitemtext idc_updateurl m_pacipfilterurl getitem theapp m_fontsymbol m_hobject getdlgitem idc_dd setfont theapp m_fontsymbol getdlgitem idc_dd setwindowtext _t getdlgitem idc_dd showwindow sw_hide bool cp pg security on apply tchar buffer 510 if get dlg item idc filterlevel get window text length get dlg item idc filterlevel get window text buffer 4 the prefs filterlevel tstoi buffer the prefs filterserverbyip is dlg button checked idc filterserverbyipfilter 0 the prefs msgonlyfriends is dlg button checked idc msgonlyfriends 0 the prefs msgsecure is dlg button checked idc msgonlysec 0 the prefs m badvancedspamfilter is dlg button checked idc advspamfilter 0 the prefs m busesecureident is dlg button checked idc usesecident 0 the prefs m brunasuser is dlg button checked idc runasuser 0 get dlg item idc filter get window text the prefs message filter c string str comment filters get dlg item idc commentfilter get window text str comment filters str comment filters make lower c string str new comment filters int cur pos 0 c string str filter str comment filters tokenize t cur pos while str filter is empty str filter trim if str new comment filters is empty str new comment filters t str new comment filters str filter str filter str comment filters tokenize t cur pos the prefs comment filter str new comment filters if the prefs comment filter str comment filters set dlg item text idc commentfilter the prefs comment filter load settings set modified false return c property page on apply cppgsecurity onapply getdlgitem idc_filterlevel getwindowtextlength getdlgitem idc_filterlevel getwindowtext theprefs _tstoi theprefs isdlgbuttonchecked idc_filterserverbyipfilter theprefs isdlgbuttonchecked idc_msgonlyfriends theprefs isdlgbuttonchecked idc_msgonlysec theprefs m_badvancedspamfilter isdlgbuttonchecked idc_advspamfilter theprefs m_busesecureident isdlgbuttonchecked idc_usesecident theprefs m_brunasuser isdlgbuttonchecked idc_runasuser getdlgitem idc_filter getwindowtext theprefs messagefilter cstring strcommentfilters getdlgitem idc_commentfilter getwindowtext strcommentfilters strcommentfilters makelower cstring strnewcommentfilters curpos cstring strfilter strcommentfilters _t curpos strfilter isempty strfilter strnewcommentfilters isempty strnewcommentfilters _t strnewcommentfilters strfilter strfilter strcommentfilters _t curpos theprefs commentfilter strnewcommentfilters theprefs commentfilter strcommentfilters setdlgitemtext idc_commentfilter theprefs commentfilter loadsettings setmodified cpropertypage onapply bool cp pg security pre translate message msg p msg if p msg message wm keydown if p msg w param vk escape return false if m pacipfilterurl m pacipfilterurl is bound p msg w param vk delete p msg hwnd get dlg item idc updateurl m hwnd get async key state vk menu 0 get async key state vk control 0 m pacipfilterurl clear if p msg w param vk return if p msg hwnd get dlg item idc updateurl m hwnd if m pacipfilterurl m pacipfilterurl is bound c string str text get dlg item idc updateurl get window text str text if str text is empty get dlg item idc updateurl set window text t this seems to be the only chance to let the dropdown list to disapear get dlg item idc updateurl set window text str text c edit get dlg item idc updateurl set sel str text get length str text get length return true return c property page pre translate message p msg cppgsecurity pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_escape m_pacipfilterurl m_pacipfilterurl isbound pmsg wparam vk_delete pmsg getdlgitem idc_updateurl m_hwnd getasynckeystate vk_menu getasynckeystate vk_control m_pacipfilterurl pmsg wparam vk_return pmsg getdlgitem idc_updateurl m_hwnd m_pacipfilterurl m_pacipfilterurl isbound cstring strtext getdlgitem idc_updateurl getwindowtext strtext strtext isempty getdlgitem idc_updateurl setwindowtext _t getdlgitem idc_updateurl setwindowtext strtext cedit getdlgitem idc_updateurl setsel strtext getlength strtext getlength cpropertypage pretranslatemessage pmsg bool cp pg security on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgsecurity oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg security on reloadip filter c wait cursor cur hourglass the app ipfilter load from default file cppgsecurity onreloadipfilter cwaitcursor curhourglass theapp loadfromdefaultfile void cp pg security on editip filter shell execute null t open the prefs get txt editor t the prefs get config dir dflt ipfilter filename t null sw show cppgsecurity oneditipfilter shellexecute _t theprefs gettxteditor _t theprefs getconfigdir dflt_ipfilter_filename _t sw_show void cp pg security on loadipf fromurl bool b have new filter file false c string url get dlg item text idc updateurl url if url is empty add entered url to lru list even if it s not yet known whether we can download from this url it s just more convenient this way if m pacipfilterurl m pacipfilterurl is bound m pacipfilterurl add item url 0 c string str temp file path tmakepath str temp file path get buffer max path null the prefs get config dir dflt ipfilter filename t tmp str temp file path release buffer c http download dlg dlg download dlg download m strtitle get res string ids dwl ipfilterfile dlg download m surltodownload url dlg download m sfiletodownloadinto str temp file path if dlg download do modal idok tremove str temp file path c string str error get res string ids dwlipfilterfailed if dlg download get error is empty str error t r n r n dlg download get error afx message box str error mb iconerror return c string str mime type get mime type str temp file path str mime type bool b is archive file false bool b uncompressed false czip file zip if zip open str temp file path b is archive file true czip file file zfile zip get file t guarding p2p if zfile null zfile zip get file t ipfilter dat if zfile c string str temp unzip file path tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer if zfile extract str temp unzip file path zip close zfile null if tremove the app ipfilter get default file path 0 trace t error failed to remove default ip filter file s hs n the app ipfilter get default file path strerror errno if trename str temp unzip file path the app ipfilter get default file path 0 trace t error failed to rename uncompressed ip filter file s to default ip filter file s hs n str temp unzip file path the app ipfilter get default file path strerror errno if tremove str temp file path 0 trace t error failed to remove temporary ip filter file s hs n str temp file path strerror errno b uncompressed true b have new filter file true else c string str error str error format get res string ids err ipfilterzipextr str temp file path afx message box str error mb iconerror else c string str error str error format get res string ids err ipfiltercontenterr str temp file path afx message box str error mb iconerror zip close else if str mime type compare no case t application x rar compressed 0 b is archive file true crar file rar if rar open str temp file path c string str file if rar get next file str file str file compare no case t ipfilter dat 0 str file compare no case t guarding p2p 0 c string str temp unzip file path tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer if rar extract str temp unzip file path rar close if tremove the app ipfilter get default file path 0 trace t error failed to remove default ip filter file s hs n the app ipfilter get default file path strerror errno if trename str temp unzip file path the app ipfilter get default file path 0 trace t error failed to rename uncompressed ip filter file s to default ip filter file s hs n str temp unzip file path the app ipfilter get default file path strerror errno if tremove str temp file path 0 trace t error failed to remove temporary ip filter file s hs n str temp file path strerror errno b uncompressed true b have new filter file true else c string str error str error format t failed to extract ip filter file from rar file s str temp file path afx message box str error mb iconerror else c string str error str error format t failed to find ip filter file guarding p2p or ipfilter dat in rar file s str temp file path afx message box str error mb iconerror rar close else c string str error str error format t failed to open file s r n r n invalid file format r n r n download latest version of unrar dll from http www rarlab com and copy unrar dll into e mule installation folder url afx message box str error mb iconerror else cgzip file gz if gz open str temp file path b is archive file true c string str temp unzip file path tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer add filename and extension of uncompressed file to temporary file c string str uncompressed file name gz get uncompressed file name if str uncompressed file name is empty str temp unzip file path t str temp unzip file path str uncompressed file name if gz extract str temp unzip file path gz close if tremove the app ipfilter get default file path 0 trace t error failed to remove default ip filter file s hs n the app ipfilter get default file path strerror errno if trename str temp unzip file path the app ipfilter get default file path 0 trace t error failed to rename uncompressed ip filter file s to default ip filter file s hs n str temp unzip file path the app ipfilter get default file path strerror errno if tremove str temp file path 0 trace t error failed to remove temporary ip filter file s hs n str temp file path strerror errno b uncompressed true b have new filter file true else c string str error str error format get res string ids err ipfilterzipextr str temp file path afx message box str error mb iconerror gz close if b is archive file b uncompressed check first lines of downloaded file for potential html content e g 404 error pages bool b validip filter file true file fp tfsopen str temp file path t rb sh denywr if fp char sz buff 16384 int i read fread sz buff 1 countof sz buff 1 fp if i read 0 b validip filter file false else sz buff i read 1 0 const char pc sz buff while pc pc t pc r pc n pc if strnicmp pc html 5 0 strnicmp pc xml 4 0 strnicmp pc doc 5 0 b validip filter file false fclose fp if b validip filter file tremove the app ipfilter get default file path trename str temp file path the app ipfilter get default file path b have new filter file true else afx message box get res string ids dwlipfilterfailed mb iconerror if url is empty b have new filter file on reloadip filter in case we received an invalid ip filter file e g an 404 html page with http status ok warn the user that there are no ip filters available any longer if b have new filter file the app ipfilter getip filter get count 0 c string str loaded str loaded format get res string ids ipfilterloaded the app ipfilter getip filter get count c string str error str error format t s r n r n s get res string ids dwlipfilterfailed str loaded afx message box str error mb iconerror cppgsecurity onloadipffromurl bhavenewfilterfile cstring getdlgitemtext idc_updateurl isempty m_pacipfilterurl m_pacipfilterurl isbound m_pacipfilterurl additem cstring strtempfilepath _tmakepath strtempfilepath getbuffer max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempfilepath releasebuffer chttpdownloaddlg dlgdownload dlgdownload m_strtitle getresstring ids_dwl_ipfilterfile dlgdownload m_surltodownload dlgdownload m_sfiletodownloadinto strtempfilepath dlgdownload domodal _tremove strtempfilepath cstring strerror getresstring ids_dwlipfilterfailed dlgdownload geterror isempty strerror _t dlgdownload geterror afxmessagebox strerror mb_iconerror cstring strmimetype getmimetype strtempfilepath strmimetype bisarchivefile buncompressed czipfile strtempfilepath bisarchivefile czipfile getfile _t getfile _t cstring strtempunzipfilepath _tmakepath strtempunzipfilepath getbuffer _max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer strtempunzipfilepath _tremove theapp getdefaultfilepath _t theapp getdefaultfilepath _trename strtempunzipfilepath theapp getdefaultfilepath _t strtempunzipfilepath theapp getdefaultfilepath _tremove strtempfilepath _t strtempfilepath buncompressed bhavenewfilterfile cstring strerror strerror getresstring ids_err_ipfilterzipextr strtempfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror getresstring ids_err_ipfiltercontenterr strtempfilepath afxmessagebox strerror mb_iconerror strmimetype comparenocase _t bisarchivefile crarfile strtempfilepath cstring strfile getnextfile strfile strfile comparenocase _t strfile comparenocase _t cstring strtempunzipfilepath _tmakepath strtempunzipfilepath getbuffer max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer strtempunzipfilepath _tremove theapp getdefaultfilepath _t theapp getdefaultfilepath _trename strtempunzipfilepath theapp getdefaultfilepath _t strtempunzipfilepath theapp getdefaultfilepath _tremove strtempfilepath _t strtempfilepath buncompressed bhavenewfilterfile cstring strerror strerror _t strtempfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t strtempfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t ninvalid ndownload emule afxmessagebox strerror mb_iconerror cgzipfile strtempfilepath bisarchivefile cstring strtempunzipfilepath _tmakepath strtempunzipfilepath getbuffer _max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer cstring struncompressedfilename getuncompressedfilename struncompressedfilename isempty strtempunzipfilepath _t strtempunzipfilepath struncompressedfilename strtempunzipfilepath _tremove theapp getdefaultfilepath _t theapp getdefaultfilepath _trename strtempunzipfilepath theapp getdefaultfilepath _t strtempunzipfilepath theapp getdefaultfilepath _tremove strtempfilepath _t strtempfilepath buncompressed bhavenewfilterfile cstring strerror strerror getresstring ids_err_ipfilterzipextr strtempfilepath afxmessagebox strerror mb_iconerror bisarchivefile buncompressed bvalidipfilterfile _tfsopen strtempfilepath _t _sh_denywr szbuff iread szbuff _countof szbuff iread bvalidipfilterfile szbuff iread szbuff bvalidipfilterfile bvalidipfilterfile _tremove theapp getdefaultfilepath _trename strtempfilepath theapp getdefaultfilepath bhavenewfilterfile afxmessagebox getresstring ids_dwlipfilterfailed mb_iconerror isempty bhavenewfilterfile onreloadipfilter bhavenewfilterfile theapp getipfilter getcount cstring strloaded strloaded getresstring ids_ipfilterloaded theapp getipfilter getcount cstring strerror strerror _t getresstring ids_dwlipfilterfailed strloaded afxmessagebox strerror mb_iconerror void cp pg security on en change update url c string str url get dlg item text idc updateurl str url get dlg item idc loadurl enable window str url is empty cppgsecurity onenchangeupdateurl cstring strurl getdlgitemtext idc_updateurl strurl getdlgitem idc_loadurl enablewindow strurl isempty void cp pg security ondd clicked c wnd box get dlg item idc updateurl box set focus box set window text t box send message wm keydown vk down 0x00510001 cppgsecurity onddclicked cwnd getdlgitem idc_updateurl setfocus setwindowtext _t sendmessage wm_keydown vk_down void cp pg security on help the app show help emule faq preferences security cppgsecurity onhelp theapp showhelp emule_faq_preferences_security bool cp pg security on help info helpinfo p help info on help return true cppgsecurity onhelpinfo phelpinfo onhelp void cp pg security on bn clicked run as user if c button get dlg item idc runasuser get check bst checked if afx message box get res string ids rau warning mb okcancel mb iconinformation 0 idcancel c button get dlg item idc runasuser set check bst unchecked on settings change cppgsecurity onbnclickedrunasuser cbutton getdlgitem idc_runasuser getcheck bst_checked afxmessagebox getresstring ids_rau_warning mb_okcancel mb_iconinformation cbutton getdlgitem idc_runasuser setcheck bst_unchecked onsettingschange void cp pg security on destroy deleteddb c property page on destroy cppgsecurity ondestroy cpropertypage ondestroy virtual bool on command wparam w param lparam l param void set modified bool b changed true m bmodified b changed c property page set modified b changed oncommand wparam lparam setmodified bchanged m_bmodified bchanged cpropertypage setmodified bchanged c property page cp pg web server idd b created false cpropertypage cppgwebserver bcreated cp pg web server cp pg web server cppgwebserver cppgwebserver void cp pg web server localize void if m hwnd set window text get res string ids pw ws get dlg item idc wspass lbl set window text get res string ids ws pass get dlg item idc wsport lbl set window text get res string ids port get dlg item idc wsenabled set window text get res string ids enabled get dlg item idc wsreloadtmpl set window text get res string ids sf reload get dlg item idc wsenabled set window text get res string ids enabled set dlg item text idc ws gzip get res string ids web gzip compression get dlg item idc wspass lbl2 set window text get res string ids ws pass get dlg item idc wsenabledlow set window text get res string ids enabled get dlg item idc static general set window text get res string ids pw general get dlg item idc static admin set window text get res string ids admin get dlg item idc static lowuser set window text get res string ids web lowuser get dlg item idc wsenabledlow set window text get res string ids enabled get dlg item idc template set window text get res string ids ws reload tmpl set dlg item text idc wstimeoutlabel get res string ids web sessiontimeout t set dlg item text idc mins get res string ids longmins get dlg item idc mmenabled set window text get res string ids enablemm get dlg item idc static mobilemule set window text get res string ids mobilemule get dlg item idc mmpassword set window text get res string ids ws pass get dlg item idc mmport lbl set window text get res string ids port get dlg item idc ws allowhilevfunc set window text get res string ids web allowhilevfunc cppgwebserver m_hwnd setwindowtext getresstring ids_pw_ws getdlgitem idc_wspass_lbl setwindowtext getresstring ids_ws_pass getdlgitem idc_wsport_lbl setwindowtext getresstring ids_port getdlgitem idc_wsenabled setwindowtext getresstring ids_enabled getdlgitem idc_wsreloadtmpl setwindowtext getresstring ids_sf_reload getdlgitem idc_wsenabled setwindowtext getresstring ids_enabled setdlgitemtext idc_ws_gzip getresstring ids_web_gzip_compression getdlgitem idc_wspass_lbl2 setwindowtext getresstring ids_ws_pass getdlgitem idc_wsenabledlow setwindowtext getresstring ids_enabled getdlgitem idc_static_general setwindowtext getresstring ids_pw_general getdlgitem idc_static_admin setwindowtext getresstring ids_admin getdlgitem idc_static_lowuser setwindowtext getresstring ids_web_lowuser getdlgitem idc_wsenabledlow setwindowtext getresstring ids_enabled getdlgitem idc_template setwindowtext getresstring ids_ws_reload_tmpl setdlgitemtext idc_wstimeoutlabel getresstring ids_web_sessiontimeout _t setdlgitemtext idc_mins getresstring ids_longmins getdlgitem idc_mmenabled setwindowtext getresstring ids_enablemm getdlgitem idc_static_mobilemule setwindowtext getresstring ids_mobilemule getdlgitem idc_mmpassword setwindowtext getresstring ids_ws_pass getdlgitem idc_mmport_lbl setwindowtext getresstring ids_port getdlgitem idc_ws_allowhilevfunc setwindowtext getresstring ids_web_allowhilevfunc void cp pg web server load settings void c string str buffer get dlg item idc wspass set window text hidden password get dlg item idc wspasslow set window text hidden password get dlg item idc mmpasswordfield set window text hidden password str buffer format t d the prefs getws port get dlg item idc wsport set window text str buffer str buffer format t d the prefs getmm port get dlg item idc mmport field set window text str buffer get dlg item idc tmplpath set window text the prefs get template str buffer format t d the prefs get web timeout mins set dlg item text idc wstimeout str buffer if the prefs getws is enabled check dlg button idc wsenabled 1 else check dlg button idc wsenabled 0 if the prefs getws is low user enabled check dlg button idc wsenabledlow 1 else check dlg button idc wsenabledlow 0 if the prefs ismm server enabled check dlg button idc mmenabled 1 else check dlg button idc mmenabled 0 check dlg button idc ws gzip the prefs get web use gzip 1 0 check dlg button idc ws allowhilevfunc the prefs get web admin allowed hi lev func 1 0 on en changemm enabled set modified false fo rc ha cppgwebserver loadsettings cstring strbuffer getdlgitem idc_wspass setwindowtext hidden_password getdlgitem idc_wspasslow setwindowtext hidden_password getdlgitem idc_mmpasswordfield setwindowtext hidden_password strbuffer _t theprefs getwsport getdlgitem idc_wsport setwindowtext strbuffer strbuffer _t theprefs getmmport getdlgitem idc_mmport_field setwindowtext strbuffer getdlgitem idc_tmplpath setwindowtext theprefs gettemplate strbuffer _t theprefs getwebtimeoutmins setdlgitemtext idc_wstimeout strbuffer theprefs getwsisenabled checkdlgbutton idc_wsenabled checkdlgbutton idc_wsenabled theprefs getwsislowuserenabled checkdlgbutton idc_wsenabledlow checkdlgbutton idc_wsenabledlow theprefs ismmserverenabled checkdlgbutton idc_mmenabled checkdlgbutton idc_mmenabled checkdlgbutton idc_ws_gzip theprefs getwebusegzip checkdlgbutton idc_ws_allowhilevfunc theprefs getwebadminallowedhilevfunc onenchangemmenabled setmodified forcha void cp pg web server do data exchange c data exchange pdx c property page do data exchange pdx cppgwebserver dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg web server on init dialog c property page on init dialog init window styles this c edit get dlg item idc wspass set limit text 12 c edit get dlg item idc wsport set limit text 6 load settings localize on en changews enabled note there are better classes to create a pure hyperlink however since it is only needed here we rather use an already existing class c rect rect get dlg item idc guidelink get window rect rect map window points null m hwnd lppoint rect 2 m wndmobilelink create ex null 0 t msg wnd ws border ws visible ws child htc wordwrap htc underline hover rect left rect top rect width rect height m hwnd 0 m wndmobilelink set bk color get sys color color 3dface still not the right color will fix this later need to merge the rc file before it changes m wndmobilelink set font get font if b created b created true m wndmobilelink append text t link m wndmobilelink append hyper link get res string ids mmguidelink 0 c string t http mobil emule project net 0 0 return true cppgwebserver oninitdialog cpropertypage oninitdialog initwindowstyles cedit getdlgitem idc_wspass setlimittext cedit getdlgitem idc_wsport setlimittext loadsettings onenchangewsenabled crect getdlgitem idc_guidelink getwindowrect mapwindowpoints m_hwnd m_wndmobilelink createex _t msgwnd ws_border ws_visible ws_child htc_wordwrap htc_underline_hover m_hwnd m_wndmobilelink setbkcolor getsyscolor color_3dface m_wndmobilelink setfont getfont bcreated bcreated m_wndmobilelink appendtext _t m_wndmobilelink appendhyperlink getresstring ids_mmguidelink cstring _t bool cp pg web server on apply if m bmodified c string s buf get and check templatefile existance get dlg item idc tmplpath get window text s buf if is dlg button checked idc wsenabled path file exists s buf c string buffer buffer format get res string ids web err cantload s buf afx message box buffer mb ok return false the prefs set template s buf the app webserver reload templates uint16 old port the prefs getws port get dlg item idc wspass get window text s buf if s buf hidden password the prefs setws pass s buf get dlg item idc wspasslow get window text s buf if s buf hidden password the prefs setws low pass s buf get dlg item idc wsport get window text s buf if tstoi s buf old port the prefs setws port uint16 tstoi s buf the app webserver restart server get dlg item text idc wstimeout s buf the prefs m iwebtimeoutmins tstoi s buf the prefs setws is enabled is dlg button checked idc wsenabled 0 the prefs setws is low user enabled is dlg button checked idc wsenabledlow 0 the prefs set web use gzip is dlg button checked idc ws gzip 0 the app webserver start server the prefs m ballowadminhilevfunc is dlg button checked idc ws allowhilevfunc 0 mobilemule get dlg item idc mmport field get window text s buf if tstoi s buf the prefs getmm port the prefs setmm port uint16 tstoi s buf the app mmserver stop server the app mmserver init the prefs setmm is enabled is dlg button checked idc mmenabled 0 if is dlg button checked idc mmenabled the app mmserver init else the app mmserver stop server get dlg item idc mmpasswordfield get window text s buf if s buf hidden password the prefs setmm pass s buf the app emuledlg serverwnd update my info set modified false set tmpl button state return c property page on apply cppgwebserver onapply m_bmodified cstring sbuf getdlgitem idc_tmplpath getwindowtext sbuf isdlgbuttonchecked idc_wsenabled pathfileexists sbuf cstring getresstring ids_web_err_cantload sbuf afxmessagebox mb_ok theprefs settemplate sbuf theapp reloadtemplates oldport theprefs getwsport getdlgitem idc_wspass getwindowtext sbuf sbuf hidden_password theprefs setwspass sbuf getdlgitem idc_wspasslow getwindowtext sbuf sbuf hidden_password theprefs setwslowpass sbuf getdlgitem idc_wsport getwindowtext sbuf _tstoi sbuf oldport theprefs setwsport _tstoi sbuf theapp restartserver getdlgitemtext idc_wstimeout sbuf theprefs m_iwebtimeoutmins _tstoi sbuf theprefs setwsisenabled isdlgbuttonchecked idc_wsenabled theprefs setwsislowuserenabled isdlgbuttonchecked idc_wsenabledlow theprefs setwebusegzip isdlgbuttonchecked idc_ws_gzip theapp startserver theprefs m_ballowadminhilevfunc isdlgbuttonchecked idc_ws_allowhilevfunc getdlgitem idc_mmport_field getwindowtext sbuf _tstoi sbuf theprefs getmmport theprefs setmmport _tstoi sbuf theapp stopserver theapp theprefs setmmisenabled isdlgbuttonchecked idc_mmenabled isdlgbuttonchecked idc_mmenabled theapp theapp stopserver getdlgitem idc_mmpasswordfield getwindowtext sbuf sbuf hidden_password theprefs setmmpass sbuf theapp updatemyinfo setmodified settmplbuttonstate cpropertypage onapply bool cp pg web server on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgwebserver oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg web server on en changews enabled uint b iswi enabled is dlg button checked idc wsenabled get dlg item idc wspass enable window b iswi enabled get dlg item idc wsport enable window b iswi enabled get dlg item idc wsenabledlow enable window b iswi enabled get dlg item idc tmplpath enable window b iswi enabled get dlg item idc tmplbrowse enable window b iswi enabled get dlg item idc ws gzip enable window b iswi enabled get dlg item idc ws allowhilevfunc enable window b iswi enabled get dlg item idc wstimeout enable window b iswi enabled get dlg item idc wspasslow enable window b iswi enabled is dlg button checked idc wsenabledlow get dlg item idc wsreloadtmpl enable window b iswi enabled set tmpl button state set modified cppgwebserver onenchangewsenabled biswienabled isdlgbuttonchecked idc_wsenabled getdlgitem idc_wspass enablewindow biswienabled getdlgitem idc_wsport enablewindow biswienabled getdlgitem idc_wsenabledlow enablewindow biswienabled getdlgitem idc_tmplpath enablewindow biswienabled getdlgitem idc_tmplbrowse enablewindow biswienabled getdlgitem idc_ws_gzip enablewindow biswienabled getdlgitem idc_ws_allowhilevfunc enablewindow biswienabled getdlgitem idc_wstimeout enablewindow biswienabled getdlgitem idc_wspasslow enablewindow biswienabled isdlgbuttonchecked idc_wsenabledlow getdlgitem idc_wsreloadtmpl enablewindow biswienabled settmplbuttonstate setmodified void cp pg web server on en changemm enabled get dlg item idc mmpasswordfield enable window is dlg button checked idc mmenabled get dlg item idc mmport field enable window is dlg button checked idc mmenabled set modified cppgwebserver onenchangemmenabled getdlgitem idc_mmpasswordfield enablewindow isdlgbuttonchecked idc_mmenabled getdlgitem idc_mmport_field enablewindow isdlgbuttonchecked idc_mmenabled setmodified void cp pg web server on reload templates the app webserver reload templates cppgwebserver onreloadtemplates theapp reloadtemplates void cp pg web server on bn clicked tmplbrowse c string str templ get dlg item text idc tmplpath str templ c string buffer buffer get res string ids ws reload tmpl t tmpl tmpl if dialog browse file buffer t template buffer str templ get dlg item idc tmplpath set window text buffer set modified set tmpl button state cppgwebserver onbnclickedtmplbrowse cstring strtempl getdlgitemtext idc_tmplpath strtempl cstring getresstring ids_ws_reload_tmpl _t dialogbrowsefile _t strtempl getdlgitem idc_tmplpath setwindowtext setmodified settmplbuttonstate void cp pg web server on help the app show help emule faq preferences webinterface cppgwebserver onhelp theapp showhelp emule_faq_preferences_webinterface void cp pg web server set tmpl button state c string buffer get dlg item text idc tmplpath buffer get dlg item idc wsreloadtmpl enable window the prefs getws is enabled buffer compare no case the prefs get template 0 cppgwebserver settmplbuttonstate cstring getdlgitemtext idc_tmplpath getdlgitem idc_wsreloadtmpl enablewindow theprefs getwsisenabled comparenocase theprefs gettemplate bool cp pg web server on help info helpinfo p help info on help return true cppgwebserver onhelpinfo phelpinfo onhelp cp pg scheduler cp pg scheduler c property page cp pg scheduler idd cppgscheduler cppgscheduler cpropertypage cppgscheduler cp pg scheduler cp pg scheduler cppgscheduler cppgscheduler void cp pg scheduler localize void if m hwnd set window text get res string ids scheduler get dlg item idc enable set window text get res string ids enabled get dlg item idc s enable set window text get res string ids enabled get dlg item idc static s title set window text get res string ids title get dlg item idc static details set window text get res string ids details get dlg item idc static s time set window text get res string ids time get dlg item idc static s action set window text get res string ids action get dlg item idc apply set window text get res string ids pw apply get dlg item idc remove set window text get res string ids remove get dlg item idc new set window text get res string ids new get dlg item idc checknoendtime set window text get res string ids checknoendtime while m timesel get count 0 m timesel delete string 0 for int i 0 i 11 i m timesel add string get day label i m timesel set cur sel 0 if m list get selection mark 1 m timesel set cur sel the app scheduler get schedule m timesel get cur sel day cppgscheduler m_hwnd setwindowtext getresstring ids_scheduler getdlgitem idc_enable setwindowtext getresstring ids_enabled getdlgitem idc_s_enable setwindowtext getresstring ids_enabled getdlgitem idc_static_s_title setwindowtext getresstring ids_title getdlgitem idc_static_details setwindowtext getresstring ids_details getdlgitem idc_static_s_time setwindowtext getresstring ids_time getdlgitem idc_static_s_action setwindowtext getresstring ids_action getdlgitem idc_apply setwindowtext getresstring ids_pw_apply getdlgitem idc_remove setwindowtext getresstring ids_remove getdlgitem idc_new setwindowtext getresstring ids_new getdlgitem idc_checknoendtime setwindowtext getresstring ids_checknoendtime m_timesel getcount m_timesel deletestring m_timesel addstring getdaylabel m_timesel setcursel m_list getselectionmark m_timesel setcursel theapp getschedule m_timesel getcursel c string cp pg scheduler get action label int index switch index case action setupl return get res string ids pw upl case action setdownl return get res string ids pw downl case action sourcesl return get res string ids limitsources case action con5sec return get res string ids limitcons5sec case action catstop return get res string ids sched catstop case action catresume return get res string ids sched catresume case action cons return get res string ids pw maxc return null cstring cppgscheduler getactionlabel action_setupl getresstring ids_pw_upl action_setdownl getresstring ids_pw_downl action_sourcesl getresstring ids_limitsources action_con5sec getresstring ids_limitcons5sec action_catstop getresstring ids_sched_catstop action_catresume getresstring ids_sched_catresume action_cons getresstring ids_pw_maxc c string cp pg scheduler get day label int index switch index case day dayly return get res string ids dayly case day mo return get res string ids mo case day di return get res string ids di case day mi return get res string ids mi case day do return get res string ids do case day fr return get res string ids fr case day sa return get res string ids sa case day so return get res string ids so case day mo fr return get res string ids day mo fr case day mo sa return get res string ids day mo sa case day sa so return get res string ids day sa so return null cstring cppgscheduler getdaylabel day_dayly getresstring ids_dayly day_mo getresstring ids_mo day_di getresstring ids_di day_mi getresstring ids_mi day_do getresstring ids_do day_fr getresstring ids_fr day_sa getresstring ids_sa day_so getresstring ids_so day_mo_fr getresstring ids_day_mo_fr day_mo_sa getresstring ids_day_mo_sa day_sa_so getresstring ids_day_sa_so void cp pg scheduler load schedule int index schedule struct schedule the app scheduler get schedule index get dlg item idc s title set window text schedule title time c time time time get current time if schedule time 0 time schedule time m time set time time c time time2 time2 get current time if schedule time2 0 time2 schedule time2 m timeto set time time2 time kindof days m timesel set cur sel schedule day check dlg button idc s enable schedule enabled check dlg button idc checknoendtime schedule time2 0 on disable time2 m actions delete all items for int i 0 i 16 i if schedule actions i 0 break m actions insert item i get action label schedule actions i m actions set item text i 1 schedule values i m actions set item data i schedule actions i cppgscheduler loadschedule schedule_struct theapp getschedule getdlgitem idc_s_title setwindowtext ctime getcurrenttime m_time settime ctime getcurrenttime m_timeto settime m_timesel setcursel checkdlgbutton idc_s_enable checkdlgbutton idc_checknoendtime ondisabletime2 m_actions deleteallitems m_actions insertitem getactionlabel m_actions setitemtext m_actions setitemdata void cp pg scheduler recheck schedules the app scheduler check true cppgscheduler recheckschedules theapp void cp pg scheduler fill schedule list m list delete all items for uint8 index 0 index the app scheduler get count index m list insert item index the app scheduler get schedule index title c time time the app scheduler get schedule index time c string times m list set item text index 1 get day label the app scheduler get schedule index day times format t s time format t h m m list set item text index 2 times if m list get item count 0 m list set selection mark 0 m list set item state 0 lvis selected lvis selected load schedule 0 cppgscheduler fillschedulelist m_list deleteallitems theapp getcount m_list insertitem theapp getschedule ctime theapp getschedule cstring m_list setitemtext getdaylabel theapp getschedule _t _t m_list setitemtext m_list getitemcount m_list setselectionmark m_list setitemstate lvis_selected lvis_selected loadschedule void cp pg scheduler do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc timesel m timesel ddx control pdx idc schedaction m actions ddx control pdx idc datetimepicker1 m time ddx control pdx idc datetimepicker2 m timeto ddx control pdx idc schedlist m list cppgscheduler dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_timesel m_timesel ddx_control idc_schedaction m_actions ddx_control idc_datetimepicker1 m_time ddx_control idc_datetimepicker2 m_timeto ddx_control idc_schedlist m_list bool cp pg scheduler on init dialog c property page on init dialog init window styles this m list set extended style lvs ex fullrowselect m list modify style lvs singlesel 0 m list insert column 0 get res string ids title lvcfmt left 150 0 m list insert column 1 get res string ids s days lvcfmt left 80 1 m list insert column 2 get res string ids starttime lvcfmt left 80 2 m time set format t h mm m timeto set format t h mm m actions set extended style lvs ex fullrowselect m actions modify style lvs singlesel 0 m actions insert column 0 get res string ids action lvcfmt left 150 0 m actions insert column 1 get res string ids value lvcfmt left 80 1 localize check dlg button idc enable the prefs is scheduler enabled fill schedule list return true return true unless you set the focus to a control exception ocx property pages should return false cppgscheduler oninitdialog cpropertypage oninitdialog initwindowstyles m_list setextendedstyle lvs_ex_fullrowselect m_list modifystyle lvs_singlesel m_list insertcolumn getresstring ids_title lvcfmt_left m_list insertcolumn getresstring ids_s_days lvcfmt_left m_list insertcolumn getresstring ids_starttime lvcfmt_left m_time setformat _t m_timeto setformat _t m_actions setextendedstyle lvs_ex_fullrowselect m_actions modifystyle lvs_singlesel m_actions insertcolumn getresstring ids_action lvcfmt_left m_actions insertcolumn getresstring ids_value lvcfmt_left checkdlgbutton idc_enable theprefs isschedulerenabled fillschedulelist bool cp pg scheduler on apply set modified false return c property page on apply cppgscheduler onapply setmodified cpropertypage onapply bool cp pg scheduler on command wparam w param lparam l param int item m actions get selection mark add if w param mp schactions w param mp schactions 20 m actions get item count 16 int action w param mp schactions int i m actions get item count m actions insert item i get action label action m actions set item data i action m actions set selection mark i if action 6 on command mp cat edit 0 else if w param mp schactions 20 w param mp schactions 80 c string newval newval format t i w param mp schactions 22 m actions set item text item 1 newval else if w param id help on help return true switch w param case mp cat edit if item 1 input box inputbox todo differen prompts c string prompt switch m actions get item data item case 1 case 2 prompt get res string ids sched enterdataratelimit t get res string ids kbytespersec t break default prompt get res string ids sched enterval inputbox set labels get res string ids sched actconfig prompt m actions get item text item 1 inputbox do modal c string res inputbox get input if inputbox was cancelled m actions set item text item 1 res break case mp cat remove remove if item 1 int ix m actions get selection mark if ix 1 m actions delete item ix break return c property page on command w param l param cppgscheduler oncommand wparam lparam m_actions getselectionmark wparam mp_schactions wparam mp_schactions m_actions getitemcount wparam mp_schactions m_actions getitemcount m_actions insertitem getactionlabel m_actions setitemdata m_actions setselectionmark oncommand mp_cat_edit wparam mp_schactions wparam mp_schactions cstring _t wparam mp_schactions m_actions setitemtext wparam id_help onhelp wparam mp_cat_edit inputbox cstring m_actions getitemdata getresstring ids_sched_enterdataratelimit _t getresstring ids_kbytespersec _t getresstring ids_sched_enterval setlabels getresstring ids_sched_actconfig m_actions getitemtext domodal cstring getinput wascancelled m_actions setitemtext mp_cat_remove m_actions getselectionmark m_actions deleteitem cpropertypage oncommand wparam lparam void cp pg scheduler onnm dblclk list nmhdr pnmhdr lresult p result if m list get selection mark 1 load schedule m list get selection mark cppgscheduler onnmdblclklist presult m_list getselectionmark loadschedule m_list getselectionmark void cp pg scheduler on bn clicked add int index schedule struct newschedule new schedule struct newschedule day 0 newschedule enabled false newschedule time time null newschedule time2 time null newschedule title t newschedule reset actions index the app scheduler add schedule newschedule m list insert item index newschedule title m list set selection mark index recheck schedules cppgscheduler onbnclickedadd schedule_struct schedule_struct _t resetactions theapp addschedule m_list insertitem m_list setselectionmark recheckschedules void cp pg scheduler on bn clicked apply int index m list get selection mark if index 1 schedule struct schedule the app scheduler get schedule index title get dlg item idc s title get window text schedule title time c time my time dword result m time get time my time if result gdt valid schedule time safe mktime my time get local tm c time my time2 dword result2 m timeto get time my time2 if result2 gdt valid schedule time2 safe mktime my time2 get local tm if is dlg button checked idc checknoendtime schedule time2 0 time kindof days schedule day m timesel get cur sel schedule enabled is dlg button checked idc s enable 0 schedule reset actions for uint8 i 0 i m actions get item count i schedule actions i m actions get item data i schedule values i m actions get item text i 1 m list set item text index 0 schedule title m list set item text index 1 get day label schedule day c time time the app scheduler get schedule index time c string times times format t s time format t h m m list set item text index 2 times recheck schedules cppgscheduler onbnclickedapply m_list getselectionmark schedule_struct theapp getschedule getdlgitem idc_s_title getwindowtext ctime mytime m_time gettime mytime gdt_valid safe_mktime mytime getlocaltm ctime mytime2 m_timeto gettime mytime2 gdt_valid safe_mktime mytime2 getlocaltm isdlgbuttonchecked idc_checknoendtime m_timesel getcursel isdlgbuttonchecked idc_s_enable resetactions m_actions getitemcount m_actions getitemdata m_actions getitemtext m_list setitemtext m_list setitemtext getdaylabel ctime theapp getschedule cstring _t _t m_list setitemtext recheckschedules void cp pg scheduler on bn clicked remove int index m list get selection mark if index 1 the app scheduler remove schedule index fill schedule list the app scheduler restore originals recheck schedules cppgscheduler onbnclickedremove m_list getselectionmark theapp removeschedule fillschedulelist theapp restoreoriginals recheckschedules void cp pg scheduler on enable change the prefs scheduler is dlg button checked idc enable 0 if the prefs scheduler the app scheduler restore originals recheck schedules the app emuledlg preferenceswnd m wndconnection load settings set modified cppgscheduler onenablechange theprefs isdlgbuttonchecked idc_enable theprefs theapp restoreoriginals recheckschedules theapp m_wndconnection loadsettings setmodified void cp pg scheduler on disable time2 get dlg item idc datetimepicker2 enable window is dlg button checked idc checknoendtime 0 cppgscheduler ondisabletime2 getdlgitem idc_datetimepicker2 enablewindow isdlgbuttonchecked idc_checknoendtime void cp pg scheduler onnm dblclk actionlist nmhdr pnmhdr lresult p result if m actions get selection mark 1 int ac m actions get item data m actions get selection mark if ac 6 ac 7 on command mp cat edit 0 p result 0 cppgscheduler onnmdblclkactionlist presult m_actions getselectionmark m_actions getitemdata m_actions getselectionmark oncommand mp_cat_edit presult void cp pg scheduler onnm rclick actionlist nmhdr pnmhdr lresult p result point point get cursor pos point c title menu m actionmenu c menu m actionsel c menu m catactionsel bool is cat action false if m actions get selection mark 1 int ac m actions get item data m actions get selection mark if ac 6 ac 7 is cat action true m actionmenu create popup menu m actionsel create popup menu m catactionsel create popup menu uint n flag mf string if m actions get selection mark 1 n flag mf string mf grayed m actionsel append menu mf string mp schactions action setupl get res string ids pw upl m actionsel append menu mf string mp schactions action setdownl get res string ids pw downl m actionsel append menu mf string mp schactions action sourcesl get res string ids limitsources m actionsel append menu mf string mp schactions action con5sec get res string ids limitcons5sec m actionsel append menu mf string mp schactions action cons get res string ids pw maxc m actionsel append menu mf string mp schactions action catstop get res string ids sched catstop m actionsel append menu mf string mp schactions action catresume get res string ids sched catresume m actionmenu add menu title get res string ids action m actionmenu append menu mf popup uint ptr m actionsel m hmenu get res string ids add if is cat action if the prefs get cat count 1 m catactionsel append menu mf string mp schactions 20 get res string ids allunassigned m catactionsel append menu mf string mp schactions 21 get res string ids all for int i 1 i the prefs get cat count i m catactionsel append menu mf string mp schactions 22 i the prefs get category i title m actionmenu append menu mf popup uint ptr m catactionsel m hmenu get res string ids selectcat else m actionmenu append menu n flag mp cat edit get res string ids edit m actionmenu append menu n flag mp cat remove get res string ids remove m actionmenu track popup menu tpm leftalign tpm rightbutton point x point y this verify m actionsel destroy menu verify m catactionsel destroy menu verify m actionmenu destroy menu p result 0 cppgscheduler onnmrclickactionlist presult getcursorpos ctitlemenu m_actionmenu cmenu m_actionsel cmenu m_catactionsel iscataction m_actions getselectionmark m_actions getitemdata m_actions getselectionmark iscataction m_actionmenu createpopupmenu m_actionsel createpopupmenu m_catactionsel createpopupmenu nflag mf_string m_actions getselectionmark nflag mf_string mf_grayed m_actionsel appendmenu mf_string mp_schactions action_setupl getresstring ids_pw_upl m_actionsel appendmenu mf_string mp_schactions action_setdownl getresstring ids_pw_downl m_actionsel appendmenu mf_string mp_schactions action_sourcesl getresstring ids_limitsources m_actionsel appendmenu mf_string mp_schactions action_con5sec getresstring ids_limitcons5sec m_actionsel appendmenu mf_string mp_schactions action_cons getresstring ids_pw_maxc m_actionsel appendmenu mf_string mp_schactions action_catstop getresstring ids_sched_catstop m_actionsel appendmenu mf_string mp_schactions action_catresume getresstring ids_sched_catresume m_actionmenu addmenutitle getresstring ids_action m_actionmenu appendmenu mf_popup uint_ptr m_actionsel m_hmenu getresstring ids_add iscataction theprefs getcatcount m_catactionsel appendmenu mf_string mp_schactions getresstring ids_allunassigned m_catactionsel appendmenu mf_string mp_schactions getresstring ids_all theprefs getcatcount m_catactionsel appendmenu mf_string mp_schactions theprefs getcategory m_actionmenu appendmenu mf_popup uint_ptr m_catactionsel m_hmenu getresstring ids_selectcat m_actionmenu appendmenu nflag mp_cat_edit getresstring ids_edit m_actionmenu appendmenu nflag mp_cat_remove getresstring ids_remove m_actionmenu trackpopupmenu tpm_leftalign tpm_rightbutton m_actionsel destroymenu m_catactionsel destroymenu m_actionmenu destroymenu presult void cp pg scheduler on help the app show help emule faq preferences scheduler cppgscheduler onhelp theapp showhelp emule_faq_preferences_scheduler bool cp pg scheduler on help info helpinfo p help info on help return true cppgscheduler onhelpinfo phelpinfo onhelp m hcaptionicon null m dwmsgformat dt center dt vcenter dt noprefix dt singleline m_hcaptionicon m_dwmsgformat dt_center dt_vcenter dt_noprefix dt_singleline c prop page frame c prop page frame cproppageframe cproppageframe void c prop page frame show caption bool b enable m bshowcaption b enable safe update window calc caption area cproppageframe showcaption benable m_bshowcaption benable safeupdatewindow calccaptionarea bool c prop page frame get show caption const return m bshowcaption cproppageframe getshowcaption m_bshowcaption void c prop page frame set caption height int n caption height m ncaptionheight n caption height safe update window calc caption area cproppageframe setcaptionheight ncaptionheight m_ncaptionheight ncaptionheight safeupdatewindow calccaptionarea int c prop page frame get caption height const return m ncaptionheight cproppageframe getcaptionheight m_ncaptionheight void c prop page frame set caption lpctstr lpsz caption hicon h icon null m strcaption lpsz caption m hcaptionicon h icon safe update window calc caption area cproppageframe setcaption lpszcaption hicon m_strcaption lpszcaption m_hcaptionicon hicon safeupdatewindow calccaptionarea c string c prop page frame get caption hicon p icon null const if p icon p icon m hcaptionicon return m strcaption cstring cproppageframe getcaption picon picon picon m_hcaptionicon m_strcaption void c prop page frame set msg text lpctstr lpsz msg m strmsg lpsz msg safe update window calc msg area cproppageframe setmsgtext lpszmsg m_strmsg lpszmsg safeupdatewindow calcmsgarea c string c prop page frame get msg text const return m strmsg cstring cproppageframe getmsgtext m_strmsg void c prop page frame set msg format dword dw format m dwmsgformat dw format safe update window calc msg area cproppageframe setmsgformat dwformat m_dwmsgformat dwformat safeupdatewindow calcmsgarea dword c prop page frame get msg format const return m dwmsgformat cproppageframe getmsgformat m_dwmsgformat void c prop page frame draw cdc p dc if get show caption draw caption p dc calc caption area m strcaption m hcaptionicon draw msg p dc calc msg area m strmsg m dwmsgformat cproppageframe pdc getshowcaption drawcaption pdc calccaptionarea m_strcaption m_hcaptionicon drawmsg pdc calcmsgarea m_strmsg m_dwmsgformat c rect c prop page frame calc msg area assert is window get wnd get safe hwnd c rect rect msg get wnd get client rect rect msg if get show caption rect msg top get caption height return rect msg crect cproppageframe calcmsgarea iswindow getwnd getsafehwnd crect rectmsg getwnd getclientrect rectmsg getshowcaption rectmsg getcaptionheight rectmsg void c prop page frame draw msg cdc p dc c rect rect lpctstr lpsz msg dword dw format c font p prev font c font p dc select stock object default gui font int n prev bk mode p dc set bk mode transparent p dc draw text get msg text rect get msg format p dc set bk mode n prev bk mode p dc select object p prev font cproppageframe drawmsg pdc crect lpszmsg dwformat cfont pprevfont cfont pdc selectstockobject default_gui_font nprevbkmode pdc setbkmode pdc drawtext getmsgtext getmsgformat pdc setbkmode nprevbkmode pdc selectobject pprevfont c rect c prop page frame calc caption area assert is window get wnd get safe hwnd c rect rect caption get wnd get client rect rect caption if get show caption rect caption bottom rect caption top else rect caption bottom rect caption top get caption height return rect caption crect cproppageframe calccaptionarea iswindow getwnd getsafehwnd crect rectcaption getwnd getclientrect rectcaption getshowcaption rectcaption rectcaption rectcaption rectcaption getcaptionheight rectcaption void c prop page frame draw caption cdc pdc c rect rect lpctstr lpsz caption hicon h icon should be implemented by specialized classes cproppageframe drawcaption crect lpszcaption hicon void c prop page frame safe update window lpcrect lp rect null if is window get wnd get safe hwnd return get wnd invalidate rect lp rect true cproppageframe safeupdatewindow lprect iswindow getwnd getsafehwnd getwnd invalidaterect lprect m pwndpagetree null m pframe null m_pwndpagetree m_pframe m pwndpagetree null m pframe null m_pwndpagetree m_pframe c tree prop sheet c tree prop sheet ctreepropsheet ctreepropsheet bool c tree prop sheet set tree view mode bool b tree view mode true bool b page caption false bool b tree images false if is window m hwnd needs to becalled before the window has been created assert false return false m btreeviewmode b tree view mode if m btreeviewmode m bpagecaption b page caption m btreeimages b tree images return true ctreepropsheet settreeviewmode btreeviewmode bpagecaption btreeimages iswindow m_hwnd m_btreeviewmode btreeviewmode m_btreeviewmode m_bpagecaption bpagecaption m_btreeimages btreeimages bool c tree prop sheet set tree width int n width if is window m hwnd needs to be called before the window is created assert false return false m npagetreewidth n width return true ctreepropsheet settreewidth nwidth iswindow m_hwnd m_npagetreewidth nwidth void c tree prop sheet set empty page text lpctstr lpsz empty page text m stremptypagemessage lpsz empty page text ctreepropsheet setemptypagetext lpszemptypagetext m_stremptypagemessage lpszemptypagetext dword c tree prop sheet set empty page text format dword dw format dword dw prev format m pframe get msg format m pframe set msg format dw format return dw prev format ctreepropsheet setemptypagetextformat dwformat dwprevformat m_pframe getmsgformat m_pframe setmsgformat dwformat dwprevformat bool c tree prop sheet set tree default images c image list p images if p images get image count 2 assert false return false if m defaultimages get safe handle m defaultimages delete image list m defaultimages create p images update if necessary if is window m hwnd refill page tree return true ctreepropsheet settreedefaultimages cimagelist pimages pimages getimagecount m_defaultimages getsafehandle m_defaultimages deleteimagelist m_defaultimages pimages iswindow m_hwnd refillpagetree bool c tree prop sheet set tree default images uint un bitmapid int cx colorref cr mask if m defaultimages get safe handle m defaultimages delete image list if m defaultimages create un bitmapid cx 0 cr mask return false if m defaultimages get image count 2 m defaultimages delete image list return false return true ctreepropsheet settreedefaultimages unbitmapid crmask m_defaultimages getsafehandle m_defaultimages deleteimagelist m_defaultimages unbitmapid crmask m_defaultimages getimagecount m_defaultimages deleteimagelist c tree ctrl c tree prop sheet get page tree control return m pwndpagetree ctreectrl ctreepropsheet getpagetreecontrol m_pwndpagetree bool c tree prop sheet set page icon c property page p page lpctstr psz icon id p page m psp dw flags psp useiconid p page m psp psz icon psz icon id return true ctreepropsheet setpageicon cpropertypage ppage psziconid ppage m_psp dwflags psp_useiconid ppage m_psp pszicon psziconid bool c tree prop sheet set page icon c property page p page hicon h icon p page m psp dw flags psp usehicon p page m psp h icon h icon return true ctreepropsheet setpageicon cpropertypage ppage hicon ppage m_psp dwflags psp_usehicon ppage m_psp hicon hicon bool c tree prop sheet set page icon c property page p page uint un icon id hicon h icon afx get app load icon un icon id if h icon return false return set page icon p page h icon ctreepropsheet setpageicon cpropertypage ppage uniconid hicon afxgetapp loadicon uniconid hicon setpageicon ppage hicon bool c tree prop sheet set page icon c property page p page c image list images int n image hicon h icon images extract icon n image if h icon return false return set page icon p page h icon ctreepropsheet setpageicon cpropertypage ppage cimagelist nimage hicon extracticon nimage hicon setpageicon ppage hicon bool c tree prop sheet destroy page icon c property page p page if p page p page m psp dw flags psp usehicon p page m psp h icon return false destroy icon p page m psp h icon p page m psp dw flags psp usehicon p page m psp h icon null return true ctreepropsheet destroypageicon cpropertypage ppage ppage ppage m_psp dwflags psp_usehicon ppage m_psp hicon destroyicon ppage m_psp hicon ppage m_psp dwflags psp_usehicon ppage m_psp hicon c string c tree prop sheet generate empty page message lpctstr lpsz empty page message lpctstr lpsz caption c string str msg str msg format lpsz empty page message lpsz caption return str msg cstring ctreepropsheet generateemptypagemessage lpszemptypagemessage lpszcaption cstring strmsg strmsg lpszemptypagemessage lpszcaption strmsg c tree ctrl c tree prop sheet create page tree object return new c tree ctrl ctreectrl ctreepropsheet createpagetreeobject ctreectrl c prop page frame c tree prop sheet create page frame return new c prop page frame default cproppageframe ctreepropsheet createpageframe cproppageframedefault void c tree prop sheet move child windows int n dx int n dy c wnd p wnd get window gw child while p wnd c rect rect p wnd get window rect rect screen to client rect rect offset rect n dx n dy p wnd move window rect p wnd p wnd get next window ctreepropsheet movechildwindows ndx ndy cwnd pwnd getwindow gw_child pwnd crect pwnd getwindowrect screentoclient offsetrect ndx ndy pwnd movewindow pwnd pwnd getnextwindow void c tree prop sheet refill page tree if is window m hwnd return m pwndpagetree delete all items c tab ctrl p tab ctrl get tab control if is window p tab ctrl get safe hwnd assert false return const int n page count p tab ctrl get item count rebuild image list if m btreeimages for int i m images get image count 1 i 0 i m images remove i add page images c image list p page images p tab ctrl get image list if p page images for int n image 0 n image p page images get image count n image hicon h icon p page images extract icon n image m images add h icon destroy icon h icon add default images if m defaultimages get safe handle hicon h icon add default images h icon m defaultimages extract icon 0 if h icon m images add h icon destroy icon h icon h icon m defaultimages extract icon 1 m images add h icon destroy icon h icon insert tree items for int n page 0 n page n page count n page get title and image of the page c string str page path tcitem ti zero memory ti sizeof ti ti mask tcif text tcif image ti cch text max max path ti psz text str page path get buffer ti cch text max assert ti psz text if ti psz text return p tab ctrl get item n page ti str page path release buffer create an item in the tree for the page htreeitem h item create page tree item ti psz text assert h item if h item m pwndpagetree set item data h item n page set image if m btreeimages int n image ti i image if n image 0 n image m images get image count n image m defaultimages get safe handle m images get image count 1 1 m pwndpagetree set item image h item n image n image ctreepropsheet refillpagetree iswindow m_hwnd m_pwndpagetree deleteallitems ctabctrl ptabctrl gettabcontrol iswindow ptabctrl getsafehwnd npagecount ptabctrl getitemcount m_btreeimages m_images getimagecount m_images cimagelist ppageimages ptabctrl getimagelist ppageimages nimage nimage ppageimages getimagecount nimage hicon ppageimages extracticon nimage m_images hicon destroyicon hicon m_defaultimages getsafehandle hicon hicon m_defaultimages extracticon hicon m_images hicon destroyicon hicon hicon m_defaultimages extracticon m_images hicon destroyicon hicon npage npage npagecount npage cstring strpagepath zeromemory tcif_text tcif_image cchtextmax max_path psztext strpagepath getbuffer cchtextmax psztext psztext ptabctrl getitem npage strpagepath releasebuffer hitem createpagetreeitem psztext hitem hitem m_pwndpagetree setitemdata hitem npage m_btreeimages nimage iimage nimage nimage m_images getimagecount nimage m_defaultimages getsafehandle m_images getimagecount m_pwndpagetree setitemimage hitem nimage nimage htreeitem c tree prop sheet create page tree item lpctstr lpsz path htreeitem h parent tvi root c string str path lpsz path c string str top most item split page tree path str path check if an item with the given text does already exist htreeitem h item null htreeitem h child m pwndpagetree get child item h parent while h child if m pwndpagetree get item text h child str top most item h item h child break h child m pwndpagetree get next item h child tvgn next if item with that text does not already exist create a new one if h item h item m pwndpagetree insert item str top most item h parent m pwndpagetree set item data h item dword ptr 1 if str path is empty m btreeimages m defaultimages get safe handle set folder image m pwndpagetree set item image h item m images get image count 2 m images get image count 2 if h item assert false return null if str path is empty return h item else return create page tree item str path h item ctreepropsheet createpagetreeitem lpszpath hparent tvi_root cstring strpath lpszpath cstring strtopmostitem splitpagetreepath strpath hitem hchild m_pwndpagetree getchilditem hparent hchild m_pwndpagetree getitemtext hchild strtopmostitem hitem hchild hchild m_pwndpagetree getnextitem hchild tvgn_next hitem hitem m_pwndpagetree insertitem strtopmostitem hparent m_pwndpagetree setitemdata hitem dword_ptr strpath isempty m_btreeimages m_defaultimages getsafehandle m_pwndpagetree setitemimage hitem m_images getimagecount m_images getimagecount hitem strpath isempty hitem createpagetreeitem strpath hitem c string c tree prop sheet split page tree path c string str rest int n seperator pos 0 for n seperator pos str rest find t n seperator pos if n seperator pos 1 c string str item str rest str rest empty return str item else if n seperator pos 0 if there is an odd number of backslashes infront of the seperator than do not interpret it as separator int n backslash count 0 for int n pos n seperator pos 1 n pos 0 str rest n pos t n pos n backslash count if n backslash count 2 0 break else n seperator pos c string str item str rest left n seperator pos str item replace t t str item replace t t str rest str rest mid n seperator pos 2 return str item cstring ctreepropsheet splitpagetreepath cstring strrest nseperatorpos nseperatorpos strrest _t nseperatorpos nseperatorpos cstring stritem strrest strrest stritem nseperatorpos nbackslashcount npos nseperatorpos npos strrest npos _t npos nbackslashcount nbackslashcount nseperatorpos cstring stritem strrest nseperatorpos stritem _t _t stritem _t _t strrest strrest nseperatorpos stritem bool c tree prop sheet kill active current page hwnd h current page propsheet getcurrentpagehwnd m hwnd if is window h current page assert false return true check if the current page is really active if page is invisible an virtual empty page is the active one if is window visible h current page return true try to deactivate current page pshnotify pshn pshn hdr code psn killactive pshn hdr hwnd from m hwnd pshn hdr id from get dlg ctrlid pshn l param 0 if send message h current page wm notify pshn hdr id from lparam pshn current page does not allow page change return false hide the page show window h current page sw hide return true ctreepropsheet killactivecurrentpage hcurrentpage propsheet_getcurrentpagehwnd m_hwnd iswindow hcurrentpage iswindowvisible hcurrentpage psn_killactive hwndfrom m_hwnd idfrom getdlgctrlid lparam sendmessage hcurrentpage wm_notify idfrom showwindow hcurrentpage sw_hide htreeitem c tree prop sheet get page tree item int n page htreeitem h root tvi root special handling for root case if h root tvi root h root m pwndpagetree get next item null tvgn root check parameters if n page 0 n page get page count assert false return null if h root null assert false return null we are performing a simple linear search here because we are expecting only little data htreeitem h item h root while h item if signed m pwndpagetree get item data h item n page return h item if m pwndpagetree item has children h item htreeitem h result get page tree item n page m pwndpagetree get next item h item tvgn child if h result return h result h item m pwndpagetree get next item h item tvgn next we ve found nothing if we arrive here return h item ctreepropsheet getpagetreeitem npage hroot tvi_root hroot tvi_root hroot m_pwndpagetree getnextitem tvgn_root npage npage getpagecount hroot hitem hroot hitem m_pwndpagetree getitemdata hitem npage hitem m_pwndpagetree itemhaschildren hitem hresult getpagetreeitem npage m_pwndpagetree getnextitem hitem tvgn_child hresult hresult hitem m_pwndpagetree getnextitem hitem tvgn_next hitem bool c tree prop sheet select page tree item int n page htreeitem h item get page tree item n page if h item return false return m pwndpagetree select item h item ctreepropsheet selectpagetreeitem npage hitem getpagetreeitem npage hitem m_pwndpagetree selectitem hitem bool c tree prop sheet select current page tree item c tab ctrl p tab get tab control if is window p tab get safe hwnd return false return select page tree item p tab get cur sel ctreepropsheet selectcurrentpagetreeitem ctabctrl ptab gettabcontrol iswindow ptab getsafehwnd selectpagetreeitem ptab getcursel void c tree prop sheet update caption hwnd h page propsheet getcurrentpagehwnd get safe hwnd bool b real page is window h page is window visible h page htreeitem h item m pwndpagetree get selected item if h item return c string str caption m pwndpagetree get item text h item if empty page then update empty page message if b real page m pframe set msg text generate empty page message m stremptypagemessage str caption if no captions are displayed cancel here if m pframe get show caption return get tab control to the the images from c tab ctrl p tab ctrl get tab control if is window p tab ctrl get safe hwnd assert false return if m btreeimages get image from tree int n image m pwndpagetree get item image h item n image n image hicon h icon m images extract icon n image m pframe set caption str caption h icon if h icon destroy icon h icon else if b real page get image from hidden original tab provided by the original implementation c image list p images p tab ctrl get image list if p images tcitem ti zero memory ti sizeof ti ti mask tcif image hicon h icon null if p tab ctrl get item int m pwndpagetree get item data h item ti h icon p images extract icon ti i image m pframe set caption str caption h icon if h icon destroy icon h icon else m pframe set caption str caption else m pframe set caption str caption ctreepropsheet updatecaption hpage propsheet_getcurrentpagehwnd getsafehwnd brealpage iswindow hpage iswindowvisible hpage hitem m_pwndpagetree getselecteditem hitem cstring strcaption m_pwndpagetree getitemtext hitem brealpage m_pframe setmsgtext generateemptypagemessage m_stremptypagemessage strcaption m_pframe getshowcaption ctabctrl ptabctrl gettabcontrol iswindow ptabctrl getsafehwnd m_btreeimages nimage m_pwndpagetree getitemimage hitem nimage nimage hicon m_images extracticon nimage m_pframe setcaption strcaption hicon hicon destroyicon hicon brealpage cimagelist pimages ptabctrl getimagelist pimages zeromemory tcif_image hicon ptabctrl getitem m_pwndpagetree getitemdata hitem hicon pimages extracticon iimage m_pframe setcaption strcaption hicon hicon destroyicon hicon m_pframe setcaption strcaption m_pframe setcaption strcaption void c tree prop sheet activate previous page if is window m hwnd return if is window m pwndpagetree get safe hwnd normal tab property sheet simply use page index int n page index get active index if n page index 0 n page index get page count return int n prev index n page index 0 get page count 1 n page index 1 set active page n prev index else property sheet with page tree we need a more sophisticated handling here than simply using the page index because we won t skip empty pages so we have to walk the page tree htreeitem h item m pwndpagetree get selected item assert h item if h item return htreeitem h prev item null if h prev item m pwndpagetree get prev sibling item h item null while m pwndpagetree item has children h prev item h prev item m pwndpagetree get child item h prev item while m pwndpagetree get next sibling item h prev item h prev item m pwndpagetree get next sibling item h prev item else h prev item m pwndpagetree get parent item h item if h prev item no prev item so cycle to the last item h prev item m pwndpagetree get root item for while m pwndpagetree get next sibling item h prev item h prev item m pwndpagetree get next sibling item h prev item if m pwndpagetree item has children h prev item h prev item m pwndpagetree get child item h prev item else break if h prev item m pwndpagetree select item h prev item ctreepropsheet activatepreviouspage iswindow m_hwnd iswindow m_pwndpagetree getsafehwnd npageindex getactiveindex npageindex npageindex getpagecount nprevindex npageindex getpagecount npageindex setactivepage nprevindex hitem m_pwndpagetree getselecteditem hitem hitem hprevitem hprevitem m_pwndpagetree getprevsiblingitem hitem m_pwndpagetree itemhaschildren hprevitem hprevitem m_pwndpagetree getchilditem hprevitem m_pwndpagetree getnextsiblingitem hprevitem hprevitem m_pwndpagetree getnextsiblingitem hprevitem hprevitem m_pwndpagetree getparentitem hitem hprevitem hprevitem m_pwndpagetree getrootitem m_pwndpagetree getnextsiblingitem hprevitem hprevitem m_pwndpagetree getnextsiblingitem hprevitem m_pwndpagetree itemhaschildren hprevitem hprevitem m_pwndpagetree getchilditem hprevitem hprevitem m_pwndpagetree selectitem hprevitem void c tree prop sheet activate next page if is window m hwnd return if is window m pwndpagetree get safe hwnd normal tab property sheet simply use page index int n page index get active index if n page index 0 n page index get page count return int n next index n page index get page count 1 0 n page index 1 set active page n next index else property sheet with page tree we need a more sophisticated handling here than simply using the page index because we won t skip empty pages so we have to walk the page tree htreeitem h item m pwndpagetree get selected item assert h item if h item return htreeitem h next item null if h next item m pwndpagetree get child item h item null else if h next item m pwndpagetree get next sibling item h item null else if m pwndpagetree get parent item h item while h next item h item m pwndpagetree get parent item h item if h item break h next item m pwndpagetree get next sibling item h item if h next item no next item so cycle to the first item h next item m pwndpagetree get root item if h next item m pwndpagetree select item h next item ctreepropsheet activatenextpage iswindow m_hwnd iswindow m_pwndpagetree getsafehwnd npageindex getactiveindex npageindex npageindex getpagecount nnextindex npageindex getpagecount npageindex setactivepage nnextindex hitem m_pwndpagetree getselecteditem hitem hitem hnextitem hnextitem m_pwndpagetree getchilditem hitem hnextitem m_pwndpagetree getnextsiblingitem hitem m_pwndpagetree getparentitem hitem hnextitem hitem m_pwndpagetree getparentitem hitem hitem hnextitem m_pwndpagetree getnextsiblingitem hitem hnextitem hnextitem m_pwndpagetree getrootitem hnextitem m_pwndpagetree selectitem hnextitem bool c tree prop sheet on init dialog if m btreeviewmode be sure there are no stacked tabs because otherwise the page caption will be to large in tree view mode enable stacked tabs false initialize image list if m defaultimages get safe handle imageinfo ii m defaultimages get image info 0 ii m images create ii rc image right ii rc image left ii rc image bottom ii rc image top the app m idfltimagelistcolorflags ilc mask 0 1 else m images create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 perform default implementation bool b result c property sheet on init dialog if m btreeviewmode stop here if we would like to use tabs return b result get tab control c tab ctrl p tab get tab control if is window p tab get safe hwnd assert false return b result high color tab update image list this and hide it p tab show window sw hide p tab enable window false place another empty tab ctrl to get a frame instead c rect rect frame p tab get window rect rect frame screen to client rect frame m pframe create page frame if m pframe assert false afx throw memory exception m pframe create ws child ws visible ws clipsiblings rect frame this 0xffff m pframe show caption m bpagecaption lets make place for the tree ctrl const int n tree width m npagetreewidth const int n tree space 5 c rect rect sheet get window rect rect sheet rect sheet right n tree width set window pos null 0 0 rect sheet width rect sheet height swp nozorder swp nomove center window move child windows n tree width 0 lets calculate the rectangle for the tree ctrl c rect rect tree rect frame rect tree right rect tree left n tree width n tree space calculate caption height c tab ctrl wnd tab ctrl wnd tab ctrl create ws child ws visible ws clipsiblings rect frame this 0x1234 wnd tab ctrl insert item 0 t c rect rect frame caption wnd tab ctrl get item rect 0 rect frame caption wnd tab ctrl destroy window m pframe set caption height rect frame caption height if no caption should be displayed make the window smaller in height if m bpagecaption make frame smaller m pframe get wnd get window rect rect frame screen to client rect frame rect frame top rect frame caption height m pframe get wnd move window rect frame move all child windows up move child windows 0 rect frame caption height modify rectangle for the tree ctrl rect tree bottom rect frame caption height make us smaller c rect rect get window rect rect rect top rect frame caption height 2 rect bottom rect frame caption height rect frame caption height 2 if get parent get parent screen to client rect move window rect finally create tht tree control const dword dw tree style tvs showselalways tvs trackselect tvs haslines tvs linesatroot tvs hasbuttons m pwndpagetree create page tree object if m pwndpagetree assert false afx throw memory exception mfc7 support here thanks to rainer wollgarten if mfc ver 0x0700 using c tree ctrl create ex and it s indeed a good idea to call this one results in flawed window styles border is missing when running under winxp themed m pwndpagetree create ex ws ex clientedge ws ex noparentnotify ws tabstop ws child ws visible dw tree style rect tree this s unpagetreeid feel free to explain to me why we need to call c wnd create ex to get the proper window style for the tree view control when running under winxp look at c tree ctrl create ex and c wnd create ex to see the minor difference however this could create problems in future mfc versions m pwndpagetree c wnd create ex ws ex clientedge ws ex noparentnotify wc treeview t page tree ws tabstop ws child ws visible dw tree style rect tree this s unpagetreeid else m pwndpagetree create ex ws ex clientedge ws ex noparentnotify t sys tree view32 t page tree ws tabstop ws child ws visible dw tree style rect tree this s unpagetreeid endif m pwndpagetree set item height m pwndpagetree get item height 6 if m btreeimages m pwndpagetree set image list m images tvsil normal m pwndpagetree set image list m images tvsil state fill the tree ctrl refill page tree select item for the current page if p tab get cur sel 1 select page tree item p tab get cur sel return b result ctreepropsheet oninitdialog m_btreeviewmode enablestackedtabs m_defaultimages getsafehandle m_defaultimages getimageinfo m_images rcimage rcimage rcimage rcimage theapp m_idfltimagelistcolorflags ilc_mask m_images theapp m_idfltimagelistcolorflags ilc_mask bresult cpropertysheet oninitdialog m_btreeviewmode bresult ctabctrl ptab gettabcontrol iswindow ptab getsafehwnd bresult highcolortab updateimagelist ptab showwindow sw_hide ptab enablewindow crect rectframe ptab getwindowrect rectframe screentoclient rectframe m_pframe createpageframe m_pframe afxthrowmemoryexception m_pframe ws_child ws_visible ws_clipsiblings rectframe m_pframe showcaption m_bpagecaption ntreewidth m_npagetreewidth ntreespace crect rectsheet getwindowrect rectsheet rectsheet ntreewidth setwindowpos rectsheet rectsheet swp_nozorder swp_nomove centerwindow movechildwindows ntreewidth crect recttree rectframe recttree recttree ntreewidth ntreespace ctabctrl wndtabctrl wndtabctrl ws_child ws_visible ws_clipsiblings rectframe wndtabctrl insertitem _t crect rectframecaption wndtabctrl getitemrect rectframecaption wndtabctrl destroywindow m_pframe setcaptionheight rectframecaption m_bpagecaption m_pframe getwnd getwindowrect rectframe screentoclient rectframe rectframe rectframecaption m_pframe getwnd movewindow rectframe movechildwindows rectframecaption recttree rectframecaption crect getwindowrect rectframecaption rectframecaption rectframecaption getparent getparent screentoclient movewindow dwtreestyle tvs_showselalways tvs_trackselect tvs_haslines tvs_linesatroot tvs_hasbuttons m_pwndpagetree createpagetreeobject m_pwndpagetree afxthrowmemoryexception _mfc_ver ctreectrl createex m_pwndpagetree createex ws_ex_clientedge ws_ex_noparentnotify ws_tabstop ws_child ws_visible dwtreestyle recttree s_unpagetreeid cwnd createex ctreectrl createex cwnd createex m_pwndpagetree cwnd createex ws_ex_clientedge ws_ex_noparentnotify wc_treeview _t pagetree ws_tabstop ws_child ws_visible dwtreestyle recttree s_unpagetreeid m_pwndpagetree createex ws_ex_clientedge ws_ex_noparentnotify _t systreeview32 _t pagetree ws_tabstop ws_child ws_visible dwtreestyle recttree s_unpagetreeid m_pwndpagetree setitemheight m_pwndpagetree getitemheight m_btreeimages m_pwndpagetree setimagelist m_images tvsil_normal m_pwndpagetree setimagelist m_images tvsil_state refillpagetree ptab getcursel selectpagetreeitem ptab getcursel bresult void c tree prop sheet on destroy c property sheet on destroy if m images get safe handle m images delete image list if m pwndpagetree verify m pwndpagetree destroy window delete m pwndpagetree m pwndpagetree null if m pframe verify m pframe get wnd destroy window delete m pframe m pframe null ctreepropsheet ondestroy cpropertysheet ondestroy m_images getsafehandle m_images deleteimagelist m_pwndpagetree m_pwndpagetree destroywindow m_pwndpagetree m_pwndpagetree m_pframe m_pframe getwnd destroywindow m_pframe m_pframe lresult c tree prop sheet on add page wparam w param lparam l param lresult l result def window proc psm addpage w param l param if m btreeviewmode return l result refill page tree select current page tree item return l result ctreepropsheet onaddpage wparam lparam lresult defwindowproc psm_addpage wparam lparam m_btreeviewmode lresult refillpagetree selectcurrentpagetreeitem lresult lresult c tree prop sheet on remove page wparam w param lparam l param lresult l result def window proc psm removepage w param l param if m btreeviewmode return l result refill page tree select current page tree item return l result ctreepropsheet onremovepage wparam lparam lresult defwindowproc psm_removepage wparam lparam m_btreeviewmode lresult refillpagetree selectcurrentpagetreeitem lresult lresult c tree prop sheet on set cur sel wparam w param lparam l param lresult l result def window proc psm setcursel w param l param if m btreeviewmode return l result select current page tree item update caption return l result ctreepropsheet onsetcursel wparam lparam lresult defwindowproc psm_setcursel wparam lparam m_btreeviewmode lresult selectcurrentpagetreeitem updatecaption lresult lresult c tree prop sheet on set cur sel id wparam w param lparam l param lresult l result def window proc psm setcursel w param l param if m btreeviewmode return l result select current page tree item update caption return l result ctreepropsheet onsetcurselid wparam lparam lresult defwindowproc psm_setcursel wparam lparam m_btreeviewmode lresult selectcurrentpagetreeitem updatecaption lresult lresult c tree prop sheet on is dialog message wparam w param lparam l param msg p msg reinterpret cast msg l param if p msg message wm keydown p msg w param vk tab get key state vk control 0x8000 if get key state vk shift 0x8000 activate previous page else activate next page return true return c property sheet def window proc psm isdialogmessage w param l param ctreepropsheet onisdialogmessage wparam lparam pmsg reinterpret_cast lparam pmsg wm_keydown pmsg wparam vk_tab getkeystate vk_control getkeystate vk_shift activatepreviouspage activatenextpage cpropertysheet defwindowproc psm_isdialogmessage wparam lparam void c tree prop sheet on page tree sel changing nmhdr p notify struct lresult pl result pl result 0 if m bpagetreeselchangedactive return else m bpagetreeselchangedactive true nmtreeview p tvn reinterpret cast nmtreeview p notify struct int n page m pwndpagetree get item data p tvn item new h item bool b result if n page 0 unsigned n page m pwndpagetree get count b result kill active current page else b result set active page n page if b result prevent selection to change pl result true set focus to tree ctrl i guess that s what the user expects m pwndpagetree set focus m bpagetreeselchangedactive false return ctreepropsheet onpagetreeselchanging pnotifystruct plresult plresult m_bpagetreeselchangedactive m_bpagetreeselchangedactive ptvn reinterpret_cast pnotifystruct npage m_pwndpagetree getitemdata ptvn itemnew hitem bresult npage npage m_pwndpagetree getcount bresult killactivecurrentpage bresult setactivepage npage bresult plresult m_pwndpagetree setfocus m_bpagetreeselchangedactive void c tree prop sheet on page tree sel changed nmhdr p notify struct lresult pl result pl result 0 update caption return ctreepropsheet onpagetreeselchanged pnotifystruct plresult plresult updatecaption c preferences dlg c preferences dlg m psh dw flags psh hashelp m wndgeneral m psp dw flags psh hashelp m wnddisplay m psp dw flags psh hashelp m wndconnection m psp dw flags psh hashelp m wndserver m psp dw flags psh hashelp m wnddirectories m psp dw flags psh hashelp m wndfiles m psp dw flags psh hashelp m wndstats m psp dw flags psh hashelp m wndirc m psp dw flags psh hashelp m wndwebserver m psp dw flags psh hashelp m wndtweaks m psp dw flags psh hashelp m wndsecurity m psp dw flags psh hashelp m wndscheduler m psp dw flags psh hashelp m wndproxy m psp dw flags psh hashelp if defined debug defined use debug device m wnddebug m psp dw flags psh hashelp endif c tree prop sheet set page icon m wndgeneral t preferences c tree prop sheet set page icon m wnddisplay t display c tree prop sheet set page icon m wndconnection t connection c tree prop sheet set page icon m wndproxy t proxy c tree prop sheet set page icon m wndserver t server c tree prop sheet set page icon m wnddirectories t folders c tree prop sheet set page icon m wndfiles t transfer c tree prop sheet set page icon m wndnotify t notifications c tree prop sheet set page icon m wndstats t statistics c tree prop sheet set page icon m wndirc t irc c tree prop sheet set page icon m wndsecurity t security c tree prop sheet set page icon m wndscheduler t scheduler c tree prop sheet set page icon m wndwebserver t web c tree prop sheet set page icon m wndtweaks t tweak if defined debug defined use debug device c tree prop sheet set page icon m wnddebug t preferences endif add page m wndgeneral add page m wnddisplay add page m wndconnection add page m wndproxy add page m wndserver add page m wnddirectories add page m wndfiles add page m wndnotify add page m wndstats add page m wndirc add page m wndsecurity add page m wndscheduler add page m wndwebserver add page m wndtweaks if defined debug defined use debug device add page m wnddebug endif set tree view mode true true true set tree width 170 m ppshstartpage null m bsaveinifile false cpreferencesdlg cpreferencesdlg m_psh dwflags psh_hashelp m_wndgeneral m_psp dwflags psh_hashelp m_wnddisplay m_psp dwflags psh_hashelp m_wndconnection m_psp dwflags psh_hashelp m_wndserver m_psp dwflags psh_hashelp m_wnddirectories m_psp dwflags psh_hashelp m_wndfiles m_psp dwflags psh_hashelp m_wndstats m_psp dwflags psh_hashelp m_wndirc m_psp dwflags psh_hashelp m_wndwebserver m_psp dwflags psh_hashelp m_wndtweaks m_psp dwflags psh_hashelp m_wndsecurity m_psp dwflags psh_hashelp m_wndscheduler m_psp dwflags psh_hashelp m_wndproxy m_psp dwflags psh_hashelp _debug use_debug_device m_wnddebug m_psp dwflags psh_hashelp ctreepropsheet setpageicon m_wndgeneral _t ctreepropsheet setpageicon m_wnddisplay _t ctreepropsheet setpageicon m_wndconnection _t ctreepropsheet setpageicon m_wndproxy _t ctreepropsheet setpageicon m_wndserver _t ctreepropsheet setpageicon m_wnddirectories _t ctreepropsheet setpageicon m_wndfiles _t ctreepropsheet setpageicon m_wndnotify _t ctreepropsheet setpageicon m_wndstats _t ctreepropsheet setpageicon m_wndirc _t ctreepropsheet setpageicon m_wndsecurity _t ctreepropsheet setpageicon m_wndscheduler _t ctreepropsheet setpageicon m_wndwebserver _t ctreepropsheet setpageicon m_wndtweaks _t _debug use_debug_device ctreepropsheet setpageicon m_wnddebug _t addpage m_wndgeneral addpage m_wnddisplay addpage m_wndconnection addpage m_wndproxy addpage m_wndserver addpage m_wnddirectories addpage m_wndfiles addpage m_wndnotify addpage m_wndstats addpage m_wndirc addpage m_wndsecurity addpage m_wndscheduler addpage m_wndwebserver addpage m_wndtweaks _debug use_debug_device addpage m_wnddebug settreeviewmode settreewidth m_ppshstartpage m_bsaveinifile c preferences dlg c preferences dlg cpreferencesdlg cpreferencesdlg void c preferences dlg localize set title remove ambersand get res string ids em prefs m wndgeneral localize m wnddisplay localize m wndconnection localize m wndserver localize m wnddirectories localize m wndfiles localize m wndstats localize m wndnotify localize m wndirc localize m wndsecurity localize m wndtweaks localize m wndwebserver localize m wndscheduler localize m wndproxy localize int c 0 c tree ctrl p tree get page tree control if p tree p tree set item text get page tree item c remove ambersand get res string ids pw general p tree set item text get page tree item c remove ambersand get res string ids pw display p tree set item text get page tree item c remove ambersand get res string ids pw connection p tree set item text get page tree item c remove ambersand get res string ids pw proxy p tree set item text get page tree item c remove ambersand get res string ids pw server p tree set item text get page tree item c remove ambersand get res string ids pw dir p tree set item text get page tree item c remove ambersand get res string ids pw files p tree set item text get page tree item c remove ambersand get res string ids pw ekdev options p tree set item text get page tree item c remove ambersand get res string ids statssetupinfo p tree set item text get page tree item c remove ambersand get res string ids irc p tree set item text get page tree item c remove ambersand get res string ids security p tree set item text get page tree item c remove ambersand get res string ids scheduler p tree set item text get page tree item c remove ambersand get res string ids pw ws p tree set item text get page tree item c remove ambersand get res string ids pw tweak if defined debug defined use debug device p tree set item text get page tree item c t debug endif update caption cpreferencesdlg settitle removeambersand getresstring ids_em_prefs m_wndgeneral m_wnddisplay m_wndconnection m_wndserver m_wnddirectories m_wndfiles m_wndstats m_wndnotify m_wndirc m_wndsecurity m_wndtweaks m_wndwebserver m_wndscheduler m_wndproxy ctreectrl ptree getpagetreecontrol ptree ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_general ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_display ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_connection ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_proxy ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_server ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_dir ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_files ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_ekdev_options ptree setitemtext getpagetreeitem removeambersand getresstring ids_statssetupinfo ptree setitemtext getpagetreeitem removeambersand getresstring ids_irc ptree setitemtext getpagetreeitem removeambersand getresstring ids_security ptree setitemtext getpagetreeitem removeambersand getresstring ids_scheduler ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_ws ptree setitemtext getpagetreeitem removeambersand getresstring ids_pw_tweak _debug use_debug_device ptree setitemtext getpagetreeitem _t updatecaption void c preferences dlg set start page uint u start pageid m ppshstartpage makeintresource u start pageid cpreferencesdlg setstartpage ustartpageid m_ppshstartpage ustartpageid bool c preferences dlg on init dialog assert m bsaveinifile bool b result c tree prop sheet on init dialog init window styles this for int i 0 i m pages get size i if get page i m psp psz template m ppshstartpage set active page i break localize return b result cpreferencesdlg oninitdialog m_bsaveinifile bresult ctreepropsheet oninitdialog initwindowstyles m_pages getsize getpage m_psp psztemplate m_ppshstartpage setactivepage bresult bool c preferences dlg on command wparam w param lparam l param if w param id help on help return true if w param idok w param id apply now m bsaveinifile true return super on command w param l param cpreferencesdlg oncommand wparam lparam wparam id_help onhelp wparam wparam id_apply_now m_bsaveinifile __super oncommand wparam lparam void c preferences dlg on destroy c tree prop sheet on destroy if m bsaveinifile the prefs save m bsaveinifile false m ppshstartpage get page get active index m psp psz template cpreferencesdlg ondestroy ctreepropsheet ondestroy m_bsaveinifile theprefs m_bsaveinifile m_ppshstartpage getpage getactiveindex m_psp psztemplate void c preferences dlg on help int i cur sel get active index if i cur sel 0 c property page p page get page i cur sel if p page helpinfo hi 0 hi cb size sizeof hi hi i context type helpinfo window hi i ctrl id 0 hi h item handle p page m hwnd hi dw context id 0 p page send message wm help 0 lparam hi return the app show help 0 help contents cpreferencesdlg onhelp icursel getactiveindex icursel cpropertypage ppage getpage icursel ppage cbsize icontexttype helpinfo_window ictrlid hitemhandle ppage m_hwnd dwcontextid ppage sendmessage wm_help theapp showhelp help_contents bool c preferences dlg on help info helpinfo p help info on help return true cpreferencesdlg onhelpinfo phelpinfo onhelp c dialog c connection wizard dlg idd p parent m ios 0 m itotaldownload 0 m icnwnd null cdialog cconnectionwizarddlg pparent m_ios m_itotaldownload m_icnwnd c connection wizard dlg c connection wizard dlg if m icnwnd verify destroy icon m icnwnd cconnectionwizarddlg cconnectionwizarddlg m_icnwnd destroyicon m_icnwnd void c connection wizard dlg localize set window text get res string ids wizard get dlg item idc wiz os frame set window text get res string ids wiz os frame get dlg item idc wiz concurentdown frame set window text get res string ids concurdwl get dlg item idc wiz hotbutton frame set window text get res string ids wiz ctframe get dlg item idc wiz trueupload text set window text get res string ids wiz trueupload text get dlg item idc wiz truedownload text set window text get res string ids wiz truedownload text get dlg item idc kbits set window text get res string ids kbitssec get dlg item idc kbytes set window text get res string ids kbytessec get dlg item idc wiz apply button set window text get res string ids pw apply get dlg item idc wiz cancel button set window text get res string ids cancel cconnectionwizarddlg setwindowtext getresstring ids_wizard getdlgitem idc_wiz_os_frame setwindowtext getresstring ids_wiz_os_frame getdlgitem idc_wiz_concurentdown_frame setwindowtext getresstring ids_concurdwl getdlgitem idc_wiz_hotbutton_frame setwindowtext getresstring ids_wiz_ctframe getdlgitem idc_wiz_trueupload_text setwindowtext getresstring ids_wiz_trueupload_text getdlgitem idc_wiz_truedownload_text setwindowtext getresstring ids_wiz_truedownload_text getdlgitem idc_kbits setwindowtext getresstring ids_kbitssec getdlgitem idc_kbytes setwindowtext getresstring ids_kbytessec getdlgitem idc_wiz_apply_button setwindowtext getresstring ids_pw_apply getdlgitem idc_wiz_cancel_button setwindowtext getresstring ids_cancel void c connection wizard dlg set custom items activation bool b active m provider get selection mark 1 get dlg item idc wiz trueupload box enable window b active get dlg item idc wiz truedownload box enable window b active get dlg item idc kbits enable window b active get dlg item idc kbytes enable window b active cconnectionwizarddlg setcustomitemsactivation bactive m_provider getselectionmark getdlgitem idc_wiz_trueupload_box enablewindow bactive getdlgitem idc_wiz_truedownload_box enablewindow bactive getdlgitem idc_kbits enablewindow bactive getdlgitem idc_kbytes enablewindow bactive bool c connection wizard dlg on init dialog c dialog on init dialog init window styles this set icon m icnwnd the app load icon t wizard false if detect win version winver 95 detect win version winver 98 detect win version winver me check radio button idc wiz xp radio idc wiz me radio idc wiz me radio m ios 1 else check radio button idc wiz xp radio idc wiz me radio idc wiz xp radio m ios 0 check radio button idc wiz lowdown radio idc wiz highdown radio idc wiz lowdown radio check radio button idc kbits idc kbytes idc kbits set dlg item int idc wiz truedownload box 0 false set dlg item int idc wiz trueupload box 0 false m provider insert column 0 get res string ids pw connection lvcfmt left 150 m provider insert column 1 get res string ids wiz down lvcfmt left 85 m provider insert column 2 get res string ids wiz up lvcfmt left 85 m provider set extended style m provider get extended style lvs ex fullrowselect m provider insert item 0 get res string ids unknown m provider set item text 0 1 t m provider set item text 0 2 t m provider insert item 1 get res string ids wizard custom m provider set item text 1 1 get res string ids wizard enterbelow m provider set item text 1 2 get res string ids wizard enterbelow m provider insert item 2 t 56 k modem m provider set item text 2 1 t 56 m provider set item text 2 2 t 56 m provider insert item 3 t isdn m provider set item text 3 1 t 64 m provider set item text 3 2 t 64 m provider insert item 4 t isdn 2x m provider set item text 4 1 t 128 m provider set item text 4 2 t 128 m provider insert item 5 t t dsl 1000 t arcor freenet 1 1 m provider set item text 5 1 t 1024 m provider set item text 5 2 t 128 m provider insert item 6 t t dsl 1500 t m provider set item text 6 1 t 1536 m provider set item text 6 2 t 192 m provider insert item 7 t t dsl 2000 t arcor freenet tiscali alice m provider set item text 7 1 t 2048 m provider set item text 7 2 t 192 m provider insert item 8 t versatel dsl 2000 m provider set item text 8 1 t 2048 m provider set item text 8 2 t 384 m provider insert item 9 t t dsl 3000 t arcor m provider set item text 9 1 t 3072 m provider set item text 9 2 t 384 m provider insert item 10 t t dsl 6000 t arcor m provider set item text 10 1 t 6016 m provider set item text 10 2 t 576 m provider insert item 11 t dsl 6000 tiscali freenet 1 1 m provider set item text 11 1 t 6016 m provider set item text 11 2 t 572 m provider insert item 12 t dsl 6000 lycos alice m provider set item text 12 1 t 6016 m provider set item text 12 2 t 512 m provider insert item 13 t versatel dsl 6000 m provider set item text 13 1 t 6144 m provider set item text 13 2 t 512 m provider insert item 14 t cable m provider set item text 14 1 t 187 m provider set item text 16 2 t 32 m provider insert item 15 t cable m provider set item text 15 1 t 187 m provider set item text 17 2 t 64 m provider insert item 16 t t1 m provider set item text 16 1 t 1500 m provider set item text 18 2 t 1500 m provider insert item 17 t t3 m provider set item text 17 1 t 44 mbps m provider set item text 19 2 t 44 mbps m provider set selection mark 0 m provider set item state 0 lvis focused lvis selected lvis focused lvis selected set custom items activation localize return true cconnectionwizarddlg oninitdialog cdialog oninitdialog initwindowstyles seticon m_icnwnd theapp loadicon _t detectwinversion _winver_95_ detectwinversion _winver_98_ detectwinversion _winver_me_ checkradiobutton idc_wiz_xp_radio idc_wiz_me_radio idc_wiz_me_radio m_ios checkradiobutton idc_wiz_xp_radio idc_wiz_me_radio idc_wiz_xp_radio m_ios checkradiobutton idc_wiz_lowdown_radio idc_wiz_highdown_radio idc_wiz_lowdown_radio checkradiobutton idc_kbits idc_kbytes idc_kbits setdlgitemint idc_wiz_truedownload_box setdlgitemint idc_wiz_trueupload_box m_provider insertcolumn getresstring ids_pw_connection lvcfmt_left m_provider insertcolumn getresstring ids_wiz_down lvcfmt_left m_provider insertcolumn getresstring ids_wiz_up lvcfmt_left m_provider setextendedstyle m_provider getextendedstyle lvs_ex_fullrowselect m_provider insertitem getresstring ids_unknown m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem getresstring ids_wizard_custom m_provider setitemtext getresstring ids_wizard_enterbelow m_provider setitemtext getresstring ids_wizard_enterbelow m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider insertitem _t m_provider setitemtext _t m_provider setitemtext _t m_provider setselectionmark m_provider setitemstate lvis_focused lvis_selected lvis_focused lvis_selected setcustomitemsactivation void c connection wizard dlg do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc providers m provider ddx radio pdx idc wiz xp radio m ios ddx radio pdx idc wiz lowdown radio m itotaldownload cconnectionwizarddlg dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_providers m_provider ddx_radio idc_wiz_xp_radio m_ios ddx_radio idc_wiz_lowdown_radio m_itotaldownload void c connection wizard dlg on bn clicked apply if m provider get selection mark 0 change the upload download to unlimited and dont touch other stuff keep the default values the prefs max graph upload rate unlimited the prefs max graph download rate 96 the prefs maxupload unlimited the prefs maxdownload unlimited the app emuledlg statisticswnd seta range false the prefs get max graph upload rate true the app emuledlg statisticswnd seta range true the prefs max graph download rate the app emuledlg preferenceswnd m wndconnection load settings c dialog onok return tchar buffer 510 int upload download if get dlg item idc wiz truedownload box get window text length get dlg item idc wiz truedownload box get window text buffer 20 download tstoi buffer else download 0 if get dlg item idc wiz trueupload box get window text length get dlg item idc wiz trueupload box get window text buffer 20 upload tstoi buffer else upload 0 if is dlg button checked idc kbits 1 upload upload 8 1000 512 1024 download download 8 1000 512 1024 else upload upload 1000 512 1024 download download 1000 512 1024 the prefs max graph download rate download the prefs max graph upload rate upload if upload 0 download 0 the prefs maxupload uint16 upload 4l 5 if upload 4 download upload 3 the prefs maxdownload the prefs maxupload 3 download upload 3 if upload 10 download upload 4 the prefs maxdownload the prefs maxupload 4 download upload 4 else the prefs maxdownload uint16 download 9l 10 the app emuledlg statisticswnd seta range false the prefs max graph upload rate the app emuledlg statisticswnd seta range true the prefs max graph download rate if m ios 1 the prefs maxconnections 50 else if upload 7 the prefs maxconnections 80 else if upload 12 the prefs maxconnections 200 else if upload 25 the prefs maxconnections 400 else if upload 37 the prefs maxconnections 600 else the prefs maxconnections 800 if m ios 1 download download 2 if download 7 switch m itotaldownload case 0 the prefs maxsourceperfile 100 break case 1 the prefs maxsourceperfile 60 break case 2 the prefs maxsourceperfile 40 break else if download 62 switch m itotaldownload case 0 the prefs maxsourceperfile 300 break case 1 the prefs maxsourceperfile 200 break case 2 the prefs maxsourceperfile 100 break else if download 187 switch m itotaldownload case 0 the prefs maxsourceperfile 500 break case 1 the prefs maxsourceperfile 400 break case 2 the prefs maxsourceperfile 350 break else if download 312 switch m itotaldownload case 0 the prefs maxsourceperfile 800 break case 1 the prefs maxsourceperfile 600 break case 2 the prefs maxsourceperfile 400 break else switch m itotaldownload case 0 the prefs maxsourceperfile 1000 break case 1 the prefs maxsourceperfile 750 break case 2 the prefs maxsourceperfile 500 break the app emuledlg preferenceswnd m wndconnection load settings c dialog onok cconnectionwizarddlg onbnclickedapply m_provider getselectionmark theprefs maxgraphuploadrate theprefs maxgraphdownloadrate theprefs theprefs theapp setarange theprefs getmaxgraphuploadrate theapp setarange theprefs maxgraphdownloadrate theapp m_wndconnection loadsettings cdialog getdlgitem idc_wiz_truedownload_box getwindowtextlength getdlgitem idc_wiz_truedownload_box getwindowtext _tstoi getdlgitem idc_wiz_trueupload_box getwindowtextlength getdlgitem idc_wiz_trueupload_box getwindowtext _tstoi isdlgbuttonchecked idc_kbits theprefs maxgraphdownloadrate theprefs maxgraphuploadrate theprefs theprefs theprefs theprefs theprefs theprefs theapp setarange theprefs maxgraphuploadrate theapp setarange theprefs maxgraphdownloadrate m_ios theprefs theprefs theprefs theprefs theprefs theprefs m_ios m_itotaldownload theprefs theprefs theprefs m_itotaldownload theprefs theprefs theprefs m_itotaldownload theprefs theprefs theprefs m_itotaldownload theprefs theprefs theprefs m_itotaldownload theprefs theprefs theprefs theapp m_wndconnection loadsettings cdialog void c connection wizard dlg on bn clicked cancel c dialog on cancel cconnectionwizarddlg onbnclickedcancel cdialog oncancel void c connection wizard dlg on bn clicked wiz radio os ntxp m ios 0 cconnectionwizarddlg onbnclickedwizradioosntxp m_ios void c connection wizard dlg on bn clicked wiz radio us98me m ios 1 cconnectionwizarddlg onbnclickedwizradious98me m_ios void c connection wizard dlg on bn clicked wiz lowdownload radio m itotaldownload 0 cconnectionwizarddlg onbnclickedwizlowdownloadradio m_itotaldownload void c connection wizard dlg on bn clicked wiz mediumdownload radio m itotaldownload 1 cconnectionwizarddlg onbnclickedwizmediumdownloadradio m_itotaldownload void c connection wizard dlg on bn clicked wiz highdownload radio m itotaldownload 2 cconnectionwizarddlg onbnclickedwizhighdownloadradio m_itotaldownload void c connection wizard dlg on bn clicked wiz reset button set dlg item int idc wiz truedownload box 0 false set dlg item int idc wiz trueupload box 0 false cconnectionwizarddlg onbnclickedwizresetbutton setdlgitemint idc_wiz_truedownload_box setdlgitemint idc_wiz_trueupload_box void c connection wizard dlg onnm click providers nmhdr pnmhdr lresult p result set custom items activation uint up down switch m provider get selection mark case 0 down 0 up 0 break case 1 down the prefs max graph download rate 1024 500 1000 8 up the prefs get max graph upload rate true 1024 500 1000 8 break case 2 down 56 up 33 break case 3 down 64 up 64 break case 4 down 128 up 128 break case 5 down 1024 up 128 break case 6 down 1536 up 192 break case 7 down 2048 up 192 break case 8 down 2048 up 384 break case 9 down 3072 up 384 break case 10 down 6016 up 576 break case 11 down 6016 up 572 break case 12 down 6016 up 512 break case 13 down 6144 up 512 break case 14 down 187 up 32 break case 15 down 187 up 64 break case 16 down 1500 up 1500 break case 17 down 44000 up 44000 break default return set dlg item int idc wiz truedownload box down false set dlg item int idc wiz trueupload box up false check radio button idc kbits idc kbytes idc kbits p result 0 cconnectionwizarddlg onnmclickproviders presult setcustomitemsactivation m_provider getselectionmark theprefs maxgraphdownloadrate theprefs getmaxgraphuploadrate setdlgitemint idc_wiz_truedownload_box setdlgitemint idc_wiz_trueupload_box checkradiobutton idc_kbits idc_kbytes idc_kbits presult c statistics tree c statistics tree cstatisticstree cstatisticstree c statistics tree c statistics tree if mnuhtml verify mnuhtml destroy menu if mnu context verify mnu context destroy menu cstatisticstree cstatisticstree destroymenu mnucontext mnucontext destroymenu bool c statistics tree on command wparam w param lparam l param switch w param case mp stattree reset if afx message box get res string ids stats mbreset txt mb yesno mb iconexclamation idno break the prefs reset cumulative statistics add log line false get res string ids stats nforeset the app emuledlg statisticswnd show statistics c string my buffer my buffer format get res string ids stats lastresetstatic the prefs get stats last reset str false get parent get dlg item idc static lastreset set window text my buffer break case mp stattree restore if afx message box get res string ids stats mbrestore txt mb yesno mb iconquestion idno break if the prefs load stats 1 log error log statusbar get res string ids err nostatbkup else add log line false get res string ids stats nfoloadedbkup c string my buffer my buffer format get res string ids stats lastresetstatic the prefs get stats last reset str false get parent get dlg item idc static lastreset set window text my buffer break case mp stattree expandmain set redraw false expand all true goto lbl save expanded case mp stattree expandall set redraw false expand all goto lbl save expanded case mp stattree collapseall set redraw false collapse all lbl save expanded the prefs set expanded tree items get expanded mask set redraw true break case mp stattree copysel case mp stattree copyvis case mp stattree copyall copy text w param break case mp stattree htmlcopysel case mp stattree htmlcopyvis case mp stattree htmlcopyall copyhtml w param break case mp stattree htmlexport exporthtml break return true cstatisticstree oncommand wparam lparam wparam mp_stattree_reset afxmessagebox getresstring ids_stats_mbreset_txt mb_yesno mb_iconexclamation theprefs resetcumulativestatistics addlogline getresstring ids_stats_nforeset theapp showstatistics cstring mybuffer mybuffer getresstring ids_stats_lastresetstatic theprefs getstatslastresetstr getparent getdlgitem idc_static_lastreset setwindowtext mybuffer mp_stattree_restore afxmessagebox getresstring ids_stats_mbrestore_txt mb_yesno mb_iconquestion theprefs loadstats logerror log_statusbar getresstring ids_err_nostatbkup addlogline getresstring ids_stats_nfoloadedbkup cstring mybuffer mybuffer getresstring ids_stats_lastresetstatic theprefs getstatslastresetstr getparent getdlgitem idc_static_lastreset setwindowtext mybuffer mp_stattree_expandmain setredraw expandall lblsaveexpanded mp_stattree_expandall setredraw expandall lblsaveexpanded mp_stattree_collapseall setredraw collapseall lblsaveexpanded theprefs setexpandedtreeitems getexpandedmask setredraw mp_stattree_copysel mp_stattree_copyvis mp_stattree_copyall copytext wparam mp_stattree_htmlcopysel mp_stattree_htmlcopyvis mp_stattree_htmlcopyall wparam mp_stattree_htmlexport void c statistics tree onl button up uint n flags c point point the app emuledlg statisticswnd show statistics c tree ctrl onl button up n flags point cstatisticstree onlbuttonup nflags cpoint theapp showstatistics ctreectrl onlbuttonup nflags void c statistics tree onr button down uint n flags c point point uint u hit flags htreeitem h item hit test point u hit flags if h item null u hit flags tvht onitem select h item tvgn caret set item state h item tvis selected tvis selected return cstatisticstree onrbuttondown nflags cpoint uhitflags hitem hittest uhitflags hitem uhitflags tvht_onitem hitem tvgn_caret setitemstate hitem tvis_selected tvis_selected void c statistics tree on context menu c wnd p wnd c point point do menu point tpm leftalign tpm rightbutton cstatisticstree oncontextmenu cwnd pwnd cpoint domenu tpm_leftalign tpm_rightbutton void c statistics tree on item expanded nmhdr pnmhdr lresult p result if m bexpandingall the prefs set expanded tree items get expanded mask cstatisticstree onitemexpanded presult m_bexpandingall theprefs setexpandedtreeitems getexpandedmask void c statistics tree init m bexpandingall false cstatisticstree m_bexpandingall void c statistics tree exporthtml c file html file tchar sz dir max path get current directory max path sz dir c file dialog save as dlg false t html t e mule statistics html ofn hidereadonly ofn overwriteprompt ofn explorer t html files html html all files this 0 if save as dlg do modal idok c string strhtml strhtml format c string html r n header r n title e mule s s title r n meta http equiv content type content text html charset utf 8 style type text css r n pghdr color 000f80 font bold 12pt 14pt verdana courier new helvetica r n pghdr2 color 000f80 font bold 10pt 12pt verdana courier new helvetica r n img border 0px r n a text decoration none r n sec color 000000 font bold 9pt 11pt verdana courier new helvetica r n item color 000000 font normal 8pt 10pt verdana courier new helvetica r n bdy color 000000 font normal 8pt 10pt verdana courier new helvetica background color ffffff r n style r n header r n script language java script1 2 type text javascript r n function obj menu r n r n return navigator app name microsoft internet explorer this menu document get element by id menu r n r n function togglevisible treepart r n r n if this obj t treepart style visibility hidden r n r n this obj t treepart style position r n this obj t treepart style visibility r n document i treepart src stats visible gif r n r n else r n r n this obj t treepart style position absolute r n this obj t treepart style visibility hidden r n document i treepart src stats hidden gif r n r n r n script r n body id bdy r n span id pghdr b e mule s b span br span id pghdr2 s s span r n br br r n s body html get res string ids sf statistics the prefs get user nick get res string ids sf statistics get res string ids cd uname the prefs get user nick gethtml for export html file open save as dlg get path name c file mode create c file mode write c file share deny write c stringa str htmla wc2utf8 strhtml html file write str htmla str htmla get length html file close static const tchar const s apcfilenames t stats 0 gif t stats 1 gif t stats 2 gif t stats 3 gif t stats 4 gif t stats 5 gif t stats 6 gif t stats 7 gif t stats 8 gif t stats 9 gif t stats 10 gif t stats 11 gif t stats 12 gif t stats 13 gif t stats 14 gif t stats 15 gif t stats 16 gif t stats 17 gif t stats hidden gif t stats space gif t stats visible gif c string str dst save as dlg get path name left save as dlg get path name get length save as dlg get file name get length ec what if directory name filename this should fix this c string str src the prefs get app dir str src t web server for unsigned ui 0 ui arrsize s apcfilenames ui copy file str src s apcfilenames ui str dst s apcfilenames ui false set current directory sz dir cstatisticstree cfile htmlfile szdir max_path getcurrentdirectory max_path szdir cfiledialog saveasdlg _t _t emule ofn_hidereadonly ofn_overwriteprompt ofn_explorer _t saveasdlg domodal cstring cstring emule javascript1 appname getelementbyid stats_visible stats_hidden emule getresstring ids_sf_statistics theprefs getusernick getresstring ids_sf_statistics getresstring ids_cd_uname theprefs getusernick gethtmlforexport htmlfile saveasdlg getpathname cfile modecreate cfile modewrite cfile sharedenywrite cstringa strhtmla htmlfile strhtmla strhtmla getlength htmlfile s_apcfilenames _t stats_0 _t stats_1 _t stats_2 _t stats_3 _t stats_4 _t stats_5 _t stats_6 _t stats_7 _t stats_8 _t stats_9 _t stats_10 _t stats_11 _t stats_12 _t stats_13 _t stats_14 _t stats_15 _t stats_16 _t stats_17 _t stats_hidden _t stats_space _t stats_visible cstring strdst saveasdlg getpathname saveasdlg getpathname getlength saveasdlg getfilename getlength cstring strsrc theprefs getappdir strsrc _t webserver s_apcfilenames copyfile strsrc s_apcfilenames strdst s_apcfilenames setcurrentdirectory szdir bool c statistics tree copyhtml int copy mode switch copy mode case mp stattree htmlcopysel htreeitem selected item get selected item if selected item null c string thehtml gethtml true selected item if thehtml is empty return false the app copy text to clipboard thehtml return true return false case mp stattree htmlcopyvis c string thehtml gethtml if thehtml is empty return false the app copy text to clipboard thehtml return true case mp stattree htmlcopyall c string thehtml gethtml false if thehtml is empty return false the app copy text to clipboard thehtml return true return false cstatisticstree copymode copymode mp_stattree_htmlcopysel selecteditem getselecteditem selecteditem cstring selecteditem isempty theapp copytexttoclipboard mp_stattree_htmlcopyvis cstring isempty theapp copytexttoclipboard mp_stattree_htmlcopyall cstring isempty theapp copytexttoclipboard c string c statistics tree gethtml bool only visible htreeitem the item int the item level bool first item htreeitem h current if the item null if only visible the app emuledlg statisticswnd show statistics true h current get root item copy all vis or copy all else h current the item c string str buffer if first item str buffer format t font face tahoma verdana courier new helvetica size 2 r n b e mule v s s s b r n br br r n the app m strcurversionlong get res string ids sf statistics the prefs get user nick while h current null c string str item if is bold h current str item t b get item text h current t b else str item get item text h current for int i 0 i the item level i str buffer t nbsp nbsp nbsp if the item level 0 str buffer append t n str buffer str item t br if item has children h current only visible is expanded h current str buffer gethtml only visible get child item h current the item level 1 false h current get next item h current tvgn next if first item the item null break copy selected branch was used so we don t want to copy all branches at this level only the one that was selected if first item str buffer t font return str buffer cstring cstatisticstree onlyvisible theitem theitemlevel firstitem hcurrent theitem onlyvisible theapp showstatistics hcurrent getrootitem hcurrent theitem cstring strbuffer firstitem strbuffer _t emule theapp m_strcurversionlong getresstring ids_sf_statistics theprefs getusernick hcurrent cstring stritem isbold hcurrent stritem _t getitemtext hcurrent _t stritem getitemtext hcurrent theitemlevel strbuffer _t theitemlevel strbuffer _t strbuffer stritem _t itemhaschildren hcurrent onlyvisible isexpanded hcurrent strbuffer onlyvisible getchilditem hcurrent theitemlevel hcurrent getnextitem hcurrent tvgn_next firstitem theitem firstitem strbuffer _t strbuffer c string c statistics tree gethtml for export htreeitem the item int the item level bool first item static int s ihtmlid if the item null the item level 0 first item s ihtmlid 0 c string str buffer str item str image str child str tab int n image 0 n selected image 0 htreeitem h current c string str div start str div str diva str div end strj str name str buffer empty if first item h current get root item else h current the item while h current null str item empty if item has children h current s ihtmlid strj format t d s ihtmlid if is expanded h current str child t visible str div t div id t strj t style margin left 18px else str child t hidden str div t div id t strj t style margin left 18px visibility hidden position absolute str div start t a href javascript togglevisible strj t str div end t div str diva t a str name t name i strj t else str child t space str div t str div start t str div end t str name t str buffer t n for int i 0 i the item level i str buffer t t str item str div start str item t img str name t src stats str child t gif align middle nbsp str item str diva if get item image h current n image n selected image str image format t u n image else str image format t u 0 str item t img src stats str image t gif align middle nbsp if is bold h current str item t b get item text h current t b else str item get item text h current if the item level 0 str buffer append t n str buffer str item t br if item has children h current str tab t n for int i 0 i the item level i str tab t t str buffer str tab str div str buffer str tab t t gethtml for export get child item h current the item level 1 false str buffer str tab str div end h current get next item h current tvgn next return str buffer cstring cstatisticstree gethtmlforexport theitem theitemlevel firstitem s_ihtmlid theitem theitemlevel firstitem s_ihtmlid cstring strbuffer stritem strimage strchild strtab nimage nselectedimage hcurrent cstring strdivstart strdiv strdiva strdivend strname strbuffer firstitem hcurrent getrootitem hcurrent theitem hcurrent stritem itemhaschildren hcurrent s_ihtmlid _t s_ihtmlid isexpanded hcurrent strchild _t strdiv _t _t strchild _t strdiv _t _t strdivstart _t _t strdivend _t strdiva _t strname _t _t strchild _t strdiv _t strdivstart _t strdivend _t strname _t strbuffer _t theitemlevel strbuffer _t stritem strdivstart stritem _t strname _t stats_ strchild _t stritem strdiva getitemimage hcurrent nimage nselectedimage strimage _t nimage strimage _t stritem _t stats_ strimage _t isbold hcurrent stritem _t getitemtext hcurrent _t stritem getitemtext hcurrent theitemlevel strbuffer _t strbuffer stritem _t itemhaschildren hcurrent strtab _t theitemlevel strtab _t strbuffer strtab strdiv strbuffer strtab _t gethtmlforexport getchilditem hcurrent theitemlevel strbuffer strtab strdivend hcurrent getnextitem hcurrent tvgn_next strbuffer bool c statistics tree copy text int copy mode switch copy mode case mp stattree copysel htreeitem selected item get selected item if selected item null c string the text get text true selected item if the text is empty return false the app copy text to clipboard the text return true return false case mp stattree copyvis c string the text get text if the text is empty return false the app copy text to clipboard the text return true case mp stattree copyall c string the text get text false if the text is empty return false the app copy text to clipboard the text return true return false cstatisticstree copytext copymode copymode mp_stattree_copysel selecteditem getselecteditem selecteditem cstring thetext gettext selecteditem thetext isempty theapp copytexttoclipboard thetext mp_stattree_copyvis cstring thetext gettext thetext isempty theapp copytexttoclipboard thetext mp_stattree_copyall cstring thetext gettext thetext isempty theapp copytexttoclipboard thetext c string c statistics tree get text bool only visible htreeitem the item int the item level bool first item bool b print header first item htreeitem h current if the item null h current get root item copy all vis or copy all else if b print header item has children the item is expanded the item b print header false h current the item c string str buffer if b print header str buffer format t e mule v s s s r n r n the app m strcurversionlong get res string ids sf statistics the prefs get user nick while h current null for int i 0 i the item level i str buffer t str buffer get item text h current if b print header first item str buffer t r n if item has children h current only visible is expanded h current str buffer get text only visible get child item h current the item level 1 false h current get next item h current tvgn next if first item the item null break copy selected branch was used so we don t want to copy all branches at this level only the one that was selected return str buffer cstring cstatisticstree gettext onlyvisible theitem theitemlevel firstitem bprintheader firstitem hcurrent theitem hcurrent getrootitem bprintheader itemhaschildren theitem isexpanded theitem bprintheader hcurrent theitem cstring strbuffer bprintheader strbuffer _t emule theapp m_strcurversionlong getresstring ids_sf_statistics theprefs getusernick hcurrent theitemlevel strbuffer _t strbuffer getitemtext hcurrent bprintheader firstitem strbuffer _t itemhaschildren hcurrent onlyvisible isexpanded hcurrent strbuffer gettext onlyvisible getchilditem hcurrent theitemlevel hcurrent getnextitem hcurrent tvgn_next firstitem theitem strbuffer c string c statistics tree get item text htreeitem the item if the item null return t tvitem item tchar sz text 1024 item mask tvif text tvif handle item h item the item item psz text sz text item cch text max 1024 if get item item return c string item psz text return t cstring cstatisticstree getitemtext theitem theitem _t sztext tvif_text tvif_handle hitem theitem psztext sztext cchtextmax getitem cstring psztext _t c string c statistics tree get item text htreeitem the item int get part if the item null return t c string full text return text full text get item text the item if full text is empty return t int pos separator full text find t if pos separator 1 return text get part get title full text t return return text if get part get title return text full text left pos separator else if get part get value return text full text mid pos separator 2 else return text t return return text cstring cstatisticstree getitemtext theitem getpart theitem _t cstring fulltext returntext fulltext getitemtext theitem fulltext isempty _t posseparator fulltext _t posseparator returntext getpart get_title fulltext _t returntext getpart get_title returntext fulltext posseparator getpart get_value returntext fulltext posseparator returntext _t returntext bool c statistics tree is bold htreeitem the item uint state bold get item state the item tvis bold return state bold tvis bold cstatisticstree isbold theitem statebold getitemstate theitem tvis_bold statebold tvis_bold bool c statistics tree is expanded htreeitem the item uint state expanded get item state the item tvis expanded return state expanded tvis expanded cstatisticstree isexpanded theitem stateexpanded getitemstate theitem tvis_expanded stateexpanded tvis_expanded bool c statistics tree check state htreeitem h item uint state uint state generic get item state h item state return state generic state cstatisticstree checkstate hitem stategeneric getitemstate hitem stategeneric void c statistics tree do menu c point cursor pos get cursor pos cursor pos do menu cursor pos cstatisticstree domenu cpoint cursorpos getcursorpos cursorpos domenu cursorpos void c statistics tree do menu c point do where do menu do where tpm rightalign tpm rightbutton cstatisticstree domenu cpoint dowhere domenu dowhere tpm_rightalign tpm_rightbutton void c statistics tree do menu c point do where uint n flags c file find find back up c string my buffer int my flags my buffer format t sstatbkup ini the prefs get config dir if find back up find file my buffer my flags mf grayed else my flags mf string mnu context create popup menu mnu context add menu title get res string ids stats mnutreetitle true mnu context append menu mf string mp stattree reset get res string ids stats bnreset t delete mnu context append menu my flags mp stattree restore get res string ids stats bnrestore t restore mnu context append menu mf separator mnu context append menu mf string mp stattree expandmain get res string ids stats mnutreeexpandmain t expandmain mnu context append menu mf string mp stattree expandall get res string ids stats mnutreeexpandall t expandall mnu context append menu mf string mp stattree collapseall get res string ids stats mnutreecollapseall t collapse mnu context append menu mf separator mnu context append menu mf string mp stattree copysel get res string ids stats mnutreecpysel t copy mnu context append menu mf string mp stattree copyvis get res string ids stats mnutreecpyvis t copyvisible mnu context append menu mf string mp stattree copyall get res string ids stats mnutreecpyall t copyselected mnu context append menu mf separator mnuhtml create menu mnuhtml add menu title null true mnuhtml append menu mf string mp stattree htmlcopysel get res string ids stats mnutreecpysel t copy mnuhtml append menu mf string mp stattree htmlcopyvis get res string ids stats mnutreecpyvis t copyvisible mnuhtml append menu mf string mp stattree htmlcopyall get res string ids stats mnutreecpyall t copyselected mnuhtml append menu mf separator mnuhtml append menu mf string mp stattree htmlexport get res string ids stats export2html t exportall mnu context append menu mf string mf popup uint ptr mnuhtml m hmenu get res string ids stats mnutreehtml t web get popup menu pos this do where mnu context track popup menu n flags do where x do where y this verify mnuhtml destroy menu verify mnu context destroy menu cstatisticstree domenu cpoint dowhere nflags cfilefind findbackup cstring mybuffer myflags mybuffer _t theprefs getconfigdir findbackup findfile mybuffer myflags mf_grayed myflags mf_string mnucontext createpopupmenu mnucontext addmenutitle getresstring ids_stats_mnutreetitle mnucontext appendmenu mf_string mp_stattree_reset getresstring ids_stats_bnreset _t mnucontext appendmenu myflags mp_stattree_restore getresstring ids_stats_bnrestore _t mnucontext appendmenu mf_separator mnucontext appendmenu mf_string mp_stattree_expandmain getresstring ids_stats_mnutreeexpandmain _t mnucontext appendmenu mf_string mp_stattree_expandall getresstring ids_stats_mnutreeexpandall _t mnucontext appendmenu mf_string mp_stattree_collapseall getresstring ids_stats_mnutreecollapseall _t mnucontext appendmenu mf_separator mnucontext appendmenu mf_string mp_stattree_copysel getresstring ids_stats_mnutreecpysel _t mnucontext appendmenu mf_string mp_stattree_copyvis getresstring ids_stats_mnutreecpyvis _t mnucontext appendmenu mf_string mp_stattree_copyall getresstring ids_stats_mnutreecpyall _t mnucontext appendmenu mf_separator createmenu addmenutitle appendmenu mf_string mp_stattree_htmlcopysel getresstring ids_stats_mnutreecpysel _t appendmenu mf_string mp_stattree_htmlcopyvis getresstring ids_stats_mnutreecpyvis _t appendmenu mf_string mp_stattree_htmlcopyall getresstring ids_stats_mnutreecpyall _t appendmenu mf_separator appendmenu mf_string mp_stattree_htmlexport getresstring ids_stats_export2html _t mnucontext appendmenu mf_string mf_popup uint_ptr m_hmenu getresstring ids_stats_mnutreehtml _t getpopupmenupos dowhere mnucontext trackpopupmenu nflags dowhere dowhere destroymenu mnucontext destroymenu void c statistics tree expand all bool only bold htreeitem the item htreeitem h current if the item null if only bold collapse all h current get root item m bexpandingall true else h current the item while h current null if item has children h current only bold is bold h current expand h current tve expand expand all only bold get child item h current h current get next item h current tvgn next if the item null m bexpandingall false cstatisticstree expandall onlybold theitem hcurrent theitem onlybold collapseall hcurrent getrootitem m_bexpandingall hcurrent theitem hcurrent itemhaschildren hcurrent onlybold isbold hcurrent hcurrent tve_expand expandall onlybold getchilditem hcurrent hcurrent getnextitem hcurrent tvgn_next theitem m_bexpandingall void c statistics tree collapse all htreeitem the item htreeitem h current if the item null h current get root item m bexpandingall true else h current the item while h current null if item has children h current collapse all get child item h current expand h current tve collapse h current get next item h current tvgn next if the item null m bexpandingall false cstatisticstree collapseall theitem hcurrent theitem hcurrent getrootitem m_bexpandingall hcurrent theitem hcurrent itemhaschildren hcurrent collapseall getchilditem hcurrent hcurrent tve_collapse hcurrent getnextitem hcurrent tvgn_next theitem m_bexpandingall c string c statistics tree get expanded mask htreeitem the item htreeitem h current c string temp mask temp mask empty if the item null h current get root item else h current the item while h current null if item has children h current is bold h current if is expanded h current temp mask 1 if is expanded h current temp mask 0 temp mask get expanded mask get child item h current h current get next item h current tvgn next return temp mask cstring cstatisticstree getexpandedmask theitem hcurrent cstring tempmask tempmask theitem hcurrent getrootitem hcurrent theitem hcurrent itemhaschildren hcurrent isbold hcurrent isexpanded hcurrent tempmask isexpanded hcurrent tempmask tempmask getexpandedmask getchilditem hcurrent hcurrent getnextitem hcurrent tvgn_next tempmask int c statistics tree apply expanded mask c string the mask htreeitem the item int the string index htreeitem h current if the item null h current get root item set redraw false expand all true m bexpandingall true else h current the item while h current null the string index the mask get length if item has children h current is bold h current if the mask get at the string index 0 expand h current tve collapse the string index the string index apply expanded mask the mask get child item h current the string index h current get next item h current tvgn next if the item null set redraw true m bexpandingall true return the string index cstatisticstree applyexpandedmask cstring themask theitem thestringindex hcurrent theitem hcurrent getrootitem setredraw expandall m_bexpandingall hcurrent theitem hcurrent thestringindex themask getlength itemhaschildren hcurrent isbold hcurrent themask getat thestringindex hcurrent tve_collapse thestringindex thestringindex applyexpandedmask themask getchilditem hcurrent thestringindex hcurrent getnextitem hcurrent tvgn_next theitem setredraw m_bexpandingall thestringindex co scope ctrl co scope ctrl int n trends int i colorref preset color 16 rgb 0xff 0x00 0x00 rgb 0xff 0xc0 0xc0 rgb 0xff 0xff 0x00 rgb 0xff 0xa0 0x00 rgb 0xa0 0x60 0x00 rgb 0x00 0xff 0x00 rgb 0x00 0xa0 0x00 rgb 0x00 0x00 0xff rgb 0x00 0xa0 0xff rgb 0x00 0xff 0xff rgb 0x00 0xa0 0xa0 rgb 0xc0 0xc0 0xff rgb 0xff 0x00 0xff rgb 0xa0 0x00 0xa0 rgb 0xff 0xff 0xff rgb 0x80 0x80 0x80 since plotting is based on a line to for each new point we need a starting point i e a previous point use 0 0 as the default first point these are public member variables and can be changed outside after construction g hayduk n trends is the number of trends that will be drawn on the plot first 15 plots have predefined colors but others will be drawn with white unless you call set plot color m plotdata new plotdata t n trends m ntrends n trends for i 0 i m ntrends i if i 15 m plotdata i cr plot color preset color i see also set plot color else m plotdata i cr plot color rgb 255 255 255 see also set plot color m plotdata i pen plot create pen ps solid 0 m plotdata i cr plot color m plotdata i d previous position 0 0 m plotdata i n prevy 1 m plotdata i d lower limit 10 0 m plotdata i d upper limit 10 0 m plotdata i d range m plotdata i d upper limit m plotdata i d lower limit m plotdata i lst points add tail 0 0 initialize our new trend ratio variable to 1 m plotdata i i trend ratio 1 m plotdata i legend label format t legend i i m plotdata i bars plot false public variable for the number of decimal places on the y axis g hayduk i ve deleted the possibility of changing this parameter in set range so change it after constructing the plot m nydecimals 1 set some initial values for the scaling until set range is called these are protected varaibles and must be set with set range in order to ensure that m drange is updated accordingly m nshiftpixels determines how much the plot shifts in terms of pixels with the addition of a new data point draw bars false autofit yscale false m nshiftpixels 1 m ntrendpoints 0 m nmaxpointcnt 1024 cust shift m npointstodo 0 g hayduk actually i needed an o scope ctrl to draw specific number of data samples and stretch them on the plot ctrl now o scope ctrl has two modes of operation fixed shift when m ntrendpoints 0 m nshiftpixels is in use or fixed number of points in the plot width when m ntrendpoints 0 when m ntrendpoints 0 cust shift structure is in use background grid and data colors these are public variables and can be set directly m crbackcolor rgb 0 0 0 see also set background color m crgridcolor rgb 0 255 255 see also set grid color public member variables can be set directly m str x units format t samples can also be set with setx units m str y units format t y units can also be set with sety units protected bitmaps to restore the memory dc s m pbitmapoldgrid null m pbitmapoldplot null g hayduk configurable number of grids init you are free to change those between contructing the object and calling create m nxgrids 6 m nygrids 5 m ntrendpoints 1 m bdoupdate true m nredrawtimer 0 ready false coscopectrl coscopectrl ntrends presetcolor lineto ntrends setplotcolor m_plotdata plotdata_t ntrends m_ntrends ntrends m_ntrends m_plotdata crplotcolor presetcolor setplotcolor m_plotdata crplotcolor setplotcolor m_plotdata penplot createpen ps_solid m_plotdata crplotcolor m_plotdata dpreviousposition m_plotdata nprevy m_plotdata dlowerlimit m_plotdata dupperlimit m_plotdata drange m_plotdata dupperlimit m_plotdata dlowerlimit m_plotdata lstpoints addtail m_plotdata itrendratio m_plotdata legendlabel _t m_plotdata barsplot setrange m_nydecimals setrange setrange m_drange m_nshiftpixels drawbars autofityscale m_nshiftpixels m_ntrendpoints m_nmaxpointcnt custshift m_npointstodo oscopectrl oscopectrl m_ntrendpoints m_nshiftpixels m_ntrendpoints m_ntrendpoints custshift m_crbackcolor setbackgroundcolor m_crgridcolor setgridcolor m_str xunits _t setxunits m_str yunits _t setyunits m_pbitmapoldgrid m_pbitmapoldplot m_nxgrids m_nygrids m_ntrendpoints m_bdoupdate m_nredrawtimer co scope ctrl co scope ctrl if m pbitmapoldgrid null m dcgrid select object m pbitmapoldgrid if m pbitmapoldplot null m dcplot select object m pbitmapoldplot delete m plotdata coscopectrl coscopectrl m_pbitmapoldgrid m_dcgrid selectobject m_pbitmapoldgrid m_pbitmapoldplot m_dcplot selectobject m_pbitmapoldplot m_plotdata bool co scope ctrl create dword dw style const rect rect c wnd p parent wnd uint nid bool result static c string class name afx register wnd class cs dblclks cs hredraw cs vredraw afx get app load standard cursor idc arrow result c wnd create ex ws ex clientedge ws ex staticedge class name null dw style rect left rect top rect right rect left rect bottom rect top p parent wnd get safe hwnd hmenu nid if result 0 invalidate ctrl init window styles this ready true return result coscopectrl dwstyle cwnd pparentwnd cstring classname afxregisterwndclass cs_dblclks cs_hredraw cs_vredraw afxgetapp loadstandardcursor idc_arrow cwnd createex ws_ex_clientedge ws_ex_staticedge classname dwstyle pparentwnd getsafehwnd invalidatectrl initwindowstyles void co scope ctrl set trend ratio int i trend uint i ratio assert i trend m ntrends i ratio 0 i trend must be a valid trend in this plot if i ratio uint m plotdata i trend i trend ratio double d trend modifier double m plotdata i trend i trend ratio i ratio m plotdata i trend i trend ratio i ratio int i cnt m plotdata i trend lst points get count for int i 0 i i cnt i position pos m plotdata i trend lst points find index i if pos m plotdata i trend lst points set at pos m plotdata i trend lst points get at pos d trend modifier invalidate ctrl coscopectrl settrendratio itrend iratio itrend m_ntrends iratio itrend iratio m_plotdata itrend itrendratio dtrendmodifier m_plotdata itrend itrendratio iratio m_plotdata itrend itrendratio iratio icnt m_plotdata itrend lstpoints getcount icnt m_plotdata itrend lstpoints findindex m_plotdata itrend lstpoints setat m_plotdata itrend lstpoints getat dtrendmodifier invalidatectrl void co scope ctrl set legend label c string string int i trend m plotdata i trend legend label string invalidate ctrl false coscopectrl setlegendlabel cstring itrend m_plotdata itrend legendlabel invalidatectrl void co scope ctrl set bars plot bool bars plot int i trend m plotdata i trend bars plot bars plot invalidate ctrl false coscopectrl setbarsplot barsplot itrend m_plotdata itrend barsplot barsplot invalidatectrl void co scope ctrl set range double d lower double d upper int i trend assert d upper d lower m plotdata i trend d lower limit d lower m plotdata i trend d upper limit d upper m plotdata i trend d range m plotdata i trend d upper limit m plotdata i trend d lower limit m plotdata i trend d vertical factor double m nplotheight m plotdata i trend d range invalidate ctrl coscopectrl setrange dlower dupper itrend dupper dlower m_plotdata itrend dlowerlimit dlower m_plotdata itrend dupperlimit dupper m_plotdata itrend drange m_plotdata itrend dupperlimit m_plotdata itrend dlowerlimit m_plotdata itrend dverticalfactor m_nplotheight m_plotdata itrend drange invalidatectrl void co scope ctrl set ranges double d lower double d upper assert d upper d lower int i trend for i trend 0 i trend m ntrends i trend m plotdata i trend d lower limit d lower m plotdata i trend d upper limit d upper m plotdata i trend d range m plotdata i trend d upper limit m plotdata i trend d lower limit m plotdata i trend d vertical factor double m nplotheight m plotdata i trend d range invalidate ctrl coscopectrl setranges dlower dupper dupper dlower itrend itrend itrend m_ntrends itrend m_plotdata itrend dlowerlimit dlower m_plotdata itrend dupperlimit dupper m_plotdata itrend drange m_plotdata itrend dupperlimit m_plotdata itrend dlowerlimit m_plotdata itrend dverticalfactor m_nplotheight m_plotdata itrend drange invalidatectrl void co scope ctrl setx units c string string c string x min c string x max m str x units string m str x min x min m str x max x max invalidate ctrl false coscopectrl setxunits cstring cstring xmin cstring xmax m_str xunits m_str xmin xmin m_str xmax xmax invalidatectrl void co scope ctrl sety units c string string c string y min c string y max m str y units string m str y min y min m str y max y max invalidate ctrl coscopectrl setyunits cstring cstring ymin cstring ymax m_str yunits m_str ymin ymin m_str ymax ymax invalidatectrl void co scope ctrl set grid color colorref color m crgridcolor color invalidate ctrl coscopectrl setgridcolor m_crgridcolor invalidatectrl void co scope ctrl set plot color colorref color int i trend m plotdata i trend cr plot color color m plotdata i trend pen plot delete object m plotdata i trend pen plot create pen ps solid 0 m plotdata i trend cr plot color invalidate ctrl coscopectrl setplotcolor itrend m_plotdata itrend crplotcolor m_plotdata itrend penplot deleteobject m_plotdata itrend penplot createpen ps_solid m_plotdata itrend crplotcolor invalidatectrl colorref co scope ctrl get plot color int i trend return m plotdata i trend cr plot color coscopectrl getplotcolor itrend m_plotdata itrend crplotcolor void co scope ctrl set background color colorref color m crbackcolor color invalidate ctrl coscopectrl setbackgroundcolor m_crbackcolor invalidatectrl void co scope ctrl append points double d new point bool b invalidate bool b add2 list bool b use trend ratio append a data point to the plot int i trend for i trend 0 i trend m ntrends i trend changed this to support the new trend ratio var if b use trend ratio m plotdata i trend d current position double d new point i trend m plotdata i trend i trend ratio else m plotdata i trend d current position d new point i trend if b add2 list m plotdata i trend lst points add tail m plotdata i trend d current position while m plotdata i trend lst points get count m nmaxpointcnt m plotdata i trend lst points remove head sometime responsible for ghost point on the left after a resize if m bdoupdate return if m ntrendpoints 0 if cust shift m npointstodo 0 cust shift m npointstodo m ntrendpoints 1 cust shift m nwidthtodo m nplotwidth cust shift m nrmndr 0 a little bit tricky setting m nshiftpixels in fixed number of points through plot width mode m nshiftpixels cust shift m nwidthtodo cust shift m nrmndr cust shift m npointstodo cust shift m nrmndr cust shift m nwidthtodo cust shift m nrmndr cust shift m npointstodo if cust shift m npointstodo 1 m nshiftpixels cust shift m nwidthtodo cust shift m nwidthtodo m nshiftpixels cust shift m npointstodo draw point if b invalidate ready m bdoupdate invalidate return coscopectrl appendpoints dnewpoint binvalidate badd2list busetrendratio itrend itrend itrend m_ntrends itrend trendratio busetrendratio m_plotdata itrend dcurrentposition dnewpoint itrend m_plotdata itrend itrendratio m_plotdata itrend dcurrentposition dnewpoint itrend badd2list m_plotdata itrend lstpoints addtail m_plotdata itrend dcurrentposition m_plotdata itrend lstpoints getcount m_nmaxpointcnt m_plotdata itrend lstpoints removehead m_bdoupdate m_ntrendpoints custshift m_npointstodo custshift m_npointstodo m_ntrendpoints custshift m_nwidthtodo m_nplotwidth custshift m_nrmndr m_nshiftpixels m_nshiftpixels custshift m_nwidthtodo custshift m_nrmndr custshift m_npointstodo custshift m_nrmndr custshift m_nwidthtodo custshift m_nrmndr custshift m_npointstodo custshift m_npointstodo m_nshiftpixels custshift m_nwidthtodo custshift m_nwidthtodo m_nshiftpixels custshift m_npointstodo drawpoint binvalidate m_bdoupdate void co scope ctrl append empty points double d new point bool b invalidate bool b add2 list bool b use trend ratio int i trend curry c rect scroll rect rect clean up append a data point to the plot return the previous point for i trend 0 i trend m ntrends i trend if b use trend ratio m plotdata i trend d current position double d new point i trend m plotdata i trend i trend ratio else m plotdata i trend d current position d new point i trend if b add2 list m plotdata i trend lst points add tail m plotdata i trend d current position if m ntrendpoints 0 if cust shift m npointstodo 0 cust shift m npointstodo m ntrendpoints 1 cust shift m nwidthtodo m nplotwidth cust shift m nrmndr 0 m nshiftpixels cust shift m nwidthtodo cust shift m nrmndr cust shift m npointstodo cust shift m nrmndr cust shift m nwidthtodo cust shift m nrmndr cust shift m npointstodo if cust shift m npointstodo 1 m nshiftpixels cust shift m nwidthtodo cust shift m nwidthtodo m nshiftpixels cust shift m npointstodo draw point s shift process if m dcplot get safe hdc null if m nshiftpixels 0 scroll rect left m rectplot left scroll rect top m rectplot top 1 scroll rect right m rectplot left m nplotwidth scroll rect bottom m rectplot top 1 m nplotheight scroll rect m rectplot scroll rect right m dcplot scrolldc m nshiftpixels 0 scroll rect scroll rect null null establish a rectangle over the right side of plot which now needs to be cleaned up prior to adding the new point rect clean up m rectplot rect clean up left rect clean up right m nshiftpixels 1 rect clean up right m dcplot fill solid rect rect clean up m crbackcolor fill the cleanup area with the background draw the next line segement for i trend 0 i trend m ntrends i trend curry m rectplot bottom long m plotdata i trend d current position m plotdata i trend d lower limit m plotdata i trend d vertical factor m plotdata i trend n prevy curry store the current point for connection to the next point m plotdata i trend d previous position m plotdata i trend d current position if b invalidate m bdoupdate invalidate coscopectrl appendemptypoints dnewpoint binvalidate badd2list busetrendratio itrend crect scrollrect rectcleanup itrend itrend m_ntrends itrend busetrendratio m_plotdata itrend dcurrentposition dnewpoint itrend m_plotdata itrend itrendratio m_plotdata itrend dcurrentposition dnewpoint itrend badd2list m_plotdata itrend lstpoints addtail m_plotdata itrend dcurrentposition m_ntrendpoints custshift m_npointstodo custshift m_npointstodo m_ntrendpoints custshift m_nwidthtodo m_nplotwidth custshift m_nrmndr m_nshiftpixels custshift m_nwidthtodo custshift m_nrmndr custshift m_npointstodo custshift m_nrmndr custshift m_nwidthtodo custshift m_nrmndr custshift m_npointstodo custshift m_npointstodo m_nshiftpixels custshift m_nwidthtodo custshift m_nwidthtodo m_nshiftpixels custshift m_npointstodo drawpoint m_dcplot getsafehdc m_nshiftpixels scrollrect m_rectplot scrollrect m_rectplot scrollrect m_rectplot m_nplotwidth scrollrect m_rectplot m_nplotheight scrollrect m_rectplot scrollrect m_dcplot m_nshiftpixels scrollrect scrollrect rectcleanup m_rectplot rectcleanup rectcleanup m_nshiftpixels rectcleanup m_dcplot fillsolidrect rectcleanup m_crbackcolor itrend itrend m_ntrends itrend m_rectplot m_plotdata itrend dcurrentposition m_plotdata itrend dlowerlimit m_plotdata itrend dverticalfactor m_plotdata itrend nprevy m_plotdata itrend dpreviousposition m_plotdata itrend dcurrentposition binvalidate m_bdoupdate void co scope ctrl invalidate ctrl bool delete graph int i j grid pos int n characters c pen old pen c pen solid pen ps solid 0 m crgridcolor c font axis font y unit font old font legend font c string str temp c clientdc dc this if we don t have one yet set up a memory dc for the grid if m dcgrid get safe hdc null m dcgrid create compatibledc dc m bitmapgrid delete object m bitmapgrid create compatible bitmap dc m nclientwidth m nclientheight m pbitmapoldgrid m dcgrid select object m bitmapgrid colorref cr label bk colorref cr label fg if the prefs get straight window styles cr label bk get sys color color btnface cr label fg get sys color color windowtext else cr label bk m crbackcolor cr label fg m crgridcolor fill the grid background m dcgrid fill solid rect m rectclient cr label bk draw the plot rectangle determine how wide the y axis scaling values are double f abs upper limit fabs m plotdata 0 d upper limit if f abs upper limit 0 0 n characters abs int log10 f abs upper limit else n characters 0 double f abs lower limit fabs m plotdata 0 d lower limit if f abs lower limit 0 0 n characters max n characters abs int log10 f abs lower limit add the units digit decimal point and a minus sign and an extra space as well as the number of decimal places to display n characters n characters 4 m nydecimals adjust the plot rectangle dimensions changed this so that the y units wouldn t overlap the y scale m rectplot left m rectclient left 8 7 4 n characters m nplotwidth m rectplot width draw the plot rectangle if the prefs get straight window styles m dcgrid fill solid rect m rectplot left m rectplot top m rectplot right m rectplot left 1 m rectplot bottom m rectplot top 1 m crbackcolor c rect rc plot m rectplot rc plot left 1 rc plot top 1 rc plot right 3 rc plot bottom 3 m dcgrid draw edge rc plot edge sunken bf rect else old pen m dcgrid select object solid pen m dcgrid move to m rectplot left m rectplot top m dcgrid line to m rectplot right 1 m rectplot top m dcgrid line to m rectplot right 1 m rectplot bottom 1 m dcgrid line to m rectplot left m rectplot bottom 1 m dcgrid line to m rectplot left m rectplot top m dcgrid select object old pen draw the dotted lines use set pixel instead of a dotted pen this allows for a finer dotted line and a more technical look for j 1 j m nygrids 1 j grid pos m rectplot height j m nygrids 1 m rectplot top for i m rectplot left i m rectplot right i 4 m dcgrid set pixel i grid pos m crgridcolor if the prefs m bshowverticalhourmarkers add vertical reference lines in the graphs each line indicates an elapsed hour from the current time extreme right of the graph lines are always right aligned and the gap scales accordingly to the user horizontal scale intervals of 10 hours are marked with slightly stronger lines that go beyond the bottom border int hour size partial size surplus 0 extra 0 if m nxgrids 0 hour size 3600 m rectplot width 3600 m nxgrids m nxpartial size of an hour in pixels partial size m rectplot width hour size m nxgrids if partial size hour size partial size hour size m nxpartial 3600 real partial size surplus m rectplot width hour size m nxgrids partial size pixel surplus grid pos 0 for j 1 j m nxgrids j extra 0 if surplus surplus extra 1 grid pos hour size extra if m nxgrids j 1 10 0 for i m rectplot top i m rectplot bottom i 2 m dcgrid set pixel m rectplot left grid pos hour size partial size i m crgridcolor else for i m rectplot top i m rectplot bottom i 4 m dcgrid set pixel m rectplot left grid pos hour size partial size i m crgridcolor create some fonts horizontal and vertical using arial or ms sans serif gives a more accurate small font but does not work for korean fonts using ms shell dlg gives somewhat less accurate small fonts but does work for all languages which are currently supported by e mule axis font create point font 8 10 t ms shell dlg 8pt ms shell dlg this shall be available on all windows systems y unit font create font font point size to log units 8 10 0 900 900 fw normal false false 0 default charset out default precis clip default precis default quality default pitch t ms shell dlg grab the horizontal font old font m dcgrid select object axis font y max m dcgrid set text color cr label fg m dcgrid set bk color cr label bk m dcgrid set text align ta right ta top if m str y max is empty str temp format t lf m nydecimals m plotdata 0 d upper limit else str temp m str y max m dcgrid text out m rectplot left 4 m rectplot top 7 str temp if m rectplot height m nygrids 1 14 for j 1 j m nygrids 1 j grid pos m rectplot height j m nygrids 1 m rectplot top str temp format t lf m nydecimals m plotdata 0 d upper limit m nygrids j 1 m nygrids 1 m dcgrid text out m rectplot left 4 grid pos 7 str temp else str temp format t lf m nydecimals m plotdata 0 d upper limit 2 m dcgrid text out m rectplot left 2 m rectplot bottom m rectplot top m rectplot bottom 2 7 str temp y min if m str y min is empty str temp format t lf m nydecimals m plotdata 0 d lower limit else str temp m str y min m dcgrid text out m rectplot left 4 m rectplot bottom 7 str temp x units m dcgrid set text align ta right ta bottom m dcgrid text out m rectclient right 2 m rectclient bottom 2 m str x units restore the font m dcgrid select object old font y units old font m dcgrid select object y unit font m dcgrid set text align ta center ta baseline c rect r text 0 0 0 0 m dcgrid draw text m str y units r text dt calcrect m dcgrid text out m rectclient left m rectplot left 4 2 r text height 2 m rectplot bottom m rectplot top 2 r text height 2 m str y units m dcgrid select object old font using arial or ms sans serif gives a more accurate small font but does not work for korean fonts using ms shell dlg gives somewhat less accurate small fonts but does work for all languages which are currently supported by e mule legend font create point font 8 10 t ms shell dlg 8pt ms shell dlg this shall be available on all windows systems old font m dcgrid select object legend font m dcgrid set text align ta left ta top int xpos m rectplot left 2 int ypos m rectplot bottom 3 for i 0 i m ntrends i c size size label m dcgrid get text extent m plotdata i legend label if xpos 12 size label cx 12 m rectplot right xpos m rectplot left 2 ypos m rectplot bottom size label cy if the prefs get straight window styles const int i leg frmd 1 c pen pen frame ps solid i leg frmd cr label fg old pen m dcgrid select object pen frame const int i leg boxw 9 const int i leg boxh 9 c rect rc legend frame rc legend frame left xpos i leg frmd rc legend frame top ypos 2 i leg frmd rc legend frame right rc legend frame left i leg boxw i leg frmd rc legend frame bottom rc legend frame top i leg boxh i leg frmd m dcgrid move to rc legend frame left rc legend frame top m dcgrid line to rc legend frame right rc legend frame top m dcgrid line to rc legend frame right rc legend frame bottom m dcgrid line to rc legend frame left rc legend frame bottom m dcgrid line to rc legend frame left rc legend frame top m dcgrid select object old pen m dcgrid fill solid rect xpos ypos 2 i leg boxw i leg boxh m plotdata i cr plot color m dcgrid set bk color cr label bk else c pen legend pen ps solid 3 m plotdata i cr plot color old pen m dcgrid select object legend pen m dcgrid move to xpos ypos 8 m dcgrid line to xpos 8 ypos 4 m dcgrid select object old pen m dcgrid text out xpos 12 ypos m plotdata i legend label xpos 12 size label cx 12 m dcgrid select object old font if we don t have one yet set up a memory dc for the plot if m dcplot get safe hdc null m dcplot create compatibledc dc m bitmapplot delete object m bitmapplot create compatible bitmap dc m nclientwidth m nclientheight m pbitmapoldplot m dcplot select object m bitmapplot make sure the plot bitmap is cleared if delete graph m dcplot fill solid rect m rectclient m crbackcolor int i new size m rectclient width m nshiftpixels 10 10 just in case if m nmaxpointcnt i new size m nmaxpointcnt i new size if the app emuledlg is running if the prefs is graph recreate disabled the timer will redraw the previous points in 200ms m bdoupdate false if m nredrawtimer kill timer m nredrawtimer verify m nredrawtimer set timer 1612 200 null null reduce flickering invalidate rect m rectclient coscopectrl invalidatectrl deletegraph gridpos ncharacters cpen oldpen cpen solidpen ps_solid m_crgridcolor cfont axisfont yunitfont oldfont legendfont cstring strtemp cclientdc m_dcgrid getsafehdc m_dcgrid createcompatibledc m_bitmapgrid deleteobject m_bitmapgrid createcompatiblebitmap m_nclientwidth m_nclientheight m_pbitmapoldgrid m_dcgrid selectobject m_bitmapgrid crlabelbk crlabelfg theprefs getstraightwindowstyles crlabelbk getsyscolor color_btnface crlabelfg getsyscolor color_windowtext crlabelbk m_crbackcolor crlabelfg m_crgridcolor m_dcgrid fillsolidrect m_rectclient crlabelbk fabsupperlimit m_plotdata dupperlimit fabsupperlimit ncharacters fabsupperlimit ncharacters fabslowerlimit m_plotdata dlowerlimit fabslowerlimit ncharacters ncharacters fabslowerlimit ncharacters ncharacters m_nydecimals m_rectplot m_rectclient ncharacters m_nplotwidth m_rectplot theprefs getstraightwindowstyles m_dcgrid fillsolidrect m_rectplot m_rectplot m_rectplot m_rectplot m_rectplot m_rectplot m_crbackcolor crect rcplot m_rectplot rcplot rcplot rcplot rcplot m_dcgrid drawedge rcplot edge_sunken bf_rect oldpen m_dcgrid selectobject solidpen m_dcgrid moveto m_rectplot m_rectplot m_dcgrid lineto m_rectplot m_rectplot m_dcgrid lineto m_rectplot m_rectplot m_dcgrid lineto m_rectplot m_rectplot m_dcgrid lineto m_rectplot m_rectplot m_dcgrid selectobject oldpen setpixel m_nygrids gridpos m_rectplot m_nygrids m_rectplot m_rectplot m_rectplot m_dcgrid setpixel gridpos m_crgridcolor theprefs m_bshowverticalhourmarkers hoursize partialsize m_nxgrids hoursize m_rectplot m_nxgrids m_nxpartial partialsize m_rectplot hoursize m_nxgrids partialsize hoursize partialsize hoursize m_nxpartial m_rectplot hoursize m_nxgrids partialsize gridpos m_nxgrids gridpos hoursize m_nxgrids m_rectplot m_rectplot m_dcgrid setpixel m_rectplot gridpos hoursize partialsize m_crgridcolor m_rectplot m_rectplot m_dcgrid setpixel m_rectplot gridpos hoursize partialsize m_crgridcolor emule axisfont createpointfont _t yunitfont createfont fontpointsizetologunits fw_normal default_charset out_default_precis clip_default_precis default_quality default_pitch _t oldfont m_dcgrid selectobject axisfont m_dcgrid settextcolor crlabelfg m_dcgrid setbkcolor crlabelbk m_dcgrid settextalign ta_right ta_top m_str ymax isempty strtemp _t m_nydecimals m_plotdata dupperlimit strtemp m_str ymax m_dcgrid textout m_rectplot m_rectplot strtemp m_rectplot m_nygrids m_nygrids gridpos m_rectplot m_nygrids m_rectplot strtemp _t m_nydecimals m_plotdata dupperlimit m_nygrids m_nygrids m_dcgrid textout m_rectplot gridpos strtemp strtemp _t m_nydecimals m_plotdata dupperlimit m_dcgrid textout m_rectplot m_rectplot m_rectplot m_rectplot strtemp m_str ymin isempty strtemp _t m_nydecimals m_plotdata dlowerlimit strtemp m_str ymin m_dcgrid textout m_rectplot m_rectplot strtemp m_dcgrid settextalign ta_right ta_bottom m_dcgrid textout m_rectclient m_rectclient m_str xunits m_dcgrid selectobject oldfont oldfont m_dcgrid selectobject yunitfont m_dcgrid settextalign ta_center ta_baseline crect rtext m_dcgrid drawtext m_str yunits rtext dt_calcrect m_dcgrid textout m_rectclient m_rectplot rtext m_rectplot m_rectplot rtext m_str yunits m_dcgrid selectobject oldfont emule legendfont createpointfont _t oldfont m_dcgrid selectobject legendfont m_dcgrid settextalign ta_left ta_top m_rectplot m_rectplot m_ntrends csize sizelabel m_dcgrid gettextextent m_plotdata legendlabel sizelabel m_rectplot m_rectplot m_rectplot sizelabel theprefs getstraightwindowstyles ilegfrmd cpen penframe ps_solid ilegfrmd crlabelfg oldpen m_dcgrid selectobject penframe ilegboxw ilegboxh crect rclegendframe rclegendframe ilegfrmd rclegendframe ilegfrmd rclegendframe rclegendframe ilegboxw ilegfrmd rclegendframe rclegendframe ilegboxh ilegfrmd m_dcgrid moveto rclegendframe rclegendframe m_dcgrid lineto rclegendframe rclegendframe m_dcgrid lineto rclegendframe rclegendframe m_dcgrid lineto rclegendframe rclegendframe m_dcgrid lineto rclegendframe rclegendframe m_dcgrid selectobject oldpen m_dcgrid fillsolidrect ilegboxw ilegboxh m_plotdata crplotcolor m_dcgrid setbkcolor crlabelbk cpen legendpen ps_solid m_plotdata crplotcolor oldpen m_dcgrid selectobject legendpen m_dcgrid moveto m_dcgrid lineto m_dcgrid selectobject oldpen m_dcgrid textout m_plotdata legendlabel sizelabel m_dcgrid selectobject oldfont m_dcplot getsafehdc m_dcplot createcompatibledc m_bitmapplot deleteobject m_bitmapplot createcompatiblebitmap m_nclientwidth m_nclientheight m_pbitmapoldplot m_dcplot selectobject m_bitmapplot deletegraph m_dcplot fillsolidrect m_rectclient m_crbackcolor inewsize m_rectclient m_nshiftpixels m_nmaxpointcnt inewsize m_nmaxpointcnt inewsize theapp isrunning theprefs isgraphrecreatedisabled m_bdoupdate m_nredrawtimer killtimer m_nredrawtimer m_nredrawtimer settimer invalidaterect m_rectclient void co scope ctrl draw point this does the work of scrolling the plot to the left and appending a new data point all of the plotting is directed to the memory based bitmap associated with m dcplot the will subsequently be bit blt d to the client in on paint int currx prevx curry prevy i trend c pen old pen c rect scroll rect rect clean up if m dcplot get safe hdc null if m nshiftpixels 0 scroll rect m rectplot scroll rect left scroll rect right scroll rect bottom m dcplot scrolldc m nshiftpixels 0 scroll rect scroll rect null null establish a rectangle over the right side of plot which now needs to be cleaned up prior to adding the new point rect clean up m rectplot rect clean up left rect clean up right m nshiftpixels 1 rect clean up right rect clean up bottom m dcplot fill solid rect rect clean up m crbackcolor fill the cleanup area with the background draw the next line segement for i trend 0 i trend m ntrends i trend grab the plotting pen old pen m dcplot select object m plotdata i trend pen plot move to the previous point prevx m rectplot right m nshiftpixels if m plotdata i trend n prevy 0 prevy m plotdata i trend n prevy else prevy m rectplot bottom long m plotdata i trend d previous position m plotdata i trend d lower limit m plotdata i trend d vertical factor if m plotdata i trend bars plot m dcplot move to prevx prevy draw to the current point currx m rectplot right curry m rectplot bottom long m plotdata i trend d current position m plotdata i trend d lower limit m plotdata i trend d vertical factor m plotdata i trend n prevy curry if m plotdata i trend bars plot m dcplot move to currx m rectplot bottom else if abs prevx currx abs prevy curry currx prevx currx 0 1 1 else curry prevy curry 0 1 1 m dcplot line to currx curry m dcplot select object old pen if the data leaks over the upper or lower plot boundaries fill the upper and lower leakage with the background this will facilitate clipping on an as needed basis as opposed to always calling intersect clip rect if prevy m rectplot top curry m rectplot top m dcplot fill solid rect c rect prevx 1 m rectclient top currx 5 m rectplot top 1 m crbackcolor if prevy m rectplot bottom curry m rectplot bottom m dcplot fill solid rect c rect prevx 1 m rectplot bottom 1 currx 5 m rectclient bottom 1 m crbackcolor store the current point for connection to the next point m plotdata i trend d previous position m plotdata i trend d current position coscopectrl drawpoint m_dcplot bitblt onpaint itrend cpen oldpen crect scrollrect rectcleanup m_dcplot getsafehdc m_nshiftpixels scrollrect m_rectplot scrollrect scrollrect scrollrect m_dcplot m_nshiftpixels scrollrect scrollrect rectcleanup m_rectplot rectcleanup rectcleanup m_nshiftpixels rectcleanup rectcleanup m_dcplot fillsolidrect rectcleanup m_crbackcolor itrend itrend m_ntrends itrend oldpen m_dcplot selectobject m_plotdata itrend penplot m_rectplot m_nshiftpixels m_plotdata itrend nprevy m_plotdata itrend nprevy m_rectplot m_plotdata itrend dpreviousposition m_plotdata itrend dlowerlimit m_plotdata itrend dverticalfactor m_plotdata itrend barsplot m_dcplot moveto m_rectplot m_rectplot m_plotdata itrend dcurrentposition m_plotdata itrend dlowerlimit m_plotdata itrend dverticalfactor m_plotdata itrend nprevy m_plotdata itrend barsplot m_dcplot moveto m_rectplot m_dcplot lineto m_dcplot selectobject oldpen intersectcliprect m_rectplot m_rectplot m_dcplot fillsolidrect crect m_rectclient m_rectplot m_crbackcolor m_rectplot m_rectplot m_dcplot fillsolidrect crect m_rectplot m_rectclient m_crbackcolor m_plotdata itrend dpreviousposition m_plotdata itrend dcurrentposition void co scope ctrl reset clear all points for int i 0 i m ntrends i m plotdata i d previous position 0 0 m plotdata i n prevy 1 for int i trend 0 i trend m ntrends i trend m plotdata i trend lst points remove all invalidate ctrl coscopectrl m_ntrends m_plotdata dpreviousposition m_plotdata nprevy itrend itrend m_ntrends itrend m_plotdata itrend lstpoints removeall invalidatectrl int co scope ctrl re create graph void for int i 0 i m ntrends i m plotdata i d previous position 0 0 m plotdata i n prevy 1 double p add points new double m ntrends position p pos array new position m ntrends try to avoid to call the method append points more than necessary remark the default size of the list is 1024 int point to draw m plotdata 0 lst points get count if point to draw m nplotwidth m nshiftpixels 1 point to draw m nplotwidth m nshiftpixels 1 int start index m plotdata 0 lst points get count point to draw prepare to go through the elements on n lists in parallel for int i trend 0 i trend m ntrends i trend p pos array i trend m plotdata i trend lst points find index start index we will assume that each trends have the same among of points so we test only the first iterator while p pos array 0 0 for int i trend 0 i trend m ntrends i trend p add points i trend m plotdata i trend lst points get next p pos array i trend pass false for new b use trend ratio parameter so that graph is recreated correctly append points p add points false false false delete p add points delete p pos array invalidate return 0 coscopectrl recreategraph m_ntrends m_plotdata dpreviousposition m_plotdata nprevy paddpoints m_ntrends pposarray m_ntrends appendpoints pointtodraw m_plotdata lstpoints getcount pointtodraw m_nplotwidth m_nshiftpixels pointtodraw m_nplotwidth m_nshiftpixels startindex m_plotdata lstpoints getcount pointtodraw itrend itrend m_ntrends itrend pposarray itrend m_plotdata itrend lstpoints findindex startindex pposarray itrend itrend m_ntrends itrend paddpoints itrend m_plotdata itrend lstpoints getnext pposarray itrend busetrendratio appendpoints paddpoints paddpoints pposarray void co scope ctrl on paint c paintdc dc this cdc memdc c bitmap mem bitmap c bitmap old bitmap memdc create compatibledc dc mem bitmap create compatible bitmap dc m nclientwidth m nclientheight old bitmap c bitmap memdc select object mem bitmap if memdc get safe hdc null first drop the grid on the memory dc memdc bit blt 0 0 m nclientwidth m nclientheight m dcgrid 0 0 srccopy now add the plot on top as a pattern via srcpaint works well with dark background and a light plot memdc bit blt 0 0 m nclientwidth m nclientheight m dcplot 0 0 srcpaint finally send the result to the display dc bit blt 0 0 m nclientwidth m nclientheight memdc 0 0 srccopy memdc select object old bitmap mem bitmap delete object coscopectrl onpaint cpaintdc cbitmap membitmap cbitmap oldbitmap createcompatibledc membitmap createcompatiblebitmap m_nclientwidth m_nclientheight oldbitmap cbitmap selectobject membitmap getsafehdc bitblt m_nclientwidth m_nclientheight m_dcgrid bitblt m_nclientwidth m_nclientheight m_dcplot bitblt m_nclientwidth m_nclientheight selectobject oldbitmap membitmap deleteobject void co scope ctrl on size uint n type int cx int cy if cx cy return int i trend c wnd on size n type cx cy note on size automatically gets called during the setup of the control get client rect m rectclient m nclientheight m rectclient height m nclientwidth m rectclient width the left coordinate and width will be modified in invalidate ctrl to be based on the width of the y axis scaling m rectplot left 20 m rectplot top 10 m rectplot right m rectclient right 10 m rectplot bottom m rectclient bottom 25 m nplotheight m rectplot height m nplotwidth m rectplot width set the scaling factor for now this can be adjusted in the set range functions for i trend 0 i trend m ntrends i trend m plotdata i trend d vertical factor double m nplotheight m plotdata i trend d range destroy and recreate the grid bitmap c clientdc dc this if m pbitmapoldgrid m bitmapgrid get safe handle m dcgrid get safe hdc m dcgrid select object m pbitmapoldgrid m bitmapgrid delete object m bitmapgrid create compatible bitmap dc m nclientwidth m nclientheight m pbitmapoldgrid m dcgrid select object m bitmapgrid destroy and recreate the plot bitmap if m pbitmapoldplot m bitmapplot get safe handle m dcplot get safe hdc m dcplot select object m pbitmapoldplot m bitmapplot delete object m bitmapplot create compatible bitmap dc m nclientwidth m nclientheight m pbitmapoldplot m dcplot select object m bitmapplot invalidate ctrl coscopectrl onsize ntype itrend cwnd onsize ntype onsize getclientrect m_rectclient m_nclientheight m_rectclient m_nclientwidth m_rectclient invalidatectrl m_rectplot m_rectplot m_rectplot m_rectclient m_rectplot m_rectclient m_nplotheight m_rectplot m_nplotwidth m_rectplot setrange itrend itrend m_ntrends itrend m_plotdata itrend dverticalfactor m_nplotheight m_plotdata itrend drange cclientdc m_pbitmapoldgrid m_bitmapgrid getsafehandle m_dcgrid getsafehdc m_dcgrid selectobject m_pbitmapoldgrid m_bitmapgrid deleteobject m_bitmapgrid createcompatiblebitmap m_nclientwidth m_nclientheight m_pbitmapoldgrid m_dcgrid selectobject m_bitmapgrid m_pbitmapoldplot m_bitmapplot getsafehandle m_dcplot getsafehdc m_dcplot selectobject m_pbitmapoldplot m_bitmapplot deleteobject m_bitmapplot createcompatiblebitmap m_nclientwidth m_nclientheight m_pbitmapoldplot m_dcplot selectobject m_bitmapplot invalidatectrl void co scope ctrl onl button dbl clk uint n flags c point point c wnd onl button dbl clk n flags point c wnd pwnd parent get parent if pwnd parent pwnd parent send message wm command makelong get dlg ctrlid stn dblclk lparam m hwnd coscopectrl onlbuttondblclk nflags cpoint cwnd onlbuttondblclk nflags cwnd pwndparent getparent pwndparent pwndparent sendmessage wm_command getdlgctrlid stn_dblclk m_hwnd void co scope ctrl on timer uint nid event if nid event m nredrawtimer kill timer m nredrawtimer m nredrawtimer 0 m bdoupdate true re create graph c wnd on timer nid event coscopectrl ontimer nidevent nidevent m_nredrawtimer killtimer m_nredrawtimer m_nredrawtimer m_bdoupdate recreategraph cwnd ontimer nidevent void co scope ctrl on mouse move uint n flags c point point c wnd on mouse move n flags point if get key state vk lbutton 0 return c rect plot rect get plot rect plot rect if point x 60 point x plot rect width 60 outside the axis return c wnd pwnd parent get parent if pwnd parent int mypos plot rect width point x 60 int shownsecs plot rect width the prefs get traffico meter interval float apixel float shownsecs float plot rect width pwnd parent send message um oscopeposition plot rect width int mypos apixel coscopectrl onmousemove nflags cpoint cwnd onmousemove nflags getkeystate vk_lbutton crect plotrect getplotrect plotrect plotrect cwnd pwndparent getparent pwndparent plotrect plotrect theprefs gettrafficometerinterval plotrect pwndparent sendmessage um_oscopeposition plotrect void co scope ctrl on sys color change if m pbitmapoldgrid null m dcgrid select object m pbitmapoldgrid m pbitmapoldgrid null verify m dcgrid deletedc if m pbitmapoldplot null m dcplot select object m pbitmapoldplot m pbitmapoldplot null verify m dcplot deletedc c wnd on sys color change invalidate ctrl false coscopectrl onsyscolorchange m_pbitmapoldgrid m_dcgrid selectobject m_pbitmapoldgrid m_pbitmapoldgrid m_dcgrid m_pbitmapoldplot m_dcplot selectobject m_pbitmapoldplot m_pbitmapoldplot m_dcplot cwnd onsyscolorchange invalidatectrl void c web socket set parent c web server p parent m pparent p parent cwebsocket setparent cwebserver pparent m_pparent pparent void c web socket on received void p data dword dw size in addr inad const uint size preserve 0x1000 if m dwbufsize dw size m dwrecv reallocate char p new buf new char m dwbufsize dw size m dwrecv size preserve if p new buf m bvalid false internal problem return if m pbuf copy memory p new buf m pbuf m dwrecv delete m pbuf m pbuf p new buf copy memory m pbuf m dwrecv p data dw size m dwrecv dw size check if we have all that we want if m dwhttpheaderlen try to find it bool b prev endl false for dword dw pos 0 dw pos m dwrecv dw pos if n m pbuf dw pos if b prev endl we just found the end of the http header now write the message s position into two first dwor ds of the buffer m dwhttpheaderlen dw pos 1 try to find now the content length header for dw pos 0 dw pos m dwhttpheaderlen elandal p ptr is actually a char not a void char p ptr char memchr m pbuf dw pos n m dwhttpheaderlen dw pos if p ptr break elandal and thus now the pointer substraction works as it should dword dw next pos p ptr m pbuf check this header char sz match content length if strnicmp m pbuf dw pos sz match sizeof sz match 1 dw pos sizeof sz match 1 p ptr char memchr m pbuf dw pos m dwhttpheaderlen dw pos if p ptr m dwhttpcontentlen atol p ptr 1 break dw pos dw next pos 1 break else b prev endl true else if r m pbuf dw pos b prev endl false if m dwhttpheaderlen m bcanrecv m dwhttpcontentlen m dwhttpcontentlen m dwrecv m dwhttpheaderlen of course if m dwhttpheaderlen m dwhttpcontentlen m dwrecv m dwhttpcontentlen m dwhttpheaderlen m dwhttpcontentlen m dwrecv on request received m pbuf m dwhttpheaderlen m pbuf m dwhttpheaderlen m dwhttpcontentlen inad if m bcanrecv m dwrecv m dwhttpheaderlen m dwhttpcontentlen move our data m dwrecv m dwhttpheaderlen m dwhttpcontentlen move memory m pbuf m pbuf m dwhttpheaderlen m dwhttpcontentlen m dwrecv else m dwrecv 0 m dwhttpheaderlen 0 m dwhttpcontentlen 0 cwebsocket onreceived pdata dwsize in_addr size_preserve m_dwbufsize dwsize m_dwrecv pnewbuf m_dwbufsize dwsize m_dwrecv size_preserve pnewbuf m_bvalid m_pbuf copymemory pnewbuf m_pbuf m_dwrecv m_pbuf m_pbuf pnewbuf copymemory m_pbuf m_dwrecv pdata dwsize m_dwrecv dwsize m_dwhttpheaderlen bprevendl dwpos dwpos m_dwrecv dwpos m_pbuf dwpos bprevendl dwords m_dwhttpheaderlen dwpos dwpos dwpos m_dwhttpheaderlen pptr pptr m_pbuf dwpos m_dwhttpheaderlen dwpos pptr dwnextpos pptr m_pbuf szmatch m_pbuf dwpos szmatch szmatch dwpos szmatch pptr m_pbuf dwpos m_dwhttpheaderlen dwpos pptr m_dwhttpcontentlen pptr dwpos dwnextpos bprevendl m_pbuf dwpos bprevendl m_dwhttpheaderlen m_bcanrecv m_dwhttpcontentlen m_dwhttpcontentlen m_dwrecv m_dwhttpheaderlen m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwhttpcontentlen m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv onrequestreceived m_pbuf m_dwhttpheaderlen m_pbuf m_dwhttpheaderlen m_dwhttpcontentlen m_bcanrecv m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen movememory m_pbuf m_pbuf m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen void c web socket send data const void p data dword dw data size assert p data if m bvalid m bcansend if m phead try to send it directly remember in n res could be 1 after send call int n res send m hsocket const char p data dw data size 0 if n res 0 n res signed dw data size wsaewouldblock wsa get last error m bvalid false else in n res still could be 1 if wsaewouldblock occured next to line should be like this const char p data n res 1 0 n res dw data size n res 1 0 n res and not like this const char p data n res dw data size n res if dw data size m bvalid push it to our tails c chunk p chunk new c chunk if p chunk p chunk m pnext null p chunk m dwsize dw data size if p chunk m pdata new char dw data size null data should be copied into p chunk m pdata anyhow possible solution is simple copy memory p chunk m pdata p data dw data size push it to the end of our queue p chunk m ptosend p chunk m pdata if m ptail m ptail m pnext p chunk else m phead p chunk m ptail p chunk else delete p chunk oops no memory cwebsocket senddata pdata dwdatasize pdata m_bvalid m_bcansend m_phead nres nres m_hsocket pdata dwdatasize nres nres dwdatasize wsagetlasterror m_bvalid nres pdata nres nres dwdatasize nres nres pdata nres dwdatasize nres dwdatasize m_bvalid cchunk pchunk cchunk pchunk pchunk m_pnext pchunk m_dwsize dwdatasize pchunk m_pdata dwdatasize pchunk m_pdata copymemory pchunk m_pdata pdata dwdatasize pchunk m_ptosend pchunk m_pdata m_ptail m_ptail m_pnext pchunk m_phead pchunk m_ptail pchunk pchunk void c web socket send content lpcstr sz std response const void p content dword dw content size char sz buf 0x1000 int n len wsprintfa sz buf http 1 1 200 ok r n s content length ld r n r n sz std response dw content size send data sz buf n len send data p content dw content size cwebsocket sendcontent szstdresponse pcontent dwcontentsize szbuf nlen szbuf scontent szstdresponse dwcontentsize senddata szbuf nlen senddata pcontent dwcontentsize void c web socket send reply lpcstr sz reply char sz buf 256 int n len wsprintfa sz buf sr n sz reply assert n len arrsize sz buf send data sz buf n len cwebsocket sendreply szreply szbuf nlen szbuf szreply nlen szbuf senddata szbuf nlen void c web socket disconnect if m bvalid m bcansend m bcansend false if m ptail push it as a tail c chunk p chunk new c chunk if p chunk p chunk m dwsize 0 p chunk m pdata null p chunk m ptosend null p chunk m pnext null m ptail m pnext p chunk else if shutdown m hsocket sd send m bvalid false cwebsocket m_bvalid m_bcansend m_bcansend m_ptail cchunk pchunk cchunk pchunk pchunk m_dwsize pchunk m_pdata pchunk m_ptosend pchunk m_pnext m_ptail m_pnext pchunk m_hsocket sd_send m_bvalid void c web socket on request received char p header dword dw header len char p data dword dw data len in addr inad c stringa s header p header dw header len c stringa s data p data dw data len c stringa surl bool filereq false if s header left 3 get surl s header trim else if s header left 4 post surl s data trim to imitate get syntax for parseurl if surl find 1 surl surl mid surl find 1 surl get length if surl find 1 surl surl left surl find if surl get length 4 min length for valid extentions surl right 4 make lower gif surl right 4 make lower jpg surl right 4 make lower png surl right 4 make lower ico surl right 4 make lower css surl right 3 make lower js surl right 4 make lower bmp surl right 5 make lower jpeg surl find 1 dont allow leaving the emule webserver folder for accessing files filereq true thread data data data surl surl data p this m pparent data inadr inad data p socket this if filereq m pparent processurl data else m pparent process file req data disconnect cwebsocket onrequestreceived pheader dwheaderlen pdata dwdatalen in_addr cstringa sheader pheader dwheaderlen cstringa sdata pdata dwdatalen cstringa sheader sheader sheader sdata getlength getlength makelower makelower makelower makelower makelower makelower makelower makelower threaddata pthis m_pparent psocket m_pparent m_pparent processfilereq c client list c client list m dwlastbanncleanup 0 m dwlasttrackedcleanup 0 m dwlastclientcleanup 0 m nbuddystatus disconnected m bannedlist init hash table 331 m trackedclientslist init hash table 2011 m globdeadsourcelist init true m pbuddy null cclientlist cclientlist m_dwlastbanncleanup m_dwlasttrackedcleanup m_dwlastclientcleanup m_nbuddystatus m_bannedlist inithashtable m_trackedclientslist inithashtable m_globdeadsourcelist m_pbuddy c client list c client list remove all tracked clients cclientlist cclientlist removealltrackedclients void c client list add client c up down client toadd bool b skip dup test skipping the check for duplicate list entries is only to be done for optimization purposes if the calling function has ensured that this client instance is not already within the list there are never duplicate client instances in this list if b skip dup test if list find toadd return the app emuledlg transferwnd clientlistctrl add client toadd list add tail toadd cclientlist addclient cupdownclient bskipduptest bskipduptest theapp addclient addtail void c client list remove client c up down client toremove lpctstr psz reason position pos list find toremove if pos the app uploadqueue remove from upload queue toremove psz reason the app uploadqueue remove from waiting queue toremove the app downloadqueue remove source toremove the app emuledlg transferwnd clientlistctrl remove client toremove remove from kad list toremove list remove at pos cclientlist removeclient cupdownclient pszreason theapp removefromuploadqueue pszreason theapp removefromwaitingqueue theapp removesource theapp removeclient removefromkadlist removeat c map uint32 uint32 uint32 uint32 client versiona mule ru total clients list get count memset stats 0 sizeof stats 0 num clientlist stats for position pos list get head position pos null const c up down client cur client list get next pos if cur client has lowid stats 14 switch cur client get client soft case so emule case so oldemule stats 2 client versione mule cur client get version break case so edonkeyhybrid stats 4 client versione donkey hybrid cur client get version break case so amule stats 10 client versiona mule cur client get version break case so edonkey stats 1 client versione donkey cur client get version break case so mldonkey stats 3 break case so shareaza stats 11 break all remaining e mule compatible clients case so cdonkey case so xmule case so lphant stats 5 break default stats 0 break if cur client credits null switch cur client credits get current ident state cur client getip case is identified stats 12 break case is idfailed case is idneeded case is idbadguy stats 13 break if cur client get download state ds error cur client get upload state us error stats 6 error switch cur client get user port case 4662 stats 8 default port break default stats 9 other port network client stats if cur client get serverip cur client get server port stats 15 ed2k if cur client get kad port stats 17 ed2k kad stats 16 kad else if cur client get kad port stats 16 kad else stats 18 unknown cmap clientversionamule rutotalclients getcount num_clientlist_stats getheadposition cupdownclient cur_client getnext cur_client haslowid cur_client getclientsoft so_emule so_oldemule clientversionemule cur_client getversion so_edonkeyhybrid clientversionedonkeyhybrid cur_client getversion so_amule clientversionamule cur_client getversion so_edonkey clientversionedonkey cur_client getversion so_mldonkey so_shareaza emule so_cdonkey so_xmule so_lphant cur_client cur_client getcurrentidentstate cur_client is_identified is_idfailed is_idneeded is_idbadguy cur_client getdownloadstate ds_error cur_client getuploadstate us_error cur_client getuserport cur_client getserverip cur_client getserverport cur_client getkadport cur_client getkadport void c client list delete all the app uploadqueue delete all the app downloadqueue delete all position pos1 pos2 for pos1 list get head position pos2 pos1 null list get next pos1 c up down client cur client list get at pos2 list remove at pos2 delete cur client recursiv this will call remove client cclientlist deleteall theapp deleteall theapp deleteall getheadposition getnext cupdownclient cur_client getat removeat cur_client removeclient bool c client list attach to already known c up down client client c client req socket sender position pos1 pos2 c up down client tocheck client c up down client found client null c up down client found client2 null for pos1 list get head position pos2 pos1 null list get next pos1 c up down client cur client list get at pos2 if tocheck compare cur client false matching userhash found client2 cur client if tocheck compare cur client true matching ip found client cur client break if found client null found client found client2 if found client null if tocheck found client we found the same client instance client may have sent more than one op hello do not delete that client return true if sender if found client socket if found client socket is connected found client getip tocheck getip found client get user port tocheck get user port if found client is connected and has the is identified it s safe to say that the other one is a bad guy if found client credits found client credits get current ident state found client getip is identified if the prefs get log banned clients add debug log line false t clients s s banreason userhash invalid tocheck get user name ipstr tocheck get connectip tocheck ban return false ids clientcol warning found matching client to a currently connected client s s and s s if the prefs get log banned clients add debug log line true get res string ids clientcol tocheck get user name ipstr tocheck get connectip found client get user name ipstr found client get connectip return false found client socket client 0 found client socket safe delete found client socket sender tocheck socket 0 client 0 delete tocheck client found client return true return false cclientlist attachtoalreadyknown cupdownclient cclientreqsocket cupdownclient cupdownclient found_client cupdownclient found_client2 getheadposition getnext cupdownclient cur_client getat cur_client found_client2 cur_client cur_client found_client cur_client found_client found_client found_client2 found_client found_client op_hello found_client found_client isconnected found_client found_client getuserport getuserport found_client is_identified found_client found_client getcurrentidentstate found_client is_identified theprefs getlogbannedclients adddebuglogline _t getusername getconnectip ids_clientcol theprefs getlogbannedclients adddebuglogline getresstring ids_clientcol getusername getconnectip found_client getusername found_client getconnectip found_client found_client safe_delete found_client found_client c up down client c client list find client byip uint32 clientip uint port const for position pos list get head position pos null c up down client cur client list get next pos if cur client getip clientip cur client get user port port return cur client return 0 cupdownclient cclientlist findclientbyip getheadposition cupdownclient cur_client getnext cur_client cur_client getuserport cur_client c up down client c client list find client by user hash const uchar clienthash const for position pos list get head position pos null c up down client cur client list get next pos if md4cmp cur client get user hash clienthash return cur client return 0 cupdownclient cclientlist findclientbyuserhash getheadposition cupdownclient cur_client getnext cur_client getuserhash cur_client c up down client c client list find client byip uint32 clientip const for position pos list get head position pos null c up down client cur client list get next pos if cur client getip clientip return cur client return 0 cupdownclient cclientlist findclientbyip getheadposition cupdownclient cur_client getnext cur_client cur_client c up down client c client list findclientbyip udp uint32 clientip uint nud pport const for position pos list get head position pos null c up down client cur client list get next pos if cur client getip clientip cur client getudp port nud pport return cur client return 0 cupdownclient cclientlist findclientbyip_udp nudpport getheadposition cupdownclient cur_client getnext cur_client cur_client getudpport nudpport cur_client c up down client c client list find client by serverid uint32 u serverip uint32 ued2k userid const uint32 u hybrid userid ntohl ued2k userid for position pos list get head position pos null c up down client cur client list get next pos if cur client get serverip u serverip cur client get userid hybrid u hybrid userid return cur client return 0 cupdownclient cclientlist findclientbyserverid userverip ued2kuserid uhybriduserid ued2kuserid getheadposition cupdownclient cur_client getnext cur_client getserverip userverip cur_client getuseridhybrid uhybriduserid cur_client c up down client c client list findclientbyuserid kadport uint32 clientid uint16 kad port const for position pos list get head position pos null c up down client cur client list get next pos if cur client get userid hybrid clientid cur client get kad port kad port return cur client return 0 cupdownclient cclientlist findclientbyuserid_kadport kadport getheadposition cupdownclient cur_client getnext cur_client getuseridhybrid cur_client getkadport kadport cur_client c up down client c client list findclientbyip kadport uint32 ip uint16 port const for position pos list get head position pos null c up down client cur client list get next pos if cur client getip ip cur client get kad port port return cur client return 0 cupdownclient cclientlist findclientbyip_kadport getheadposition cupdownclient cur_client getnext cur_client cur_client getkadport cur_client void c client list add banned client uint32 dwip m bannedlist set at dwip get tick count cclientlist addbannedclient m_bannedlist setat gettickcount bool c client list is banned client uint32 dwip const uint32 dw bantime if m bannedlist lookup dwip dw bantime if dw bantime clientbantime get tick count return true return false cclientlist isbannedclient dwbantime m_bannedlist dwbantime dwbantime gettickcount void c client list remove banned client uint32 dwip m bannedlist remove key dwip cclientlist removebannedclient m_bannedlist removekey void c client list remove all banned clients m bannedlist remove all cclientlist removeallbannedclients m_bannedlist removeall void c client list add track client c up down client toadd c deleted client p result 0 if m trackedclientslist lookup toadd getip p result p result m dwinserted get tick count for int i 0 i p result m itemslist get count i if p result m itemslist i n port toadd get user port already tracked update p result m itemslist i p hash toadd credits return portandhash porthash toadd get user port toadd credits p result m itemslist add porthash else m trackedclientslist set at toadd getip new c deleted client toadd cclientlist addtrackclient cupdownclient cdeletedclient presult m_trackedclientslist presult presult m_dwinserted gettickcount presult m_itemslist getcount presult m_itemslist nport getuserport presult m_itemslist phash getuserport presult m_itemslist m_trackedclientslist setat cdeletedclient false hash changed bool c client list compare prior userhash uint32 dwip uint16 n port void p new hash c deleted client p result 0 if m trackedclientslist lookup dwip p result for int i 0 i p result m itemslist get count i if p result m itemslist i n port n port if p result m itemslist i p hash p new hash return false else break return true cclientlist compareprioruserhash nport pnewhash cdeletedclient presult m_trackedclientslist presult presult m_itemslist getcount presult m_itemslist nport nport presult m_itemslist phash pnewhash uint c client list get clients fromip uint32 dwip const c deleted client p result if m trackedclientslist lookup dwip p result return p result m itemslist get count return 0 cclientlist getclientsfromip cdeletedclient presult m_trackedclientslist presult presult m_itemslist getcount void c client list track bad request const c up down client upc client int n increase counter c deleted client p result null if upc client getip 0 assert false return if m trackedclientslist lookup upc client getip p result p result m dwinserted get tick count p result m cbadrequest n increase counter else c deleted client cc to add new c deleted client upc client cc to add m cbadrequest n increase counter m trackedclientslist set at upc client getip cc to add cclientlist trackbadrequest cupdownclient upcclient nincreasecounter cdeletedclient presult upcclient m_trackedclientslist upcclient presult presult m_dwinserted gettickcount presult m_cbadrequest nincreasecounter cdeletedclient cctoadd cdeletedclient upcclient cctoadd m_cbadrequest nincreasecounter m_trackedclientslist setat upcclient cctoadd uint32 c client list get bad requests const c up down client upc client const c deleted client p result null if upc client getip 0 assert false return 0 if m trackedclientslist lookup upc client getip p result return p result m cbadrequest else return 0 cclientlist getbadrequests cupdownclient upcclient cdeletedclient presult upcclient m_trackedclientslist upcclient presult presult m_cbadrequest void c client list remove all tracked clients position pos m trackedclientslist get start position uint32 n key c deleted client p result while pos null m trackedclientslist get next assoc pos n key p result m trackedclientslist remove key n key delete p result cclientlist removealltrackedclients m_trackedclientslist getstartposition nkey cdeletedclient presult m_trackedclientslist getnextassoc nkey presult m_trackedclientslist removekey nkey presult void c client list requesttcp kademlia c contact contact uint32 n contactip ntohl contact getip address don t connect ourself if the app serverconnect get localip n contactip the prefs get port contact gettcp port return c up down client p new client find client byip n contactip contact gettcp port if p new client p new client new c up down client 0 contact gettcp port contact getip address 0 0 false add client to the lists to be processed p new client set kad port contact getudp port p new client set kad state ks queued fwcheck m kadlist add tail p new client this method checks if this is a dup already add client p new client cclientlist ccontact ncontactip getipaddress theapp getlocalip ncontactip theprefs getport gettcpport cupdownclient pnewclient findclientbyip ncontactip gettcpport pnewclient pnewclient cupdownclient gettcpport getipaddress pnewclient setkadport getudpport pnewclient setkadstate ks_queued_fwcheck m_kadlist addtail pnewclient addclient pnewclient void c client list request buddy kademlia c contact contact uint32 n contactip ntohl contact getip address don t connect ourself if the app serverconnect get localip n contactip the prefs get port contact gettcp port return c up down client p new client find client byip n contactip contact gettcp port if p new client p new client new c up down client 0 contact gettcp port contact getip address 0 0 false add client to the lists to be processed p new client set kad port contact getudp port p new client set kad state ks queued buddy byte id 16 contact get clientid to byte array id p new client set user hash id add to kad list p new client this method checks if this is a dup already add client p new client cclientlist requestbuddy ccontact ncontactip getipaddress theapp getlocalip ncontactip theprefs getport gettcpport cupdownclient pnewclient findclientbyip ncontactip gettcpport pnewclient pnewclient cupdownclient gettcpport getipaddress pnewclient setkadport getudpport pnewclient setkadstate ks_queued_buddy getclientid tobytearray pnewclient setuserhash addtokadlist pnewclient addclient pnewclient void c client list incoming buddy kademlia c contact contact kademlia cu int128 buddyid uint32 n contactip ntohl contact getip address if e mule already knows this client abort this it could cause conflicts although the odds of this happening is very small it could still happen if find client byip n contactip contact gettcp port return don t connect ourself if the app serverconnect get localip n contactip the prefs get port contact gettcp port return add client to the lists to be processed c up down client p new client new c up down client 0 contact gettcp port contact getip address 0 0 false p new client set kad port contact getudp port p new client set kad state ks incoming buddy byte id 16 contact get clientid to byte array id p new client set user hash id buddyid to byte array id p new client set buddyid id add to kad list p new client add client p new client cclientlist incomingbuddy ccontact cuint128 ncontactip getipaddress emule findclientbyip ncontactip gettcpport theapp getlocalip ncontactip theprefs getport gettcpport cupdownclient pnewclient cupdownclient gettcpport getipaddress pnewclient setkadport getudpport pnewclient setkadstate ks_incoming_buddy getclientid tobytearray pnewclient setuserhash tobytearray pnewclient setbuddyid addtokadlist pnewclient addclient pnewclient void c client list remove from kad list c up down client torem position pos m kadlist find torem if pos if torem m pbuddy m pbuddy null the app emuledlg serverwnd update my info m kadlist remove at pos cclientlist removefromkadlist cupdownclient m_kadlist m_pbuddy m_pbuddy theapp updatemyinfo m_kadlist removeat void c client list add to kad list c up down client toadd if toadd return position pos m kadlist find toadd if pos return m kadlist add tail toadd cclientlist addtokadlist cupdownclient m_kadlist m_kadlist addtail void c client list process cleanup banned client list const uint32 cur tick get tick count if m dwlastbanncleanup ban cleanup time cur tick m dwlastbanncleanup cur tick position pos m bannedlist get start position uint32 n key uint32 dw bantime while pos null m bannedlist get next assoc pos n key dw bantime if dw bantime clientbantime cur tick remove banned client n key cleanup tracked client list if m dwlasttrackedcleanup tracked cleanup time cur tick m dwlasttrackedcleanup cur tick if the prefs get log banned clients add debug log line false t cleaning up tracked client list i clients on list m trackedclientslist get count position pos m trackedclientslist get start position uint32 n key c deleted client p result while pos null m trackedclientslist get next assoc pos n key p result if p result m dwinserted keeptrack time cur tick m trackedclientslist remove key n key delete p result if the prefs get log banned clients add debug log line false t done i clients left on list m trackedclientslist get count process kad client list we need to try to connect to the clients in m kadlist if connected remove them from the list and send a message back to kad so we can send a ack if we don t connect we need to remove the client the sockets timeout should delete this object position pos1 pos2 buddy is just a flag that is used to make sure we are still connected or connecting to a buddy buddy state buddy disconnected for pos1 m kadlist get head position pos2 pos1 null m kadlist get next pos1 c up down client cur client m kadlist get at pos2 if kademlia c kademlia is running clear out this list if we stop running kad setting the kad state to ks none causes it to be removed in the switch below cur client set kad state ks none switch cur client get kad state case ks queued fwcheck another client asked us to try to connect to them to check their firewalled status cur client try to connect true break case ks connecting fwcheck ignore this state as we are just waiting for results break case ks connected fwcheck we successfully connected to the client we now send a ack to let them know if the prefs get debug client kadudp level 0 debug send kademlia firewalled ack res cur client getip cur client get kad port kademlia c kademlia getudp listener send null packet kademlia firewalled ack res ntohl cur client getip cur client get kad port we are done with this client set kad status to ks none and it will be removed in the next cycle cur client set kad state ks none break case ks incoming buddy a firewalled client wants us to be his buddy if we already have a buddy we set kad state to ks none and it s removed in the next cycle if not this client will change to ks connected buddy when it connects if m nbuddystatus connected cur client set kad state ks none break case ks queued buddy we are firewalled and want to request this client to be a buddy but first we check to make sure we are not already trying another client if we are not already trying we try to connect to this client if we are already connected to a buddy we set this client to ks none and it s removed next cycle if we are trying to connect to a buddy we just ignore as the one we are trying may fail and we can then try this one if m nbuddystatus disconnected buddy connecting m nbuddystatus connecting cur client set kad state ks connecting buddy cur client try to connect true the app emuledlg serverwnd update my info else if m nbuddystatus connected cur client set kad state ks none break case ks connecting buddy we are trying to connect to this client although it should not happen we make sure we are not already connected to a buddy if we are we set to ks none and it s removed next cycle but if we are not already connected make sure we set the flag to connecting so we know things are working correctly if m nbuddystatus connected cur client set kad state ks none else assert m nbuddystatus connecting buddy connecting break case ks connected buddy a potential connected buddy client wanting to me in the kad network we set our flag to connected to make sure things are still working correctly buddy connected if m nbuddystatus is not connected already we set this client as our buddy if m nbuddystatus connected m pbuddy cur client m nbuddystatus connected the app emuledlg serverwnd update my info if m pbuddy cur client the app is firewalled cur client send buddy ping pong if the prefs get debug clienttcp level 0 debug send op buddyping cur client packet buddy ping new packet op buddyping 0 op emuleprot the stats add up data overhead other buddy ping size cur client safe send packet buddy ping cur client set last buddy ping pong time break default remove from kad list cur client we either never had a buddy or lost our buddy if buddy disconnected if m nbuddystatus disconnected m pbuddy if kademlia c kademlia is running the app is firewalled we are a lowid client and we just lost our buddy go ahead and instantly try to find a new buddy kademlia c kademlia get prefs set find buddy m pbuddy null m nbuddystatus disconnected the app emuledlg serverwnd update my info if kademlia c kademlia is connected if kademlia c kademlia is firewalled if m nbuddystatus disconnected kademlia c kademlia get prefs get find buddy we are a firewalled client with no buddy we have also waited a set time to try to avoid a false firewalled status so lets look for a buddy if kademlia c search manager prepare lookup kademlia c search findbuddy true kademlia cu int128 true xor kademlia c kademlia get prefs get kadid this search id was already going most likely reason is that we found and lost our buddy very quickly and the last search hadn t had time to be removed yet go ahead and set this to happen again next time around kademlia c kademlia get prefs set find buddy else if m pbuddy lets make sure that if we have a buddy they are firewalled if they are also not firewalled then someone must have fixed their firewall or stopped saturating their line we just set the state of this buddy to ks none and things will be cleared up with the next cycle if m pbuddy has lowid m pbuddy set kad state ks none else if m pbuddy we are not connected anymore just set this buddy to ks none and things will be cleared out on next cycle m pbuddy set kad state ks none cleanup client list clean up client list cclientlist cur_tick gettickcount m_dwlastbanncleanup ban_cleanup_time cur_tick m_dwlastbanncleanup cur_tick m_bannedlist getstartposition nkey dwbantime m_bannedlist getnextassoc nkey dwbantime dwbantime cur_tick removebannedclient nkey m_dwlasttrackedcleanup tracked_cleanup_time cur_tick m_dwlasttrackedcleanup cur_tick theprefs getlogbannedclients adddebuglogline _t trackedclientlist m_trackedclientslist getcount m_trackedclientslist getstartposition nkey cdeletedclient presult m_trackedclientslist getnextassoc nkey presult presult m_dwinserted keeptrack_time cur_tick m_trackedclientslist removekey nkey presult theprefs getlogbannedclients adddebuglogline _t m_trackedclientslist getcount m_kadlist buddystate m_kadlist getheadposition m_kadlist getnext cupdownclient cur_client m_kadlist getat ckademlia isrunning ks_none cur_client setkadstate ks_none cur_client getkadstate ks_queued_fwcheck cur_client trytoconnect ks_connecting_fwcheck ks_connected_fwcheck theprefs getdebugclientkadudplevel debugsend kademlia_firewalled_ack_res cur_client cur_client getkadport ckademlia getudplistener sendnullpacket kademlia_firewalled_ack_res cur_client cur_client getkadport ks_none cur_client setkadstate ks_none ks_incoming_buddy ks_none ks_connected_buddy m_nbuddystatus cur_client setkadstate ks_none ks_queued_buddy ks_none m_nbuddystatus m_nbuddystatus cur_client setkadstate ks_connecting_buddy cur_client trytoconnect theapp updatemyinfo m_nbuddystatus cur_client setkadstate ks_none ks_connecting_buddy ks_none m_nbuddystatus cur_client setkadstate ks_none m_nbuddystatus ks_connected_buddy m_nbuddystatus m_nbuddystatus m_pbuddy cur_client m_nbuddystatus theapp updatemyinfo m_pbuddy cur_client theapp isfirewalled cur_client sendbuddypingpong theprefs getdebugclienttcplevel debugsend op__buddyping cur_client buddyping op_buddyping op_emuleprot thestats addupdataoverheadother buddyping cur_client safesendpacket buddyping cur_client setlastbuddypingpongtime removefromkadlist cur_client m_nbuddystatus m_pbuddy ckademlia isrunning theapp isfirewalled ckademlia getprefs setfindbuddy m_pbuddy m_nbuddystatus theapp updatemyinfo ckademlia isconnected ckademlia isfirewalled m_nbuddystatus ckademlia getprefs getfindbuddy csearchmanager preparelookup csearch cuint128 ckademlia getprefs getkadid ckademlia getprefs setfindbuddy m_pbuddy ks_none m_pbuddy haslowid m_pbuddy setkadstate ks_none m_pbuddy ks_none m_pbuddy setkadstate ks_none cleanupclientlist bool c client list is valid client c up down client tocheck const if the prefs m idbgheap 2 assert valid tocheck return list find tocheck null cclientlist isvalidclient cupdownclient theprefs m_idbgheap assert_valid zz upload speed sense bool c client list give clients for trace route this is a host that last common route finder can use to traceroute return the app last common route finder add hosts to check list uploadspeedsense cclientlist giveclientsfortraceroute lastcommonroutefinder theapp lastcommonroutefinder addhoststocheck zz download manager void c client list processa4af clients const if the prefs get loga4af add debug log line false t starting a4af check position pos1 pos2 for pos1 list get head position pos2 pos1 null list get next pos1 c up down client cur client list get at pos2 if cur client get download state ds downloading cur client get download state ds connected cur client m otherrequests list is empty cur client m othernoneeded list is empty add debug log line false t zz download manager trying for better file for source s s cur client get user name cur client reqfile get file name cur client swap to another file t periodic a4af check c client list processa4af clients false false false null true false if the prefs get loga4af add debug log line false t done with a4af check downloadmanager cclientlist processa4afclients theprefs getloga4af adddebuglogline _t getheadposition getnext cupdownclient cur_client getat cur_client getdownloadstate ds_downloading cur_client getdownloadstate ds_connected cur_client m_otherrequests_list isempty cur_client m_othernoneeded_list isempty adddebuglogline _t downloadmanager cur_client getusername cur_client getfilename cur_client swaptoanotherfile _t cclientlist processa4afclients theprefs getloga4af adddebuglogline _t void c client list clean up client list we remove clients which are not needed any more by time this check is also done on c up down client disconnected however it will not catch all cases if a client changes the state without beeing connected adding this check directly to every point where any state changes would be more effective is however not compatible with the current code because there are points where a client has no state for some code lines and the code is also not prepared that a client object gets invalid while working with it aka setting a new state so this way is just the easy and safe one to go as long as emule is basically single threaded const uint32 cur tick get tick count if m dwlastclientcleanup clientlist cleanup time cur tick m dwlastclientcleanup cur tick position pos1 pos2 uint32 c deleted 0 for pos1 list get head position pos2 pos1 null list get next pos1 c up down client p cur client list get at pos2 if p cur client get upload state us none p cur client get upload state us banned p cur client is banned p cur client get download state ds none p cur client get chat state ms none p cur client get kad state ks none p cur client socket null c deleted delete p cur client debug only add debug log line false t cleaned client list removed i not used known clients c deleted cclientlist cleanupclientlist cupdownclient cur_tick gettickcount m_dwlastclientcleanup clientlist_cleanup_time cur_tick m_dwlastclientcleanup cur_tick cdeleted getheadposition getnext cupdownclient pcurclient getat pcurclient getuploadstate us_none pcurclient getuploadstate us_banned pcurclient isbanned pcurclient getdownloadstate ds_none pcurclient getchatstate ms_none pcurclient getkadstate ks_none pcurclient cdeleted pcurclient debug_only adddebuglogline _t clientlist cdeleted c known file list c known file list m files map init hash table 2063 m mapcancelledfiles init hash table 1031 accepted 0 requested 0 transferred 0 m nlastsaved get tick count init cknownfilelist cknownfilelist m_files_map inithashtable m_mapcancelledfiles inithashtable m_nlastsaved gettickcount c known file list c known file list clear cknownfilelist cknownfilelist bool c known file list safe addk file c known file toadd cc key key toadd get file hash c known file p file in map if m files map lookup key p file in map trace t hs file already in known file list s s s n function md4str p file in map get file hash p file in map get file name p file in map get file path trace t hs old entry replaced with s s s n function md4str toadd get file hash toadd get file name toadd get file path if 1 if we hash files which are already in known file list and add them later when the hashing thread is finished we can not delete any already available entry from known files list that entry can already be used by the shared file list crash m files map remove key cc key p file in map get file hash this can happen in a couple situations file was renamed outside of e mule a user decided to redownload a file he has downloaded and unshared removing key words i believe is not thread safe if i m looking at this right not sure of a good solution yet if the app sharedfiles the app sharedfiles remove file p file in map assert the app sharedfiles is file ptr in list p file in map double check to make sure this is the same file as it s possible that a two files have the same hash maybe in the furture we can change the client to not just use hash as a key throughout the entire client assert toadd get file size p file in map get file size assert toadd p file in map if toadd get file size p file in map get file size toadd statistic merge file stats p file in map statistic assert the app sharedfiles null the app sharedfiles is file ptr in list p file in map assert the app downloadqueue null the app downloadqueue is part file p file in map quick fix if we downloaded already downloaded files again and if those files all had the same file names and were renamed during file completion we have a pending ptr in transfer window if the app emuledlg the app emuledlg transferwnd the app emuledlg transferwnd downloadlistctrl m hwnd the app emuledlg transferwnd downloadlistctrl remove file c part file p file in map delete p file in map else if the new entry is already in list update the stats and return false but do not delete the entry which is alreay in known file list assert toadd get file size p file in map get file size assert toadd p file in map if toadd get file size p file in map get file size toadd p file in map p file in map statistic merge file stats toadd statistic p file in map set file name toadd get file name false p file in map set path toadd get path p file in map set file path toadd get file path p file in map date toadd date assert the app sharedfiles is file ptr in list p file in map assert the app sharedfiles is file ptr in list toadd return false endif m files map set at key toadd return true cknownfilelist safeaddkfile cknownfile cckey getfilehash cknownfile pfileinmap m_files_map pfileinmap _t __function__ pfileinmap getfilehash pfileinmap getfilename pfileinmap getfilepath _t __function__ getfilehash getfilename getfilepath m_files_map removekey cckey pfileinmap getfilehash emule removingkeywords theapp theapp removefile pfileinmap theapp isfileptrinlist pfileinmap getfilesize pfileinmap getfilesize pfileinmap getfilesize pfileinmap getfilesize mergefilestats pfileinmap theapp theapp isfileptrinlist pfileinmap theapp theapp ispartfile pfileinmap theapp theapp theapp m_hwnd theapp removefile cpartfile pfileinmap pfileinmap getfilesize pfileinmap getfilesize pfileinmap getfilesize pfileinmap getfilesize pfileinmap pfileinmap mergefilestats pfileinmap setfilename getfilename pfileinmap setpath getpath pfileinmap setfilepath getfilepath pfileinmap theapp isfileptrinlist pfileinmap theapp isfileptrinlist m_files_map setat bool c known file list init return load known files load cancelled files cknownfilelist loadknownfiles loadcancelledfiles void c known file list save if the prefs get log file saving add debug log line false t saving known files list file s known met filename m nlastsaved get tick count c string fullpath the prefs get config dir fullpath known met filename c safe buffered file file c file exception fexp if file open fullpath c file mode write c file mode create c file type binary c file share deny write fexp c string str error t failed to save known met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error else setvbuf file m pstream null iofbf 16384 try file writeu int8 0 we will write the version tag later depending if any large files are on the list uint n records number 0 bool b contains any large files false file writeu int32 n records number position pos m files map get start position while pos null c known file p file cc key key m files map get next assoc pos key p file if the prefs is remembering downloaded files the app sharedfiles is file ptr in list p file continue else p file write to file file n records number if p file is large file b contains any large files true file seek to begin file writeu int8 b contains any large files met header i64tags met header file writeu int32 n records number if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush flush file stream buffers to disk buffers if commit fileno file m pstream 0 commit disk buffers to disk afx throw file exception c file exception hardio get last error file get file name file close catch c file exception error c string str error t failed to save known met filename t file tchar sz error max cfexp errormsg if error get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error error delete if the prefs get log file saving add debug log line false t saving known files list file s cancelled met filename fullpath the prefs get config dir fullpath cancelled met filename if file open fullpath c file mode write c file mode create c file type binary c file share deny write fexp c string str error t failed to save cancelled met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error else setvbuf file m pstream null iofbf 16384 try file writeu int8 met header if the prefs is remembering cancelled files file writeu int32 0 else uint n records number m mapcancelledfiles get count file writeu int32 n records number position pos m mapcancelledfiles get start position while pos null int dw dummy cs key key m mapcancelledfiles get next assoc pos key dw dummy file write hash16 key m key file writeu int8 0 if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush flush file stream buffers to disk buffers if commit fileno file m pstream 0 commit disk buffers to disk afx throw file exception c file exception hardio get last error file get file name file close catch c file exception error c string str error t failed to save cancelled met filename t file tchar sz error max cfexp errormsg if error get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error error delete cknownfilelist theprefs getlogfilesaving adddebuglogline _t known_met_filename m_nlastsaved gettickcount cstring theprefs getconfigdir known_met_filename csafebufferedfile cfileexception cfile modewrite cfile modecreate cfile typebinary cfile sharedenywrite cstring strerror _t known_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf writeuint8 nrecordsnumber bcontainsanylargefiles writeuint32 nrecordsnumber m_files_map getstartposition cknownfile pfile cckey m_files_map getnextassoc pfile theprefs isrememberingdownloadedfiles theapp isfileptrinlist pfile pfile writetofile nrecordsnumber pfile islargefile bcontainsanylargefiles seektobegin writeuint8 bcontainsanylargefiles met_header_i64tags met_header writeuint32 nrecordsnumber theprefs getcommitfiles theprefs getcommitfiles theapp isrunning _commit _fileno m_pstream afxthrowfileexception cfileexception getlasterror getfilename cfileexception cstring strerror _t known_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror theprefs getlogfilesaving adddebuglogline _t cancelled_met_filename theprefs getconfigdir cancelled_met_filename cfile modewrite cfile modecreate cfile typebinary cfile sharedenywrite cstring strerror _t cancelled_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf writeuint8 met_header theprefs isrememberingcancelledfiles writeuint32 nrecordsnumber m_mapcancelledfiles getcount writeuint32 nrecordsnumber m_mapcancelledfiles getstartposition dwdummy cskey m_mapcancelledfiles getnextassoc dwdummy writehash16 m_key writeuint8 theprefs getcommitfiles theprefs getcommitfiles theapp isrunning _commit _fileno m_pstream afxthrowfileexception cfileexception getlasterror getfilename cfileexception cstring strerror _t cancelled_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror void c known file list clear position pos m files map get start position while pos null c known file p file cc key key m files map get next assoc pos key p file delete p file m files map remove all cknownfilelist m_files_map getstartposition cknownfile pfile cckey m_files_map getnextassoc pfile pfile m_files_map removeall void c known file list process if get tick count m nlastsaved min2ms 11 save cknownfilelist gettickcount m_nlastsaved c known file c known file list find known file lpctstr filename uint32 date uint64 size const position pos m files map get start position while pos null c known file cur file cc key key m files map get next assoc pos key cur file if cur file get utc file date date cur file get file size size tcscmp filename cur file get file name return cur file return null cknownfile cknownfilelist findknownfile m_files_map getstartposition cknownfile cur_file cckey m_files_map getnextassoc cur_file cur_file getutcfiledate cur_file getfilesize _tcscmp cur_file getfilename cur_file c known file c known file list find known file byid const uchar hash const if hash c known file found file cc key key hash if m files map lookup key found file return found file return null cknownfile cknownfilelist findknownfilebyid cknownfile found_file cckey m_files_map found_file found_file c known file c known file list find known file by path const c string s file path const position pos m files map get start position while pos null c known file cur file cc key key m files map get next assoc pos key cur file if cur file get file path compare no case s file path return cur file return null cknownfile cknownfilelist findknownfilebypath cstring sfilepath m_files_map getstartposition cknownfile cur_file cckey m_files_map getnextassoc cur_file cur_file getfilepath comparenocase sfilepath cur_file bool c known file list is known file const c known file file const if file return find known file byid file get file hash null return false cknownfilelist isknownfile cknownfile findknownfilebyid getfilehash bool c known file list is file ptr in list const c known file file const if file position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file if file cur file return true return false cknownfilelist isfileptrinlist cknownfile m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file cur_file void c known file list add cancelled fileid const uchar hash if the prefs is remembering cancelled files m mapcancelledfiles set at cs key hash 1 cknownfilelist addcancelledfileid theprefs isrememberingcancelledfiles m_mapcancelledfiles setat cskey bool c known file list is cancelled file byid const uchar hash const if the prefs is remembering cancelled files int dw dummy if m mapcancelledfiles lookup cs key hash dw dummy return true return false cknownfilelist iscancelledfilebyid theprefs isrememberingcancelledfiles dwdummy m_mapcancelledfiles cskey dwdummy void c known file list copy known file map c map cc key const cc key c known file c known file files map if m files map is empty position pos m files map get start position while pos cc key key c known file cur file m files map get next assoc pos key cur file files map set at key cur file cknownfilelist copyknownfilemap cmap cckey cckey cknownfile cknownfile files_map m_files_map isempty m_files_map getstartposition cckey cknownfile cur_file m_files_map getnextassoc cur_file files_map setat cur_file bool c known file list load known files c string fullpath the prefs get config dir fullpath append known met filename c safe buffered file file c file exception fexp if file open fullpath c file mode read c file os sequential scan c file type binary c file share deny write fexp if fexp m cause c file exception file not found c string str error t failed to load known met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false setvbuf file m pstream null iofbf 16384 c known file p record null try uint8 header file readu int8 if header met header header met header i64tags file close return false add debug log line false t known met file version is u s support 64bit tags header header met header t doesn t t does uint records number file readu int32 for uint i 0 i records number i p record new c known file if p record load from file file trace t failed to load entry u name s hash s size i64u parthashs u expected parthashs u from known met n i p record get file name md4str p record get file hash p record get file size p record get hash count p record geted2k part hash count delete p record p record null continue safe addk file p record p record null file close catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err servermet bad else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err servermet unknown buffer error delete delete p record return false return true cknownfilelist loadknownfiles cstring theprefs getconfigdir known_met_filename csafebufferedfile cfileexception cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite m_cause cfileexception filenotfound cstring strerror _t known_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf cknownfile precord readuint8 met_header met_header_i64tags adddebuglogline _t met_header _t _t recordsnumber readuint32 recordsnumber precord cknownfile precord loadfromfile _t precord getfilename precord getfilehash precord getfilesize precord gethashcount precord geted2kparthashcount precord precord safeaddkfile precord precord cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_servermet_bad max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_servermet_unknown precord bool c known file list load cancelled files if the prefs is remembering cancelled files return true c string fullpath the prefs get config dir fullpath append cancelled met filename c safe buffered file file c file exception fexp if file open fullpath c file mode read c file os sequential scan c file type binary c file share deny write fexp if fexp m cause c file exception file not found c string str error t failed to load cancelled met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false setvbuf file m pstream null iofbf 16384 uchar uc hash 16 try uint8 header file readu int8 if header met header file close return false uint records number file readu int32 for uint i 0 i records number i file read hash16 uc hash uint8 n count file readu int8 for compatibility with future versions which may add more data than just the hash for uint j 0 j n count j c tag tag file false m mapcancelledfiles set at cs key uc hash 1 file close catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err configcorrupt cancelled met filename else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err failedtoload cancelled met filename buffer error delete return false return true cknownfilelist loadcancelledfiles theprefs isrememberingcancelledfiles cstring theprefs getconfigdir cancelled_met_filename csafebufferedfile cfileexception cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite m_cause cfileexception filenotfound cstring strerror _t cancelled_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf uchash readuint8 met_header recordsnumber readuint32 recordsnumber readhash16 uchash ncount readuint8 ncount ctag m_mapcancelledfiles setat cskey uchash cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_configcorrupt cancelled_met_filename max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_failedtoload cancelled_met_filename c friend list c friend list load list m nlastsaved get tick count cfriendlist cfriendlist loadlist m_nlastsaved gettickcount c friend list c friend list save list for position pos m listfriends get head position pos 0 delete m listfriends get next pos cfriendlist cfriendlist savelist m_listfriends getheadposition m_listfriends getnext bool c friend list is already friend uint32 dw last usedip uint32 n last used port const for position pos m listfriends get head position pos 0 const c friend cur friend m listfriends get next pos if cur friend m dwlastusedip dw last usedip cur friend m nlastusedport n last used port return true return false cfriendlist isalreadyfriend dwlastusedip nlastusedport m_listfriends getheadposition cfriend cur_friend m_listfriends getnext cur_friend m_dwlastusedip dwlastusedip cur_friend m_nlastusedport nlastusedport void c friend list save list if the prefs get log file saving add debug log line false t saving friends list file s emfriends met filename m nlastsaved get tick count c string str file name the prefs get config dir emfriends met filename c safe buffered file file c file exception fexp if file open str file name c file mode create c file mode write c file type binary c file share deny write fexp c string str error t failed to save emfriends met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return setvbuf file m pstream null iofbf 16384 try file writeu int8 met header file writeu int32 m listfriends get count for position pos m listfriends get head position pos 0 m listfriends get next pos write to file file if the prefs get commit files 2 the prefs get commit files 1 the app emuledlg is running file flush flush file stream buffers to disk buffers if commit fileno file m pstream 0 commit disk buffers to disk afx throw file exception c file exception hardio get last error file get file name file close catch c file exception error c string str error t failed to save emfriends met filename t file tchar sz error max cfexp errormsg if error get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error error delete cfriendlist savelist theprefs getlogfilesaving adddebuglogline _t emfriends_met_filename m_nlastsaved gettickcount cstring strfilename theprefs getconfigdir emfriends_met_filename csafebufferedfile cfileexception strfilename cfile modecreate cfile modewrite cfile typebinary cfile sharedenywrite cstring strerror _t emfriends_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror m_pstream _iofbf writeuint8 met_header writeuint32 m_listfriends getcount m_listfriends getheadposition m_listfriends getnext writetofile theprefs getcommitfiles theprefs getcommitfiles theapp isrunning _commit _fileno m_pstream afxthrowfileexception cfileexception getlasterror getfilename cfileexception cstring strerror _t emfriends_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror bool c friend list load list c string str file name the prefs get config dir emfriends met filename c safe buffered file file c file exception fexp if file open str file name c file mode read c file os sequential scan c file type binary c file share deny write fexp if fexp m cause c file exception file not found c string str error get res string ids err reademfriends tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false try uint8 header file readu int8 if header met header file close return false uint n records number file readu int32 for uint i 0 i n records number i c friend record new c friend record load from file file m listfriends add tail record file close catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err emfriendsinvalid else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err reademfriends buffer error delete return false return true cfriendlist loadlist cstring strfilename theprefs getconfigdir emfriends_met_filename csafebufferedfile cfileexception strfilename cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenywrite m_cause cfileexception filenotfound cstring strerror getresstring ids_err_reademfriends szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror readuint8 met_header nrecordsnumber readuint32 nrecordsnumber cfriend cfriend loadfromfile m_listfriends addtail cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_emfriendsinvalid max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_reademfriends void c friend list refresh friend c friend torefresh const if m wndoutput m wndoutput refresh friend torefresh cfriendlist refreshfriend cfriend m_wndoutput m_wndoutput refreshfriend c friend c friend list search friend const uchar aby user hash uint32 dwip uint16 n port const position pos m listfriends get head position while pos c friend cur friend m listfriends get next pos to avoid that unwanted clients become a friend we have to distinguish between friends with a userhash and of friends which are identified by ip port only if cur friend m dwhashash check for a friend which has the same userhash as the specified one if md4cmp cur friend m abyuserhash aby user hash return cur friend else if cur friend m dwlastusedip dwip cur friend m nlastusedport n port return cur friend return null cfriend cfriendlist searchfriend abyuserhash nport m_listfriends getheadposition cfriend cur_friend m_listfriends getnext cur_friend m_dwhashash cur_friend m_abyuserhash abyuserhash cur_friend cur_friend m_dwlastusedip cur_friend m_nlastusedport nport cur_friend void c friend list show friends const if m wndoutput assert false return m wndoutput delete all items for position pos m listfriends get head position pos 0 m wndoutput add friend m listfriends get next pos m wndoutput update list cfriendlist showfriends m_wndoutput m_wndoutput deleteallitems m_listfriends getheadposition m_wndoutput addfriend m_listfriends getnext m_wndoutput updatelist bool c friend list add friend c up down client toadd if toadd is friend return false client must have an ip highid or a hash if toadd has lowid toadd has valid hash return false c friend new friend new c friend toadd toadd m friend new friend m listfriends add tail new friend if m wndoutput m wndoutput add friend new friend m wndoutput update list save list return true cfriendlist addfriend cupdownclient isfriend haslowid hasvalidhash cfriend newfriend cfriend m_friend newfriend m_listfriends addtail newfriend m_wndoutput m_wndoutput addfriend newfriend m_wndoutput updatelist savelist bool c friend list add friend const uchar aby userhash uint32 dw last seen uint32 dw last usedip uint16 n last used port uint32 dw last chatted lpctstr psz name uint32 dw has hash client must have an ip highid or a hash todo check if this can be switched to a hybridid so clients with 0 can be added if is lowid dw last usedip dw has hash 0 return false if dw last usedip is already friend dw last usedip n last used port return false c friend record new c friend aby userhash dw last seen dw last usedip n last used port dw last chatted psz name dw has hash m listfriends add tail record show friends save list return true cfriendlist addfriend abyuserhash dwlastseen dwlastusedip nlastusedport dwlastchatted pszname dwhashash islowid dwlastusedip dwhashash dwlastusedip isalreadyfriend dwlastusedip nlastusedport cfriend cfriend abyuserhash dwlastseen dwlastusedip nlastusedport dwlastchatted pszname dwhashash m_listfriends addtail showfriends savelist void c friend list remove friend c friend todel position pos m listfriends find todel if pos assert false return todel set linked client null if m wndoutput m wndoutput remove friend todel m listfriends remove at pos delete todel save list if m wndoutput m wndoutput update list cfriendlist removefriend cfriend m_listfriends setlinkedclient m_wndoutput m_wndoutput removefriend m_listfriends removeat savelist m_wndoutput m_wndoutput updatelist void c friend list remove all friend slots for position pos m listfriends get head position pos 0 c friend cur friend m listfriends get next pos cur friend set friend slot false cfriendlist removeallfriendslots m_listfriends getheadposition cfriend cur_friend m_listfriends getnext cur_friend setfriendslot void c friend list process if get tick count m nlastsaved min2ms 19 save list cfriendlist gettickcount m_nlastsaved savelist caich hash tree caich hash tree uint64 n data size bool b left branch uint64 n base size m ndatasize n data size m nbasesize n base size m bisleftbranch b left branch m plefttree null m prighttree null m bhashvalid false caichhashtree caichhashtree ndatasize bleftbranch nbasesize m_ndatasize ndatasize m_nbasesize nbasesize m_bisleftbranch bleftbranch m_plefttree m_prighttree m_bhashvalid caich hash tree caich hash tree delete m plefttree delete m prighttree caichhashtree caichhashtree m_plefttree m_prighttree void caich hash tree set block hash uint64 n size uint64 n start pos caich hash algo p hash alg assert n size emblocksize caich hash tree p to insert find hash n start pos n size if p to insert null sanity assert false the app queue debug log line dlp veryhigh false t critical error failed to insert sha hash block find hash failed return sanity if p to insert m nbasesize emblocksize p to insert m ndatasize n size assert false the app queue debug log line dlp veryhigh false t critical error logical error on values in set block hash from data return p hash alg finish p to insert m hash p to insert m bhashvalid true debug only the app queue debug log line dlp verylow false t set sha hash for block u u u bytes to s n start pos n start pos n size n size p to insert m hash get string caichhashtree setblockhash nsize nstartpos caichhashalgo phashalg nsize caichhashtree ptoinsert findhash nstartpos nsize ptoinsert theapp queuedebuglogline dlp_veryhigh _t hashblock findhash ptoinsert m_nbasesize ptoinsert m_ndatasize nsize theapp queuedebuglogline dlp_veryhigh _t setblockhashfromdata phashalg ptoinsert m_hash ptoinsert m_bhashvalid debug_only theapp queuedebuglogline dlp_verylow _t shahash nstartpos nstartpos nsize nsize ptoinsert m_hash getstring fails if no hash is found for any branch bool caich hash tree re calculate hash caich hash algo hashalg bool b dont replace assert m plefttree null m prighttree null if m plefttree m prighttree if m plefttree re calculate hash hashalg b dont replace m prighttree re calculate hash hashalg b dont replace return false if b dont replace m bhashvalid return true if m prighttree m bhashvalid m plefttree m bhashvalid hashalg reset hashalg add m plefttree m hash get raw hash hashsize hashalg add m prighttree m hash get raw hash hashsize hashalg finish m hash m bhashvalid true return true else return m bhashvalid else return true caichhashtree recalculatehash caichhashalgo bdontreplace m_plefttree m_prighttree m_plefttree m_prighttree m_plefttree recalculatehash bdontreplace m_prighttree recalculatehash bdontreplace bdontreplace m_bhashvalid m_prighttree m_bhashvalid m_plefttree m_bhashvalid m_plefttree m_hash getrawhash m_prighttree m_hash getrawhash m_hash m_bhashvalid m_bhashvalid bool caich hash tree verify hash tree caich hash algo hashalg bool b delete bad trees if m bhashvalid assert false if b delete bad trees delete m plefttree m plefttree null delete m prighttree m prighttree null the app queue debug log line dlp high false t verify hash tree no masterhash available return false calculated missing hashs without overwriting anything if m plefttree m plefttree m bhashvalid m plefttree re calculate hash hashalg true if m prighttree m prighttree m bhashvalid m prighttree re calculate hash hashalg true if m prighttree m prighttree m bhashvalid m plefttree m plefttree m bhashvalid one branch can never be verified if b delete bad trees delete m plefttree m plefttree null delete m prighttree m prighttree null the app queue debug log line dlp high false t verify hash set failed hashtree incomplete return false if m prighttree m prighttree m bhashvalid m plefttree m plefttree m bhashvalid check verify the hashs of both child nodes against my hash caich hash cmp hash hashalg reset hashalg add m plefttree m hash get raw hash hashsize hashalg add m prighttree m hash get raw hash hashsize hashalg finish cmp hash if m hash cmp hash if b delete bad trees delete m plefttree m plefttree null delete m prighttree m prighttree null return false return m plefttree verify hash tree hashalg b delete bad trees m prighttree verify hash tree hashalg b delete bad trees else last hash in branch nothing below to verify return true caichhashtree verifyhashtree caichhashalgo bdeletebadtrees m_bhashvalid bdeletebadtrees m_plefttree m_plefttree m_prighttree m_prighttree theapp queuedebuglogline dlp_high _t verifyhashtree m_plefttree m_plefttree m_bhashvalid m_plefttree recalculatehash m_prighttree m_prighttree m_bhashvalid m_prighttree recalculatehash m_prighttree m_prighttree m_bhashvalid m_plefttree m_plefttree m_bhashvalid bdeletebadtrees m_plefttree m_plefttree m_prighttree m_prighttree theapp queuedebuglogline dlp_high _t verifyhashset m_prighttree m_prighttree m_bhashvalid m_plefttree m_plefttree m_bhashvalid caichhash cmphash m_plefttree m_hash getrawhash m_prighttree m_hash getrawhash cmphash m_hash cmphash bdeletebadtrees m_plefttree m_plefttree m_prighttree m_prighttree m_plefttree verifyhashtree bdeletebadtrees m_prighttree verifyhashtree bdeletebadtrees recursive caich hash tree caich hash tree find hash uint64 n start pos uint64 n size uint8 n level n level if n level 22 sanity assert false return false if n start pos n size m ndatasize sanity assert false return null if n size m ndatasize sanity assert false return null if n start pos 0 n size m ndatasize this is the searched hash return this else if m ndatasize m nbasesize sanity this is already the last level cant go deeper assert false return null else uint64 n blocks m ndatasize m nbasesize m ndatasize m nbasesize 0 1 0 uint64 n left m bisleftbranch n blocks 1 n blocks 2 m nbasesize uint64 n right m ndatasize n left if n start pos n left if n start pos n size n left sanity assert false return null if m plefttree null m plefttree new caich hash tree n left true n left partsize emblocksize partsize else assert m plefttree m ndatasize n left return m plefttree find hash n start pos n size n level else n start pos n left if n start pos n size n right sanity assert false return null if m prighttree null m prighttree new caich hash tree n right false n right partsize emblocksize partsize else assert m prighttree m ndatasize n right return m prighttree find hash n start pos n size n level caichhashtree caichhashtree findhash nstartpos nsize nlevel nlevel nlevel nstartpos nsize m_ndatasize nsize m_ndatasize nstartpos nsize m_ndatasize m_ndatasize m_nbasesize nblocks m_ndatasize m_nbasesize m_ndatasize m_nbasesize nleft m_bisleftbranch nblocks nblocks m_nbasesize nright m_ndatasize nleft nstartpos nleft nstartpos nsize nleft m_plefttree m_plefttree caichhashtree nleft nleft m_plefttree m_ndatasize nleft m_plefttree findhash nstartpos nsize nlevel nstartpos nleft nstartpos nsize nright m_prighttree m_prighttree caichhashtree nright nright m_prighttree m_ndatasize nright m_prighttree findhash nstartpos nsize nlevel bool caich hash tree create part recovery data uint64 n start pos uint64 n size c file dataio file data out uint32 w hash ident bool b32 bit ident if n start pos n size m ndatasize sanity assert false return false if n size m ndatasize sanity assert false return false if n start pos 0 n size m ndatasize this is the searched part now write all blocks of this part hashident for this level will be adjsuted by write lowest level hash return write lowest level hashs file data out w hash ident false b32 bit ident else if m ndatasize m nbasesize sanity this is already the last level cant go deeper assert false return false else w hash ident 1 w hash ident m bisleftbranch 1 0 uint64 n blocks m ndatasize m nbasesize m ndatasize m nbasesize 0 1 0 uint64 n left m bisleftbranch n blocks 1 n blocks 2 m nbasesize uint64 n right m ndatasize n left if m plefttree null m prighttree null assert false return false if n start pos n left if n start pos n size n left m prighttree m bhashvalid sanity assert false return false m prighttree write hash file data out w hash ident b32 bit ident return m plefttree create part recovery data n start pos n size file data out w hash ident b32 bit ident else n start pos n left if n start pos n size n right m plefttree m bhashvalid sanity assert false return false m plefttree write hash file data out w hash ident b32 bit ident return m prighttree create part recovery data n start pos n size file data out w hash ident b32 bit ident caichhashtree createpartrecoverydata nstartpos nsize cfiledataio filedataout whashident b32bitident nstartpos nsize m_ndatasize nsize m_ndatasize nstartpos nsize m_ndatasize writelowestlevelhash writelowestlevelhashs filedataout whashident b32bitident m_ndatasize m_nbasesize whashident whashident m_bisleftbranch nblocks m_ndatasize m_nbasesize m_ndatasize m_nbasesize nleft m_bisleftbranch nblocks nblocks m_nbasesize nright m_ndatasize nleft m_plefttree m_prighttree nstartpos nleft nstartpos nsize nleft m_prighttree m_bhashvalid m_prighttree writehash filedataout whashident b32bitident m_plefttree createpartrecoverydata nstartpos nsize filedataout whashident b32bitident nstartpos nleft nstartpos nsize nright m_plefttree m_bhashvalid m_plefttree writehash filedataout whashident b32bitident m_prighttree createpartrecoverydata nstartpos nsize filedataout whashident b32bitident void caich hash tree write hash c file dataio file data out uint32 w hash ident bool b32 bit ident const assert m bhashvalid w hash ident 1 w hash ident m bisleftbranch 1 0 if b32 bit ident assert w hash ident 0xffff file data out writeu int16 uint16 w hash ident else file data out writeu int32 w hash ident m hash write file data out caichhashtree writehash cfiledataio filedataout whashident b32bitident m_bhashvalid whashident whashident m_bisleftbranch b32bitident whashident filedataout writeuint16 whashident filedataout writeuint32 whashident m_hash filedataout write lowest level hashs into file ordered from left to right optional without identifier bool caich hash tree write lowest level hashs c file dataio file data out uint32 w hash ident bool b no ident bool b32 bit ident const w hash ident 1 w hash ident m bisleftbranch 1 0 if m plefttree null m prighttree null if m ndatasize m nbasesize m bhashvalid if b no ident b32 bit ident assert w hash ident 0xffff file data out writeu int16 uint16 w hash ident else if b no ident b32 bit ident file data out writeu int32 w hash ident m hash write file data out the app add debug log line false t s m hash get string w hash ident this return true else assert false return false else if m plefttree null m prighttree null assert false return false else return m plefttree write lowest level hashs file data out w hash ident b no ident b32 bit ident m prighttree write lowest level hashs file data out w hash ident b no ident b32 bit ident caichhashtree writelowestlevelhashs cfiledataio filedataout whashident bnoident b32bitident whashident whashident m_bisleftbranch m_plefttree m_prighttree m_ndatasize m_nbasesize m_bhashvalid bnoident b32bitident whashident filedataout writeuint16 whashident bnoident b32bitident filedataout writeuint32 whashident m_hash filedataout theapp adddebuglogline _t m_hash getstring whashident m_plefttree m_prighttree m_plefttree writelowestlevelhashs filedataout whashident bnoident b32bitident m_prighttree writelowestlevelhashs filedataout whashident bnoident b32bitident recover all low level hashs from given data hashs are assumed to be ordered in left to right no identifier used bool caich hash tree load lowest level hashs c file dataio file input if m ndatasize m nbasesize sanity lowest level read hash m hash read file input the app add debug log line false m hash get string m bhashvalid true return true else uint64 n blocks m ndatasize m nbasesize m ndatasize m nbasesize 0 1 0 uint64 n left m bisleftbranch n blocks 1 n blocks 2 m nbasesize uint64 n right m ndatasize n left if m plefttree null m plefttree new caich hash tree n left true n left partsize emblocksize partsize else assert m plefttree m ndatasize n left if m prighttree null m prighttree new caich hash tree n right false n right partsize emblocksize partsize else assert m prighttree m ndatasize n right return m plefttree load lowest level hashs file input m prighttree load lowest level hashs file input caichhashtree loadlowestlevelhashs cfiledataio fileinput m_ndatasize m_nbasesize m_hash fileinput theapp adddebuglogline m_hash getstring m_bhashvalid nblocks m_ndatasize m_nbasesize m_ndatasize m_nbasesize nleft m_bisleftbranch nblocks nblocks m_nbasesize nright m_ndatasize nleft m_plefttree m_plefttree caichhashtree nleft nleft m_plefttree m_ndatasize nleft m_prighttree m_prighttree caichhashtree nright nright m_prighttree m_ndatasize nright m_plefttree loadlowestlevelhashs fileinput m_prighttree loadlowestlevelhashs fileinput write the hash specified by w hash ident with data from file input bool caich hash tree set hash c file dataio file input uint32 w hash ident sint8 n level bool b allow overwrite if n level 1 first call check how many level we need to go for uint8 i 0 i 32 w hash ident 0x80000000 0 i w hash ident 1 if i 31 the app queue debug log line dlp high false t caich hash tree set hash found invalid hash ident 0 return false else n level 31 i if n level 0 this is the searched hash if m bhashvalid b allow overwrite not allowed to overwrite this hash however move the filepointer by reading a hash caich hash file return true m hash read file input m bhashvalid true return true else if m ndatasize m nbasesize sanity this is already the last level cant go deeper assert false return false else adjust ident to point the path to the next node w hash ident 1 n level uint64 n blocks m ndatasize m nbasesize m ndatasize m nbasesize 0 1 0 uint64 n left m bisleftbranch n blocks 1 n blocks 2 m nbasesize uint64 n right m ndatasize n left if w hash ident 0x80000000 0 if m plefttree null m plefttree new caich hash tree n left true n left partsize emblocksize partsize else assert m plefttree m ndatasize n left return m plefttree set hash file input w hash ident n level else if m prighttree null m prighttree new caich hash tree n right false n right partsize emblocksize partsize else assert m prighttree m ndatasize n right return m prighttree set hash file input w hash ident n level whashident fileinput caichhashtree sethash cfiledataio fileinput whashident nlevel ballowoverwrite nlevel whashident whashident theapp queuedebuglogline dlp_high _t caichhashtree sethash hashident nlevel nlevel m_bhashvalid ballowoverwrite caichhash m_hash fileinput m_bhashvalid m_ndatasize m_nbasesize whashident nlevel nblocks m_ndatasize m_nbasesize m_ndatasize m_nbasesize nleft m_bisleftbranch nblocks nblocks m_nbasesize nright m_ndatasize nleft whashident m_plefttree m_plefttree caichhashtree nleft nleft m_plefttree m_ndatasize nleft m_plefttree sethash fileinput whashident nlevel m_prighttree m_prighttree caichhashtree nright nright m_prighttree m_ndatasize nright m_prighttree sethash fileinput whashident nlevel bool caich hash set create part recovery data uint64 n part start pos c file dataio file data out bool b dbg dont load assert m powner if m powner is part file m estatus aich hashsetcomplete assert false return false if m phashtree m ndatasize emblocksize assert false return false if b dbg dont load if load hash set the app queue debug log line dlp veryhigh false t created recovery data error failed to load hashset file s m powner get file name set status aich error return false bool b result uint8 n level 0 uint32 n part size uint32 min partsize uint64 m powner get file size n part start pos m phashtree find hash n part start pos n part size n level uint16 n hashs to write uint16 n level 1 n part size emblocksize n part size emblocksize 0 1 0 const bool b use32 bit identifier m powner is large file if b use32 bit identifier file data out writeu int16 0 no 16bit hashs to write file data out writeu int16 n hashs to write uint32 n check file pos uint file data out get position if m phashtree create part recovery data n part start pos n part size file data out 0 b use32 bit identifier if n hashs to write hashsize b use32 bit identifier 4 2 file data out get position n check file pos assert false the app queue debug log line dlp veryhigh false t created recovery data has wrong length file s m powner get file name b result false set status aich error else b result true else the app queue debug log line dlp veryhigh false t failed to create recovery data for s m powner get file name b result false set status aich error if b use32 bit identifier file data out writeu int16 0 no 32bit hashs to write if b dbg dont load free hash set return b result caichhashset createpartrecoverydata npartstartpos cfiledataio filedataout bdbgdontload m_powner m_powner ispartfile m_estatus aich_hashsetcomplete m_phashtree m_ndatasize bdbgdontload loadhashset theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename setstatus aich_error bresult nlevel npartsize m_powner getfilesize npartstartpos m_phashtree findhash npartstartpos npartsize nlevel nhashstowrite nlevel npartsize npartsize buse32bitidentifier m_powner islargefile buse32bitidentifier filedataout writeuint16 filedataout writeuint16 nhashstowrite ncheckfilepos filedataout getposition m_phashtree createpartrecoverydata npartstartpos npartsize filedataout buse32bitidentifier nhashstowrite buse32bitidentifier filedataout getposition ncheckfilepos theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename bresult setstatus aich_error bresult theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename bresult setstatus aich_error buse32bitidentifier filedataout writeuint16 bdbgdontload freehashset bresult bool caich hash set read recovery data uint64 n part start pos c safe mem file file data in if todo m powner is part file m estatus aich verified m estatus aich trusted assert false return false v2 aich hash packet count1 uint16 16bit hashs to read identifier uint16 hash hashsize count1 aich hashs count2 uint16 32bit hashs to read identifier uint32 hash hashsize count2 aich hashs at this time we check the recoverydata for the correct ammounts of hashs only all hash are then taken into the tree depending on there hashidentifier except the masterhash uint8 n level 0 uint32 n part size uint32 min partsize uint64 m powner get file size n part start pos m phashtree find hash n part start pos n part size n level uint16 n hashs to read uint16 n level 1 n part size emblocksize n part size emblocksize 0 1 0 read hashs with 16 bit identifier uint16 n hashs available file data in readu int16 if file data in get length file data in get position n hashs to read hashsize 2 n hashs to read n hashs available n hashs available 0 this check is redunant c safememfile would catch such an error too the app queue debug log line dlp veryhigh false t failed to read recovery data for s received datasize amounts of hashs was invalid 1 m powner get file name return false debug only the app queue debug log line dlp veryhigh false t read recovery data for s received packet with u 16bit hash identifiers m powner get file name n hashs available for uint32 i 0 i n hashs available i uint16 w hash ident file data in readu int16 if w hash ident 1 never allow masterhash to be overwritten m phashtree set hash file data in w hash ident 1 false the app queue debug log line dlp veryhigh false t failed to read recovery data for s error when trying to read hash into tree 1 m powner get file name verify hash tree true remove invalid hashs which we have already written return false read hashs with 32bit identifier if n hashs available 0 file data in get length file data in get position 2 n hashs available file data in readu int16 if file data in get length file data in get position n hashs to read hashsize 4 n hashs to read n hashs available n hashs available 0 this check is redunant c safememfile would catch such an error too the app queue debug log line dlp veryhigh false t failed to read recovery data for s received datasize amounts of hashs was invalid 2 m powner get file name return false debug only the app queue debug log line dlp veryhigh false t read recovery data for s received packet with u 32bit hash identifiers m powner get file name n hashs available for uint32 i 0 i n hashs to read i uint32 w hash ident file data in readu int32 if w hash ident 1 never allow masterhash to be overwritten w hash ident 0x400000 m phashtree set hash file data in w hash ident 1 false the app queue debug log line dlp veryhigh false t failed to read recovery data for s error when trying to read hash into tree 2 m powner get file name verify hash tree true remove invalid hashs which we have already written return false if n hashs available 0 the app queue debug log line dlp veryhigh false t failed to read recovery data for s packet didn t contained any hashs m powner get file name return false if verify hash tree true some final check if all hashs we wanted are there for uint32 n part pos 0 n part pos n part size n part pos emblocksize caich hash tree pht to check m phashtree find hash n part start pos n part pos min emblocksize n part size n part pos if pht to check null pht to check m bhashvalid the app queue debug log line dlp veryhigh false t failed to read recovery data for s error while verifying presence of all lowest level hashs m powner get file name return false all done return true else the app queue debug log line dlp veryhigh false t failed to read recovery data for s verifying received hashtree failed m powner get file name return false caichhashset readrecoverydata npartstartpos csafememfile filedatain m_powner ispartfile m_estatus aich_verified m_estatus aich_trusted nlevel npartsize m_powner getfilesize npartstartpos m_phashtree findhash npartstartpos npartsize nlevel nhashstoread nlevel npartsize npartsize nhashsavailable filedatain readuint16 filedatain getlength filedatain getposition nhashstoread nhashstoread nhashsavailable nhashsavailable csafememfile theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename debug_only theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename nhashsavailable nhashsavailable whashident filedatain readuint16 whashident m_phashtree sethash filedatain whashident theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename verifyhashtree nhashsavailable filedatain getlength filedatain getposition nhashsavailable filedatain readuint16 filedatain getlength filedatain getposition nhashstoread nhashstoread nhashsavailable nhashsavailable csafememfile theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename debug_only theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename nhashsavailable nhashstoread whashident filedatain readuint32 whashident whashident m_phashtree sethash filedatain whashident theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename verifyhashtree nhashsavailable theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename verifyhashtree npartpos npartpos npartsize npartpos caichhashtree phttocheck m_phashtree findhash npartstartpos npartpos npartsize npartpos phttocheck phttocheck m_bhashvalid theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename theapp queuedebuglogline dlp_veryhigh _t recoverydata m_powner getfilename bool caich hash set re calculate hash bool b dont replace caich hash algo hashalg get new hash algo bool b result m phashtree re calculate hash hashalg b dont replace delete hashalg return b result caichhashset recalculatehash bdontreplace caichhashalgo getnewhashalgo bresult m_phashtree recalculatehash bdontreplace bresult bool caich hash set verify hash tree bool b delete bad trees caich hash algo hashalg get new hash algo bool b result m phashtree verify hash tree hashalg b delete bad trees delete hashalg return b result caichhashset verifyhashtree bdeletebadtrees caichhashalgo getnewhashalgo bresult m_phashtree verifyhashtree bdeletebadtrees bresult void caich hash set untrusted hash received const caich hash hash uint32 dw fromip switch get status case aich empty case aich untrusted case aich trusted break default return bool b found false bool b added false for int i 0 i m auntrustedhashs get count i if m auntrustedhashs i m hash hash b added m auntrustedhashs i add signingip dw fromip b found true break if b found b added true caich untrusted hash uh to add uh to add m hash hash uh to add add signingip dw fromip m auntrustedhashs add uh to add uint32 n signingi ps total 0 unique clients who send us a hash int n most trusted pos 1 the hash which most clients send us uint32 n most trustedi ps 0 for uint32 i 0 i uint32 m auntrustedhashs get count i n signingi ps total m auntrustedhashs i m adwipssigning get count if uint32 m auntrustedhashs i m adwipssigning get count n most trustedi ps n most trustedi ps m auntrustedhashs i m adwipssigning get count n most trusted pos i if n most trusted pos 1 n signingi ps total 0 assert false return the check if we trust any hash if the prefs is trusting every hash n most trustedi ps minuniqueips totrust 100 n most trustedi ps n signingi ps total minpercentage totrust trusted the app queue debug log line false t aich hash received s sadded we have now u hash from u unique i ps we trust the hash s from u clients u added ip s file s hash get string b added t t not m auntrustedhashs get count n signingi ps total m auntrustedhashs n most trusted pos m hash get string n most trustedi ps 100 n most trustedi ps n signingi ps total ipstr dw fromip 0x00f0ffff m powner get file name set status aich trusted if has valid master hash get master hash m auntrustedhashs n most trusted pos m hash set master hash m auntrustedhashs n most trusted pos m hash aich trusted free hash set else untrusted the app queue debug log line false t aich hash received s sadded we have now u hash from u unique i ps best hash s is from u clients u but we dont trust it yet added ip s file s hash get string b added t t not m auntrustedhashs get count n signingi ps total m auntrustedhashs n most trusted pos m hash get string n most trustedi ps 100 n most trustedi ps n signingi ps total ipstr dw fromip 0x00f0ffff m powner get file name set status aich untrusted if has valid master hash get master hash m auntrustedhashs n most trusted pos m hash set master hash m auntrustedhashs n most trusted pos m hash aich untrusted free hash set caichhashset untrustedhashreceived caichhash dwfromip getstatus aich_empty aich_untrusted aich_trusted bfound badded m_auntrustedhashs getcount m_auntrustedhashs m_hash badded m_auntrustedhashs addsigningip dwfromip bfound bfound badded caichuntrustedhash uhtoadd uhtoadd m_hash uhtoadd addsigningip dwfromip m_auntrustedhashs uhtoadd nsigningipstotal nmosttrustedpos nmosttrustedips m_auntrustedhashs getcount nsigningipstotal m_auntrustedhashs m_adwipssigning getcount m_auntrustedhashs m_adwipssigning getcount nmosttrustedips nmosttrustedips m_auntrustedhashs m_adwipssigning getcount nmosttrustedpos nmosttrustedpos nsigningipstotal theprefs istrustingeveryhash nmosttrustedips minuniqueips_totrust nmosttrustedips nsigningipstotal minpercentage_totrust theapp queuedebuglogline _t ips getstring badded _t _t m_auntrustedhashs getcount nsigningipstotal m_auntrustedhashs nmosttrustedpos m_hash getstring nmosttrustedips nmosttrustedips nsigningipstotal dwfromip m_powner getfilename setstatus aich_trusted hasvalidmasterhash getmasterhash m_auntrustedhashs nmosttrustedpos m_hash setmasterhash m_auntrustedhashs nmosttrustedpos m_hash aich_trusted freehashset theapp queuedebuglogline _t ips getstring badded _t _t m_auntrustedhashs getcount nsigningipstotal m_auntrustedhashs nmosttrustedpos m_hash getstring nmosttrustedips nmosttrustedips nsigningipstotal dwfromip m_powner getfilename setstatus aich_untrusted hasvalidmasterhash getmasterhash m_auntrustedhashs nmosttrustedpos m_hash setmasterhash m_auntrustedhashs nmosttrustedpos m_hash aich_untrusted freehashset bool caich hash set is part data available uint64 n part start pos if m estatus aich verified m estatus aich trusted m estatus aich hashsetcomplete assert false return false uint32 n part size uint32 min partsize uint64 m powner get file size n part start pos for uint64 n part pos 0 n part pos n part size n part pos emblocksize caich hash tree pht to check m phashtree find hash n part start pos n part pos min emblocksize n part size n part pos if pht to check null pht to check m bhashvalid return false return true caichhashset ispartdataavailable npartstartpos m_estatus aich_verified m_estatus aich_trusted m_estatus aich_hashsetcomplete npartsize m_powner getfilesize npartstartpos npartpos npartpos npartsize npartpos caichhashtree phttocheck m_phashtree findhash npartstartpos npartpos npartsize npartpos phttocheck phttocheck m_bhashvalid delete the hashset except the masterhash we dont keep aich hashsets in memory to save ressources void caich hash set free hash set delete m phashtree m plefttree m phashtree m plefttree null delete m phashtree m prighttree m phashtree m prighttree null caichhashset freehashset m_phashtree m_plefttree m_phashtree m_plefttree m_phashtree m_prighttree m_phashtree m_prighttree void caich hash set set file size em file size n size m phashtree m ndatasize n size m phashtree m nbasesize n size uint64 partsize emblocksize partsize caichhashset setfilesize emfilesize nsize m_phashtree m_ndatasize nsize m_phashtree m_nbasesize nsize void caich hash set set master hash const caich hash hash eaich status e new status m phashtree m hash hash m phashtree m bhashvalid true set status e new status caichhashset setmasterhash caichhash eaichstatus enewstatus m_phashtree m_hash m_phashtree m_bhashvalid setstatus enewstatus will delete the hashset after saving to free the memory bool caich hash set save hash set if m estatus aich hashsetcomplete assert false return false if m phashtree m bhashvalid m phashtree m ndatasize m powner get file size assert false return false c single lock lock known2 met m mutknown2file false if lock known2 met lock 5000 return false c string fullpath the prefs get config dir fullpath append known2 met filename c safe file file c file exception fexp if file open fullpath c file mode create c file mode read write c file mode no truncate c file os sequential scan c file type binary c file share deny none fexp if fexp m cause c file exception file not found c string str error t failed to load known2 met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error the app queue log line true t s str error return false try setvbuf file m pstream null iofbf 16384 uint8 header file readu int8 if header known2 met version afx throw file exception c file exception end of file 0 file get file name first we check if the hashset we want to write is already stored caich hash current hash uint32 n existing size uint file get length uint32 n hash count while file get position n existing size current hash read file if m phashtree m hash current hash this hashset if already available no need to save it again return true n hash count file readu int32 if file get position n hash count hashsize n existing size afx throw file exception c file exception end of file 0 file get file name skip the rest of this hashset file seek n hash count hashsize c file current write hashset m phashtree m hash write file n hash count uint32 partsize emblocksize partsize emblocksize 0 1 0 m phashtree m ndatasize partsize if m phashtree m ndatasize partsize 0 n hash count uint32 m phashtree m ndatasize partsize emblocksize m phashtree m ndatasize partsize emblocksize 0 1 0 file writeu int32 n hash count if m phashtree write lowest level hashs file 0 true true thats bad really file set length n existing size the app queue debug log line true t failed to save hash set write lowest level hashs failed return false if file get length n existing size n hash count 1 hashsize 4 thats even worse file set length n existing size the app queue debug log line true t failed to save hash set calculated and real size of hashset differ return false the app queue debug log line false t sucessfully saved e muleac hashset u hashs 1 masterhash written n hash count file flush file close catch c file exception error if error m cause c file exception end of file the app queue log line true get res string ids err met bad known2 met filename else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer the app queue log line true get res string ids err servermet unknown buffer error delete return false free hash set return true caichhashset savehashset m_estatus aich_hashsetcomplete m_phashtree m_bhashvalid m_phashtree m_ndatasize m_powner getfilesize csinglelock lockknown2met m_mutknown2file lockknown2met cstring theprefs getconfigdir known2_met_filename csafefile cfileexception cfile modecreate cfile modereadwrite cfile modenotruncate cfile ossequentialscan cfile typebinary cfile sharedenynone m_cause cfileexception filenotfound cstring strerror _t known2_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror theapp queuelogline _t strerror m_pstream _iofbf readuint8 known2_met_version afxthrowfileexception cfileexception endoffile getfilename caichhash currenthash nexistingsize getlength nhashcount getposition nexistingsize currenthash m_phashtree m_hash currenthash nhashcount readuint32 getposition nhashcount nexistingsize afxthrowfileexception cfileexception endoffile getfilename nhashcount cfile m_phashtree m_hash nhashcount m_phashtree m_ndatasize m_phashtree m_ndatasize nhashcount m_phashtree m_ndatasize m_phashtree m_ndatasize writeuint32 nhashcount m_phashtree writelowestlevelhashs setlength nexistingsize theapp queuedebuglogline _t hashset writelowestlevelhashs getlength nexistingsize nhashcount setlength nexistingsize theapp queuedebuglogline _t hashset theapp queuedebuglogline _t emuleac nhashcount cfileexception m_cause cfileexception endoffile theapp queuelogline getresstring ids_err_met_bad known2_met_filename max_cfexp_errormsg geterrormessage theapp queuelogline getresstring ids_err_servermet_unknown freehashset bool caich hash set load hash set if m estatus aich hashsetcomplete assert false return false if m phashtree m bhashvalid m phashtree m ndatasize m powner get file size m phashtree m ndatasize 0 assert false return false c string fullpath the prefs get config dir fullpath append known2 met filename c safe file file c file exception fexp if file open fullpath c file mode create c file mode read c file mode no truncate c file os sequential scan c file type binary c file share deny none fexp if fexp m cause c file exception file not found c string str error t failed to load known2 met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error the app queue log line true t s str error return false try setvbuf file m pstream null iofbf 16384 uint8 header file readu int8 if header known2 met version afx throw file exception c file exception end of file 0 file get file name caich hash current hash uint32 n existing size uint file get length uint32 n hash count while file get position n existing size current hash read file if m phashtree m hash current hash found hashset uint32 n expected count uint32 partsize emblocksize partsize emblocksize 0 1 0 m phashtree m ndatasize partsize if m phashtree m ndatasize partsize 0 n expected count uint32 m phashtree m ndatasize partsize emblocksize m phashtree m ndatasize partsize emblocksize 0 1 0 n hash count file readu int32 if n hash count n expected count the app queue debug log line true t failed to load hash set available hashs and expected hashcount differ return false uint32 dbg pos file get position if m phashtree load lowest level hashs file the app queue debug log line true t failed to load hash set load lowest level hashs failed return false uint32 dbg hash read file get position dbg pos hashsize if re calculate hash false the app queue debug log line true t failed to load hash set calculating loaded hashs failed return false if current hash m phashtree m hash the app queue debug log line true t failed to load hash set calculated masterhash differs from given masterhash hashset corrupt return false return true n hash count file readu int32 if file get position n hash count hashsize n existing size afx throw file exception c file exception end of file 0 file get file name skip the rest of this hashset file seek n hash count hashsize c file current the app queue debug log line true t failed to load hash set hash set not found catch c file exception error if error m cause c file exception end of file the app queue log line true get res string ids err met bad known2 met filename else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer the app queue log line true get res string ids err servermet unknown buffer error delete return false caichhashset loadhashset m_estatus aich_hashsetcomplete m_phashtree m_bhashvalid m_phashtree m_ndatasize m_powner getfilesize m_phashtree m_ndatasize cstring theprefs getconfigdir known2_met_filename csafefile cfileexception cfile modecreate cfile moderead cfile modenotruncate cfile ossequentialscan cfile typebinary cfile sharedenynone m_cause cfileexception filenotfound cstring strerror _t known2_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror theapp queuelogline _t strerror m_pstream _iofbf readuint8 known2_met_version afxthrowfileexception cfileexception endoffile getfilename caichhash currenthash nexistingsize getlength nhashcount getposition nexistingsize currenthash m_phashtree m_hash currenthash nexpectedcount m_phashtree m_ndatasize m_phashtree m_ndatasize nexpectedcount m_phashtree m_ndatasize m_phashtree m_ndatasize nhashcount readuint32 nhashcount nexpectedcount theapp queuedebuglogline _t hashset dbgpos getposition m_phashtree loadlowestlevelhashs theapp queuedebuglogline _t hashset loadlowestlevelhashs dbghashread getposition dbgpos recalculatehash theapp queuedebuglogline _t hashset currenthash m_phashtree m_hash theapp queuedebuglogline _t hashset nhashcount readuint32 getposition nhashcount nexistingsize afxthrowfileexception cfileexception endoffile getfilename nhashcount cfile theapp queuedebuglogline _t hashset hashset cfileexception m_cause cfileexception endoffile theapp queuelogline getresstring ids_err_met_bad known2_met_filename max_cfexp_errormsg geterrormessage theapp queuelogline getresstring ids_err_servermet_unknown caich hash algo caich hash set get new hash algo return new csha caichhashalgo caichhashset getnewhashalgo void caich hash set clientaich request failed c up down client p client p client set req fileaich hash null caich requested data data getaich req details p client remove clientaich request p client if data m pclient p client return if the app downloadqueue is part file data m ppartfile the app queue debug log line false t aich request failed trying to ask another client file s part u client s data m ppartfile get file name data m npart p client dbg get client info data m ppartfile requestaich recovery data m npart caichhashset clientaichrequestfailed cupdownclient pclient pclient setreqfileaichhash caichrequesteddata getaichreqdetails pclient removeclientaichrequest pclient m_pclient pclient theapp ispartfile m_ppartfile theapp queuedebuglogline _t m_ppartfile getfilename m_npart pclient dbggetclientinfo m_ppartfile requestaichrecovery m_npart void caich hash set remove clientaich request const c up down client p client for position pos m lirequesteddata get head position pos 0 m lirequesteddata get next pos if m lirequesteddata get at pos m pclient p client m lirequesteddata remove at pos return assert false caichhashset removeclientaichrequest cupdownclient pclient m_lirequesteddata getheadposition m_lirequesteddata getnext m_lirequesteddata getat m_pclient pclient m_lirequesteddata removeat bool caich hash set is client request pending const c part file p for file uint16 n part for position pos m lirequesteddata get head position pos 0 m lirequesteddata get next pos if m lirequesteddata get at pos m ppartfile p for file m lirequesteddata get at pos m npart n part return true return false caichhashset isclientrequestpending cpartfile pforfile npart m_lirequesteddata getheadposition m_lirequesteddata getnext m_lirequesteddata getat m_ppartfile pforfile m_lirequesteddata getat m_npart npart caich requested data caich hash set getaich req details const c up down client p client for position pos m lirequesteddata get head position pos 0 m lirequesteddata get next pos if m lirequesteddata get at pos m pclient p client return m lirequesteddata get at pos assert false caich requested data empty return empty caichrequesteddata caichhashset getaichreqdetails cupdownclient pclient m_lirequesteddata getheadposition m_lirequesteddata getnext m_lirequesteddata getat m_pclient pclient m_lirequesteddata getat caichrequesteddata void caich hash set dbg test ifdef debug define testsize 4294567295 uint8 max level 0 uint32 c hash 1 uint8 cur level 0 uint32 c parts 0 max level 0 caich hash tree p test new caich hash tree testsize true 9728000 for uint64 i 0 i 9728000 testsize i 9728000 caich hash tree p test2 new caich hash tree 9728000 true emblocksize p test replace hash tree i 9728000 p test2 c parts caich hash tree p test2 new caich hash tree testsize i true emblocksize p test replace hash tree i testsize i p test2 c parts define testsize m phashtree m ndatasize if m phashtree m ndatasize emblocksize return caich hash set test hash set m powner test hash set set file size m powner get file size test hash set set master hash get master hash aich verified c safe mem file file for uint64 i 0 i 9728000 testsize i 9728000 verify create part recovery data i file uint32 n random corruption rand rand file get length 4 file seek n random corruption c file begin file write n random corruption 4 file seek to begin verify test hash set read recovery data i file file seek to begin test hash set free hash set for uint32 j 0 j emblocksize 9728000 j emblocksize verify m phashtree find hash i j emblocksize cur level trace t u s r n c hash m phashtree find hash i j emblocksize cur level m hash get string max level max cur level max level cur level 0 c hash verify m phashtree find hash i j 9728000 j cur level trace t u s r n c hash m phashtree find hash i j 9728000 j cur level m hash get string max level max cur level max level cur level 0 c hash verify create part recovery data i file file seek to begin verify test hash set read recovery data i file file seek to begin test hash set free hash set for uint64 j 0 j emblocksize testsize i j emblocksize verify m phashtree find hash i j emblocksize cur level trace t u s r n c hash m phashtree find hash i j emblocksize cur level m hash get string max level max cur level max level cur level 0 c hash verify m phashtree find hash i j testsize i j cur level trace t u s r n c hash m phashtree find hash i j testsize i j cur level m hash get string max level max cur level max level endif caichhashset dbgtest _debug maxlevel chash curlevel cparts maxlevel caichhashtree ptest caichhashtree caichhashtree ptest2 caichhashtree ptest replacehashtree ptest2 cparts caichhashtree ptest2 caichhashtree ptest replacehashtree ptest2 cparts m_phashtree m_ndatasize m_phashtree m_ndatasize caichhashset testhashset m_powner testhashset setfilesize m_powner getfilesize testhashset setmasterhash getmasterhash aich_verified csafememfile createpartrecoverydata nrandomcorruption getlength nrandomcorruption cfile nrandomcorruption seektobegin testhashset readrecoverydata seektobegin testhashset freehashset m_phashtree findhash curlevel _t chash m_phashtree findhash curlevel m_hash getstring maxlevel curlevel maxlevel curlevel chash m_phashtree findhash curlevel _t chash m_phashtree findhash curlevel m_hash getstring maxlevel curlevel maxlevel curlevel chash createpartrecoverydata seektobegin testhashset readrecoverydata seektobegin testhashset freehashset m_phashtree findhash curlevel _t chash m_phashtree findhash curlevel m_hash getstring maxlevel curlevel maxlevel curlevel chash m_phashtree findhash curlevel _t chash m_phashtree findhash curlevel m_hash getstring maxlevel curlevel maxlevel void caich hash read c file dataio file file read m abybuffer hashsize caichhash cfiledataio m_abybuffer void caich hash write c file dataio file const file write m abybuffer hashsize caichhash cfiledataio m_abybuffer caich hash c string caich hash get string const return encode base32 m abybuffer hashsize caichhash cstring caichhash getstring encodebase32 m_abybuffer c deleted client c deleted client const c up down client p client m cbadrequest 0 m dwinserted get tick count portandhash porthash p client get user port p client credits m itemslist add porthash cdeletedclient cdeletedclient cupdownclient pclient m_cbadrequest m_dwinserted gettickcount pclient getuserport pclient m_itemslist caich untrusted hash bool caich untrusted hash add signingip uint32 dwip dwip 0x00f0ffff we use only the 20 most significant bytes for unique i ps for int i 0 i m adwipssigning get count i if m adwipssigning i dwip return false m adwipssigning add dwip return true caichuntrustedhash caichuntrustedhash addsigningip ips m_adwipssigning getcount m_adwipssigning m_adwipssigning ced2k link ced2k link create link from url const tchar uri c string struri uri int i pos 0 c string str tok get next string struri t i pos if str tok t ed2k str tok get next string struri t i pos if str tok t file c string str name get next string struri t i pos if str name is empty c string str size get next string struri t i pos if str size is empty c string str hash get next string struri t i pos if str hash is empty c string array astr ed2k params bool b emule ext false c string str emule ext c string str last tok str tok get next string struri t i pos while str tok is empty str last tok str tok if str tok t if b emule ext break b emule ext true else if b emule ext if str emule ext is empty str emule ext t str emule ext str tok else astr ed2k params add str tok str tok get next string struri t i pos if str last tok t return new ced2k file link str name str size str hash astr ed2k params str emule ext is empty lpctstr null lpctstr str emule ext else if str tok t serverlist c string strurl get next string struri t i pos if strurl is empty get next string struri t i pos t return new ced2k server list link strurl else if str tok t server c string str server get next string struri t i pos if str server is empty c string str port get next string struri t i pos if str port is empty get next string struri t i pos t return new ced2k server link str server str port throw get res string ids err nosllink ced2klink ced2klink createlinkfromurl cstring ipos cstring strtok getnextstring _t ipos strtok _t strtok getnextstring _t ipos strtok _t cstring strname getnextstring _t ipos strname isempty cstring strsize getnextstring _t ipos strsize isempty cstring strhash getnextstring _t ipos strhash isempty cstringarray astred2kparams bemuleext cstring stremuleext cstring strlasttok strtok getnextstring _t ipos strtok isempty strlasttok strtok strtok _t bemuleext bemuleext bemuleext stremuleext isempty stremuleext _t stremuleext strtok astred2kparams strtok strtok getnextstring _t ipos strlasttok _t ced2kfilelink strname strsize strhash astred2kparams stremuleext isempty stremuleext strtok _t cstring getnextstring _t ipos isempty getnextstring _t ipos _t ced2kserverlistlink strtok _t cstring strserver getnextstring _t ipos strserver isempty cstring strport getnextstring _t ipos strport isempty getnextstring _t ipos _t ced2kserverlink strserver strport getresstring ids_err_nosllink ced2k link ced2k link ced2klink ced2klink ced2k server link ced2k server link const tchar ip const tchar port uses conversion m ip inet addr t2ca ip unsigned long ul tcstoul port 0 10 if ul 0xffff throw get res string ids err badport m port static cast uint16 ul m defaultname t server m defaultname ip m defaultname t m defaultname port ced2kserverlink ced2kserverlink uses_conversion m_ip inet_addr _tcstoul getresstring ids_err_badport m_port static_cast m_defaultname _t m_defaultname m_defaultname _t m_defaultname ced2k server link ced2k server link ced2kserverlink ced2kserverlink ced2k link link type ced2k server link get kind const return k server ced2klink linktype ced2kserverlink getkind kserver void ced2k server link get link c string lnk const lnk format t ed2k server s u ipstr m ip uint m port ced2kserverlink getlink cstring _t m_ip m_port ced2k server link ced2k server link get server link return this ced2kserverlink ced2kserverlink getserverlink m size psz size here we have a little problem actually the proper solution would be to decode from utf8 only if the string does contain escape sequences but if user pastes a raw utf8 encoded string for whatever reason we would miss to decode that string on the other side always decoding utf8 can give flaws in case the string is valid for unicode and utf8 at the same time however to avoid the pasting of raw utf8 strings which would lead to a greater mess in the network we always try to decode from utf8 even if the string did not contain escape sequences m name opt utf8 to str url decode psz name m name trim if m name is empty throw get res string ids err notafilelink sources list null m hashset null m baichhashvalid false if tcslen psz hash 32 throw get res string ids err illformedhash if tstoi64 psz size max emule file size throw get res string ids err toolargefile if tstoi64 psz size 0 throw get res string ids err notafilelink if tstoi64 psz size old max emule file size the prefs canfs handle large files throw get res string ids err fscanthandlefile for int idx 0 idx 16 idx m hash idx byte from hex digit psz hash 16 m hash idx byte m hash idx from hex digit psz hash bool b error false for int i 0 b error i astr params get count i const c string str param astr params get at i assert str param is empty c string str tok int i pos str param find t if i pos 1 str tok str param left i pos if str tok t s c string strurl str param mid i pos 1 if strurl is empty tchar sz scheme internet max scheme length tchar sz host name internet max host name length tchar sz url path internet max path length tchar sz user name internet max user name length tchar sz password internet max password length tchar sz extra info internet max url length url components url 0 url dw struct size sizeof url url lpsz scheme sz scheme url dw scheme length arrsize sz scheme url lpsz host name sz host name url dw host name length arrsize sz host name url lpsz user name sz user name url dw user name length arrsize sz user name url lpsz password sz password url dw password length arrsize sz password url lpsz url path sz url path url dw url path length arrsize sz url path url lpsz extra info sz extra info url dw extra info length arrsize sz extra info if internet crack url strurl 0 0 url url dw host name length 0 s unresolved hostname hostname new s unresolved hostname hostname strurl strurl hostname str hostname sz host name m hostnamesourceslist add tail hostname else assert 0 else if str tok t p c string str part hashs str param tokenize t i pos if m hashset null assert 0 b error true break m hashset new c safe mem file 256 m hashset write hash16 m hash m hashset writeu int16 0 int i part hashs 0 int i posph 0 c string str hash str part hashs tokenize t i posph while str hash is empty uchar auc part hash 16 if strmd4 str hash auc part hash b error true break m hashset write hash16 auc part hash i part hashs str hash str part hashs tokenize t i posph if b error break m hashset seek 16 c file begin m hashset writeu int16 uint16 i part hashs m hashset seek 0 c file begin else if str tok t h c string str hash str param mid i pos 1 if str hash is empty if decode base32 str hash m aichhash get raw hash caich hash get hash size uint caich hash get hash size m baichhashvalid true assert m aichhash get string compare no case str hash 0 else assert false else assert false else assert 0 if b error delete m hashset m hashset null if psz sources tchar p new string tcsdup psz sources auto free liberator p new string tchar p ch p new string tchar p end tchar pip tchar p port bool b allow sources tchar date 3 c ole date time expiration date int n year n month n day uint16 n count 0 uint32 dwid uint16 n port uint32 dw serverip 0 uint16 n server port 0 unsigned long ul int n invalid 0 p ch tcsstr p ch t sources if p ch null p ch p ch 7 point to char after sources p end p ch while p end p end make p end point to the terminating null b allow sources true if there s an expiration date if p ch t p end p ch 7 p ch after date 2 0 terminate the two character string date 0 p ch date 1 p ch n year tcstol date 0 10 2000 date 0 p ch date 1 p ch n month tcstol date 0 10 date 0 p ch date 1 p ch n day tcstol date 0 10 b allow sources expiration date set date n year n month n day 0 if b allow sources b allow sources c ole date time get current time expiration date increment p ch to point to the first ip port and check for sources if b allow sources p ch p end sources list new c safe mem file 256 sources list writeu int16 n count init to 0 we ll fix this at the end for each ip port source string until the end limit to prevent overflow uint16 due to c part file add client sources while p ch 0 n count maxshort pip p ch find the end of this ip port string start of next ip port string if p ch tcschr p ch t null p ch 0 terminate current ip port p ch point to next ip port else p ch p end if port is not present for this ip go to the next ip if p port tcschr pip t null n invalid continue p port 0 terminate ip string p port point p port to port string dwid inet addr c stringa pip ul tcstoul p port 0 10 n port static cast uint16 ul skip bad ips ports if ul 0xffff ul 0 port n invalid continue if dwid inaddr none hostname if tcslen pip 512 n invalid continue s unresolved hostname hostname new s unresolved hostname hostname n port n port hostname str hostname pip m hostnamesourceslist add tail hostname continue todo this will filter out 0 clients is there a nice way to fix if is lowid dwid ip n invalid continue sources list writeu int32 dwid sources list writeu int16 n port sources list writeu int32 dw serverip sources list writeu int16 n server port n count sources list seek to begin sources list writeu int16 n count sources list seek to begin if n count 0 delete sources list sources list null m_size pszsize m_name optutf8tostr urldecode pszname m_name m_name isempty getresstring ids_err_notafilelink sourceslist m_hashset m_baichhashvalid _tcslen pszhash getresstring ids_err_illformedhash _tstoi64 pszsize max_emule_file_size getresstring ids_err_toolargefile _tstoi64 pszsize getresstring ids_err_notafilelink _tstoi64 pszsize old_max_emule_file_size theprefs canfshandlelargefiles getresstring ids_err_fscanthandlefile m_hash fromhexdigit pszhash m_hash m_hash fromhexdigit pszhash berror berror astrparams getcount cstring strparam astrparams getat strparam isempty cstring strtok ipos strparam _t ipos strtok strparam ipos strtok _t cstring strparam ipos isempty szscheme internet_max_scheme_length szhostname internet_max_host_name_length szurlpath internet_max_path_length szusername internet_max_user_name_length szpassword internet_max_password_length szextrainfo internet_max_url_length url_components dwstructsize lpszscheme szscheme dwschemelength szscheme lpszhostname szhostname dwhostnamelength szhostname lpszusername szusername dwusernamelength szusername lpszpassword szpassword dwpasswordlength szpassword lpszurlpath szurlpath dwurlpathlength szurlpath lpszextrainfo szextrainfo dwextrainfolength szextrainfo internetcrackurl dwhostnamelength sunresolvedhostname sunresolvedhostname strhostname szhostname m_hostnamesourceslist addtail strtok _t cstring strparthashs strparam _t ipos m_hashset berror m_hashset csafememfile m_hashset writehash16 m_hash m_hashset writeuint16 iparthashs iposph cstring strhash strparthashs _t iposph strhash isempty aucparthash strhash aucparthash berror m_hashset writehash16 aucparthash iparthashs strhash strparthashs _t iposph berror m_hashset cfile m_hashset writeuint16 iparthashs m_hashset cfile strtok _t cstring strhash strparam ipos strhash isempty decodebase32 strhash m_aichhash getrawhash caichhash gethashsize caichhash gethashsize m_baichhashvalid m_aichhash getstring comparenocase strhash berror m_hashset m_hashset pszsources pnewstring _tcsdup pszsources autofree pnewstring pch pnewstring pend pport ballowsources coledatetime expirationdate nyear nmonth nday ncount nport dwserverip nserverport ninvalid pch _tcsstr pch _t pch pch pch pend pch pend pend pend ballowsources pch _t pend pch pch pch pch nyear _tcstol pch pch nmonth _tcstol pch pch nday _tcstol ballowsources expirationdate setdate nyear nmonth nday ballowsources ballowsources coledatetime getcurrenttime expirationdate pch ballowsources pch pend sourceslist csafememfile sourceslist writeuint16 ncount cpartfile addclientsources pch ncount pch pch _tcschr pch _t pch pch pch pend pport _tcschr _t ninvalid pport pport pport inet_addr cstringa _tcstoul pport nport static_cast ninvalid inaddr_none _tcslen ninvalid sunresolvedhostname sunresolvedhostname nport nport strhostname m_hostnamesourceslist addtail islowid ninvalid sourceslist writeuint32 sourceslist writeuint16 nport sourceslist writeuint32 dwserverip sourceslist writeuint16 nserverport ncount sourceslist seektobegin sourceslist writeuint16 ncount sourceslist seektobegin ncount sourceslist sourceslist ced2k file link ced2k file link delete sources list while m hostnamesourceslist is empty delete m hostnamesourceslist remove head delete m hashset ced2kfilelink ced2kfilelink sourceslist m_hostnamesourceslist isempty m_hostnamesourceslist removehead m_hashset ced2k link link type ced2k file link get kind const return k file ced2klink linktype ced2kfilelink getkind kfile void ced2k file link get link c string lnk const lnk t ed2k file lnk encode url utf8 m name lnk t lnk m size lnk t for int idx 0 idx 16 idx unsigned int ui1 m hash idx 16 unsigned int ui2 m hash idx 16 lnk static cast tchar ui1 9 t 0 ui1 t a ui1 10 lnk static cast tchar ui2 9 t 0 ui2 t a ui2 10 lnk t ced2kfilelink getlink cstring _t encodeurlutf8 m_name _t m_size _t m_hash m_hash static_cast _t _t static_cast _t _t _t ced2k file link ced2k file link get file link return this ced2kfilelink ced2kfilelink getfilelink ced2k server list link ced2k server list link const tchar address m address address ced2kserverlistlink ced2kserverlistlink m_address ced2k server list link ced2k server list link ced2kserverlistlink ced2kserverlistlink ced2k link link type ced2k server list link get kind const return k server list ced2klink linktype ced2kserverlistlink getkind kserverlist void ced2k server list link get link c string lnk const lnk format t ed2k serverlist s m address ced2kserverlistlink getlink cstring _t m_address ced2k server list link ced2k server list link get server list link return this ced2kserverlistlink ced2kserverlistlink getserverlistlink c resizable dialog c kademlia wnd idd p parent m contactlistctrl new c kad contact list ctrl m contacthistogramctrl new c kad contact histogram ctrl search list new c kad search list ctrl m paconbsips null icon kadcont null icon kadsea null cresizabledialog ckademliawnd pparent m_contactlistctrl ckadcontactlistctrl m_contacthistogramctrl ckadcontacthistogramctrl searchlist ckadsearchlistctrl m_paconbsips icon_kadcont icon_kadsea c kademlia wnd c kademlia wnd if m paconbsips m paconbsips unbind m paconbsips release delete m contactlistctrl delete m contacthistogramctrl delete search list if icon kadcont verify destroy icon icon kadcont if icon kadsea verify destroy icon icon kadsea ckademliawnd ckademliawnd m_paconbsips m_paconbsips m_paconbsips m_contactlistctrl m_contacthistogramctrl searchlist icon_kadcont destroyicon icon_kadcont icon_kadsea destroyicon icon_kadsea uint c kademlia wnd get contact count const return m contactlistctrl get item count ckademliawnd getcontactcount m_contactlistctrl getitemcount void c kademlia wnd update kad contact count m contactlistctrl update kad contact count ckademliawnd updatekadcontactcount m_contactlistctrl updatekadcontactcount void c kademlia wnd show contacts m contacthistogramctrl show window sw show m contactlistctrl visable ckademliawnd showcontacts m_contacthistogramctrl showwindow sw_show m_contactlistctrl void c kademlia wnd hide contacts m contacthistogramctrl show window sw hide m contactlistctrl hide ckademliawnd hidecontacts m_contacthistogramctrl showwindow sw_hide m_contactlistctrl bool c kademlia wnd contact add const kademlia c contact contact m contacthistogramctrl contact add contact return m contactlistctrl contact add contact ckademliawnd contactadd ccontact m_contacthistogramctrl contactadd m_contactlistctrl contactadd void c kademlia wnd contact rem const kademlia c contact contact m contacthistogramctrl contact rem contact m contactlistctrl contact rem contact ckademliawnd contactrem ccontact m_contacthistogramctrl contactrem m_contactlistctrl contactrem void c kademlia wnd contact ref const kademlia c contact contact m contactlistctrl contact ref contact ckademliawnd contactref ccontact m_contactlistctrl contactref void c kademlia wnd localize m ctrlbootstrap set window text get res string ids bootstrap get dlg item idc bootstrapbutton set window text get res string ids bootstrap get dlg item idc sstatic4 set window text get res string ids sv address t get dlg item idc sstatic7 set window text get res string ids sv port t get dlg item idc firewallcheckbutton set window text get res string ids kad recheckfw set dlg item text idc kadcontactlab get res string ids kadcontactlab set dlg item text idc kadsearchlab get res string ids kadsearchlab set dlg item text idc radclients get res string ids radclients update controls state m contacthistogramctrl localize m contactlistctrl localize search list localize ckademliawnd m_ctrlbootstrap setwindowtext getresstring ids_bootstrap getdlgitem idc_bootstrapbutton setwindowtext getresstring ids_bootstrap getdlgitem idc_sstatic4 setwindowtext getresstring ids_sv_address _t getdlgitem idc_sstatic7 setwindowtext getresstring ids_sv_port _t getdlgitem idc_firewallcheckbutton setwindowtext getresstring ids_kad_recheckfw setdlgitemtext idc_kadcontactlab getresstring ids_kadcontactlab setdlgitemtext idc_kadsearchlab getresstring ids_kadsearchlab setdlgitemtext idc_radclients getresstring ids_radclients updatecontrolsstate m_contacthistogramctrl m_contactlistctrl searchlist void c kademlia wnd update controls state c string str label if kademlia c kademlia is connected str label get res string ids main btn disconnect else if kademlia c kademlia is running str label get res string ids main btn cancel else str label get res string ids main btn connect str label remove t get dlg item idc kadconnect set window text str label c string str bootstrapip get dlg item text idc bootstrapip str bootstrapip c string str bootstrap port get dlg item text idc bootstrapport str bootstrap port get dlg item idc bootstrapbutton enable window kademlia c kademlia is connected is dlg button checked idc radip 0 str bootstrapip is empty str bootstrapip find t 1 str bootstrap port is empty is dlg button checked idc radclients 0 ckademliawnd updatecontrolsstate cstring strlabel ckademlia isconnected strlabel getresstring ids_main_btn_disconnect ckademlia isrunning strlabel getresstring ids_main_btn_cancel strlabel getresstring ids_main_btn_connect strlabel _t getdlgitem idc_kadconnect setwindowtext strlabel cstring strbootstrapip getdlgitemtext idc_bootstrapip strbootstrapip cstring strbootstrapport getdlgitemtext idc_bootstrapport strbootstrapport getdlgitem idc_bootstrapbutton enablewindow ckademlia isconnected isdlgbuttonchecked idc_radip strbootstrapip isempty strbootstrapip _t strbootstrapport isempty isdlgbuttonchecked idc_radclients bool c kademlia wnd save all settings if m paconbsips m paconbsips save list the prefs get config dir onbootstrap strings profile return true ckademliawnd saveallsettings m_paconbsips m_paconbsips savelist theprefs getconfigdir onbootstrap_strings_profile void c kademlia wnd set all icons frames m ctrlbootstrap set icon t kad bootstrap if icon kadcont verify destroy icon icon kadcont icon kadcont the app load icon t kad contact list 16 16 c static get dlg item idc kadico1 set icon icon kadcont if icon kadsea verify destroy icon icon kadsea icon kadsea the app load icon t kad current searches 16 16 c static get dlg item idc kadico2 set icon icon kadsea ckademliawnd setallicons m_ctrlbootstrap seticon _t kadbootstrap icon_kadcont destroyicon icon_kadcont icon_kadcont theapp loadicon _t kadcontactlist cstatic getdlgitem idc_kadico1 seticon icon_kadcont icon_kadsea destroyicon icon_kadsea icon_kadsea theapp loadicon _t kadcurrentsearches cstatic getdlgitem idc_kadico2 seticon icon_kadsea void c kademlia wnd do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc contactlist m contactlistctrl ddx control pdx idc kad histogram m contacthistogramctrl ddx control pdx idc searchlist search list ddx control pdx idc kadcontactlab kad contact lab ddx control pdx idc kadsearchlab kad search lab ddx control pdx idc bsstatic m ctrlbootstrap ckademliawnd dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_contactlist m_contactlistctrl ddx_control idc_kad_histogram m_contacthistogramctrl ddx_control idc_searchlist searchlist ddx_control idc_kadcontactlab kadcontactlab ddx_control idc_kadsearchlab kadsearchlab ddx_control idc_bsstatic m_ctrlbootstrap bool c kademlia wnd on init dialog c resizable dialog on init dialog init window styles this m contactlistctrl init search list init set all icons localize add anchor idc kadico1 top left add anchor idc contactlist top left c size 100 50 add anchor idc kad histogram top right c size 100 50 add anchor idc kadico2 c size 0 50 add anchor idc searchlist c size 0 50 c size 100 100 add anchor idc kadcontactlab top left add anchor idc firewallcheckbutton top right add anchor idc kadconnect top right add anchor idc kadsearchlab c size 0 50 add anchor idc bsstatic top right add anchor idc bootstrapbutton top right add anchor idc bootstrapport top right add anchor idc bootstrapip top right add anchor idc sstatic4 top right add anchor idc sstatic7 top right add anchor idc radclients top right add anchor idc radip top right search list update kad search count m contactlistctrl update kad contact count if the prefs get use autocompletion m paconbsips new c custom auto complete m paconbsips add ref if m paconbsips bind get dlg item m hwnd idc bootstrapip aco updownkeydropslist aco autosuggest aco filterprefixes m paconbsips load list the prefs get config dir onbootstrap strings profile check dlg button idc radclients 1 return true ckademliawnd oninitdialog cresizabledialog oninitdialog initwindowstyles m_contactlistctrl searchlist setallicons addanchor idc_kadico1 top_left addanchor idc_contactlist top_left csize addanchor idc_kad_histogram top_right csize addanchor idc_kadico2 csize addanchor idc_searchlist csize csize addanchor idc_kadcontactlab top_left addanchor idc_firewallcheckbutton top_right addanchor idc_kadconnect top_right addanchor idc_kadsearchlab csize addanchor idc_bsstatic top_right addanchor idc_bootstrapbutton top_right addanchor idc_bootstrapport top_right addanchor idc_bootstrapip top_right addanchor idc_sstatic4 top_right addanchor idc_sstatic7 top_right addanchor idc_radclients top_right addanchor idc_radip top_right searchlist updatekadsearchcount m_contactlistctrl updatekadcontactcount theprefs getuseautocompletion m_paconbsips ccustomautocomplete m_paconbsips addref m_paconbsips getdlgitem m_hwnd idc_bootstrapip aco_updownkeydropslist aco_autosuggest aco_filterprefixes m_paconbsips loadlist theprefs getconfigdir onbootstrap_strings_profile checkdlgbutton idc_radclients bool c kademlia wnd pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 return false return c resizable dialog pre translate message p msg ckademliawnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control cresizabledialog pretranslatemessage pmsg void c kademlia wnd on bn clicked bootstrapbutton c string strip uint16 n port 0 if is dlg button checked idc radclients get dlg item idc bootstrapip get window text strip strip trim auto handle ip port int i pos if i pos strip find t 1 get dlg item idc bootstrapport set window text strip mid i pos 1 strip strip left i pos get dlg item idc bootstrapip set window text strip c string str port get dlg item idc bootstrapport get window text str port str port trim n port uint16 ttoi str port invalid ip port if strip get length 7 n port 0 return if m paconbsips m paconbsips is bound m paconbsips add item strip t str port 0 if kademlia c kademlia is running kademlia c kademlia start the app emuledlg show connection state if strip is empty n port kademlia c kademlia bootstrap strip n port ckademliawnd onbnclickedbootstrapbutton cstring nport isdlgbuttonchecked idc_radclients getdlgitem idc_bootstrapip getwindowtext ipos ipos _t getdlgitem idc_bootstrapport setwindowtext ipos ipos getdlgitem idc_bootstrapip setwindowtext cstring strport getdlgitem idc_bootstrapport getwindowtext strport strport nport _ttoi strport getlength nport m_paconbsips m_paconbsips isbound m_paconbsips additem _t strport ckademlia isrunning ckademlia theapp showconnectionstate isempty nport ckademlia nport void c kademlia wnd on bn connect if kademlia c kademlia is connected kademlia c kademlia stop else if kademlia c kademlia is running kademlia c kademlia stop else kademlia c kademlia start the app emuledlg show connection state ckademliawnd onbnconnect ckademlia isconnected ckademlia ckademlia isrunning ckademlia ckademlia theapp showconnectionstate void c kademlia wnd on bn clicked firewallcheckbutton kademlia c kademlia recheck firewalled ckademliawnd onbnclickedfirewallcheckbutton ckademlia recheckfirewalled void c kademlia wnd on sys color change c resizable dialog on sys color change set all icons ckademliawnd onsyscolorchange cresizabledialog onsyscolorchange setallicons void c kademlia wnd on en setfocus bootstrapip check radio button idc radip idc radclients idc radip ckademliawnd onensetfocusbootstrapip checkradiobutton idc_radip idc_radclients idc_radip md5 sum md5 sum md5sum md5sum md5 sum md5 sum const c string s source calculate s source md5sum md5sum cstring ssource ssource md5 sum md5 sum const unsigned char pach source uint32 n len calculate pach source n len md5sum md5sum pachsource nlen pachsource nlen c string md5 sum calculate const c string s source return calculate const unsigned char lpctstr s source s source get length sizeof tchar cstring md5sum cstring ssource ssource ssource getlength c string md5 sum calculate const unsigned char pach source uint32 n len md5 ctx context md5 init context md5 update context pach source n len md5 final m rawhash context m shash empty for int i 0 i 16 i c string st st format t 02x m rawhash i m shash st return m shash cstring md5sum pachsource nlen md5_ctx md5init md5update pachsource nlen md5final m_rawhash m_shash cstring _t m_rawhash m_shash m_shash c string md5 sum get hash const return m shash cstring md5sum gethash m_shash c icon static c icon static ciconstatic ciconstatic c icon static c icon static m membmp delete object ciconstatic ciconstatic m_membmp deleteobject void c icon static set icon lpctstr psz iconid m striconid psz iconid if this function is called for the first time and we did not yet call set window text we take take the window label which is already specified for the window the label which comes from the resource c string str text c static get window text str text c static set window text t if str text is empty m strtext is empty m strtext str text c rect r rect get client rect r rect cdc pdc getdc cdc memdc c bitmap p oldbmp verify memdc create compatibledc pdc c font p old font memdc select object get font c rect r caption 0 0 0 0 memdc draw text m strtext r caption dt calcrect assert r caption width 0 assert r caption height 0 if r caption height 16 r caption bottom r caption top 16 r caption right 25 if r rect width 16 r caption width r rect width 16 r caption right r caption left r rect width 16 if m membmp m hobject verify m membmp delete object verify m membmp create compatible bitmap pdc r caption width r caption height p oldbmp memdc select object m membmp memdc fill solid rect r caption get sys color color btnface verify draw state memdc m hdc null null lparam hicon c temp icon loader psz iconid 16 16 null 3 0 16 16 dst icon dss normal clear all alpha channel data bitmap bm mem if m membmp get object sizeof bm mem bm mem sizeof bm mem bm mem bm bits pixel 32 dword dw size m membmp get bitmap bits 0 null if dw size lpbyte p pixels lpbyte malloc dw size if p pixels if m membmp get bitmap bits dw size p pixels dw size lpbyte p line p pixels int i lines bm mem bm height while i lines 0 lpdword pdw pixel lpdword p line for int x 0 x bm mem bm width x pdw pixel 0x00ffffff p line bm mem bm width bytes m membmp set bitmap bits dw size p pixels free p pixels r caption left 22 if g xpstyle is theme active g xpstyle is app themed htheme h theme g xpstyle open theme data null l button uses conversion lpcwstr ole text t2cw m strtext g xpstyle draw theme text h theme memdc m hdc bp groupbox gbs normal ole text ocslen ole text dt wordbreak dt center dt word ellipsis null r caption g xpstyle close theme data h theme else memdc set text color pdc get text color memdc draw text m strtext r caption dt singleline dt left dt end ellipsis releasedc pdc memdc select object p oldbmp memdc select object p old font if m wndpicture m hwnd null m wndpicture create null ws child ws visible ss bitmap c rect 0 0 0 0 this m wndpicture set window pos null r rect left 8 r rect top r caption width 22 r caption height swp showwindow m wndpicture set bitmap m membmp c wnd p parent get parent if p parent null p parent get desktop window c rect r get window rect r r bottom r top 20 get parent screen to client r get parent redraw window r ciconstatic seticon psziconid m_striconid psziconid setwindowtext cstring strtext cstatic getwindowtext strtext cstatic setwindowtext _t strtext isempty m_strtext isempty m_strtext strtext crect rrect getclientrect rrect cbitmap poldbmp createcompatibledc cfont poldfont selectobject getfont crect rcaption drawtext m_strtext rcaption dt_calcrect rcaption rcaption rcaption rcaption rcaption rcaption rrect rcaption rrect rcaption rcaption rrect m_membmp m_hobject m_membmp deleteobject m_membmp createcompatiblebitmap rcaption rcaption poldbmp selectobject m_membmp fillsolidrect rcaption getsyscolor color_btnface drawstate m_hdc ctempiconloader psziconid dst_icon dss_normal bmmem m_membmp getobject bmmem bmmem bmmem bmmem bmbitspixel dwsize m_membmp getbitmapbits dwsize ppixels dwsize ppixels m_membmp getbitmapbits dwsize ppixels dwsize pline ppixels ilines bmmem bmheight ilines pdwpixel pline bmmem bmwidth pdwpixel pline bmmem bmwidthbytes m_membmp setbitmapbits dwsize ppixels ppixels rcaption g_xpstyle isthemeactive g_xpstyle isappthemed htheme g_xpstyle openthemedata uses_conversion oletext m_strtext g_xpstyle drawthemetext htheme m_hdc bp_groupbox gbs_normal oletext oletext dt_wordbreak dt_center dt_word_ellipsis rcaption g_xpstyle closethemedata htheme settextcolor gettextcolor drawtext m_strtext rcaption dt_singleline dt_left dt_end_ellipsis selectobject poldbmp selectobject poldfont m_wndpicture m_hwnd m_wndpicture ws_child ws_visible ss_bitmap crect m_wndpicture setwindowpos rrect rrect rcaption rcaption swp_showwindow m_wndpicture setbitmap m_membmp cwnd pparent getparent pparent pparent getdesktopwindow crect getwindowrect getparent screentoclient getparent redrawwindow void c icon static set window text lpctstr psz text m strtext psz text set icon m striconid ciconstatic setwindowtext psztext m_strtext psztext seticon m_striconid void c icon static on sys color change c static on sys color change if m striconid is empty set icon m striconid ciconstatic onsyscolorchange cstatic onsyscolorchange m_striconid isempty seticon m_striconid c kad search list ctrl c kad search list ctrl set general purpose find true set name t kad search list ctrl ckadsearchlistctrl ckadsearchlistctrl setgeneralpurposefind setname _t kadsearchlistctrl c kad search list ctrl c kad search list ctrl ckadsearchlistctrl ckadsearchlistctrl void c kad search list ctrl search add const kademlia c search search try assert search null int i item insert item lvif text lvif param get item count null 0 0 0 lparam search if i item 0 update search i item search update kad search count catch assert 0 ckadsearchlistctrl searchadd csearch iitem insertitem lvif_text lvif_param getitemcount iitem updatesearch iitem updatekadsearchcount void c kad search list ctrl search rem const kademlia c search search try assert search null lvfindinfo find find flags lvfi param find l param lparam search int i item find item find if i item 1 delete item i item update kad search count catch assert 0 ckadsearchlistctrl searchrem csearch lvfi_param lparam iitem finditem iitem deleteitem iitem updatekadsearchcount void c kad search list ctrl search ref const kademlia c search search try assert search null lvfindinfo find find flags lvfi param find l param lparam search int i item find item find if i item 1 update search i item search catch assert 0 ckadsearchlistctrl searchref csearch lvfi_param lparam iitem finditem iitem updatesearch iitem void c kad search list ctrl init set extended style lvs ex fullrowselect lvs ex infotip insert column col num get res string ids number lvcfmt left 50 insert column col key get res string ids key lvcfmt left 50 insert column col type get res string ids type lvcfmt left 100 insert column col name get res string ids sw name lvcfmt left 100 insert column col stop get res string ids status lvcfmt left 100 insert column col load get res string ids theload lvcfmt left 100 insert column col packets sent get res string ids packsent lvcfmt left 100 insert column col responses get res string ids responses lvcfmt left 100 set all icons localize load settings set sort arrow sort items sort proc makelong get sort item get sort ascending 0 0x0001 ckadsearchlistctrl setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip insertcolumn colnum getresstring ids_number lvcfmt_left insertcolumn colkey getresstring ids_key lvcfmt_left insertcolumn coltype getresstring ids_type lvcfmt_left insertcolumn colname getresstring ids_sw_name lvcfmt_left insertcolumn colstop getresstring ids_status lvcfmt_left insertcolumn colload getresstring ids_theload lvcfmt_left insertcolumn colpacketssent getresstring ids_packsent lvcfmt_left insertcolumn colresponses getresstring ids_responses lvcfmt_left setallicons loadsettings setsortarrow sortitems sortproc getsortitem getsortascending void c kad search list ctrl localize who let this empty masta notices those things and ornis have to do the slavework c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res for int icol 0 icol p header ctrl get item count icol switch icol case col num str res get res string ids number break case col key str res get res string ids key break case col type str res get res string ids type break case col name str res get res string ids sw name break case col stop str res get res string ids status break case col responses str res get res string ids responses break case col load str res get res string ids theload break case col packets sent str res get res string ids packsent break default str res t break hdi psz text const cast lptstr lpctstr str res p header ctrl set item icol hdi int i items get item count for int i 0 i i items i search ref kademlia c search get item data i ckadsearchlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres pheaderctrl getitemcount colnum strres getresstring ids_number colkey strres getresstring ids_key coltype strres getresstring ids_type colname strres getresstring ids_sw_name colstop strres getresstring ids_status colresponses strres getresstring ids_responses colload strres getresstring ids_theload colpacketssent strres getresstring ids_packsent strres _t psztext const_cast strres pheaderctrl setitem iitems getitemcount iitems searchref csearch getitemdata void c kad search list ctrl update kad search count c string id id format t s i get res string ids kadsearchlab get item count the app emuledlg kademliawnd get dlg item idc kadsearchlab set window text id ckadsearchlistctrl updatekadsearchcount cstring _t getresstring ids_kadsearchlab getitemcount theapp getdlgitem idc_kadsearchlab setwindowtext void c kad search list ctrl update search int i item const kademlia c search search c string id id format t i search get searchid set item text i item col num id switch search get search types case kademlia c search file id get res string ids kad searchsrc set item i item 0 lvif image 0 0 0 0 0 0 break case kademlia c search keyword id get res string ids kad searchkw set item i item 0 lvif image 0 1 0 0 0 0 break case kademlia c search node case kademlia c search nodecomplete id get res string ids kad node set item i item 0 lvif image 0 2 0 0 0 0 break case kademlia c search storefile id get res string ids kad storefile set item i item 0 lvif image 0 3 0 0 0 0 break case kademlia c search storekeyword id get res string ids kad storekw set item i item 0 lvif image 0 4 0 0 0 0 break johntodo i also need to understand skinning so the icons are done correctly case kademlia c search findbuddy id get res string ids findbuddy break case kademlia c search storenotes id get res string ids storenotes break case kademlia c search notes id get res string ids notes break default id get res string ids kad unknown set item text i item col type id set item text i item col name search get file name if search get target null search get target to hex string id set item text i item col key id if search stoping set item text i item col stop get res string ids kadstatus stopping else set item text i item col stop get res string ids kadstatus active id format t u u u search get node load search get node load resonse search get node load total set item text i item col load id id format t u search get answers set item text i item col responses id id format t u u search get kad packet sent search get request answer set item text i item col packets sent id ckadsearchlistctrl updatesearch iitem csearch cstring _t getsearchid setitemtext iitem colnum getsearchtypes csearch getresstring ids_kad_searchsrc setitem iitem lvif_image csearch getresstring ids_kad_searchkw setitem iitem lvif_image csearch csearch getresstring ids_kad_node setitem iitem lvif_image csearch getresstring ids_kad_storefile setitem iitem lvif_image csearch getresstring ids_kad_storekw setitem iitem lvif_image csearch getresstring ids_findbuddy csearch getresstring ids_storenotes csearch getresstring ids_notes getresstring ids_kad_unknown setitemtext iitem coltype setitemtext iitem colname getfilename gettarget gettarget tohexstring setitemtext iitem colkey setitemtext iitem colstop getresstring ids_kadstatus_stopping setitemtext iitem colstop getresstring ids_kadstatus_active _t getnodeload getnodeloadresonse getnodeloadtotal setitemtext iitem colload _t getanswers setitemtext iitem colresponses _t getkadpacketsent getrequestanswer setitemtext iitem colpacketssent void c kad search list ctrl set all icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t kad file search iml add c temp icon loader t kad word search iml add c temp icon loader t kad node search iml add c temp icon loader t kad store file iml add c temp icon loader t kad store word assert get style lvs shareimagelists 0 himagelist himl apply image list iml detach if himl imagelist destroy himl ckadsearchlistctrl setallicons cimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t kadfilesearch ctempiconloader _t kadwordsearch ctempiconloader _t kadnodesearch ctempiconloader _t kadstorefile ctempiconloader _t kadstoreword getstyle lvs_shareimagelists applyimagelist imagelist_destroy int c kad search list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort kademlia c search item1 kademlia c search l param1 kademlia c search item2 kademlia c search l param2 if item1 null item2 null return 0 int i result switch loword l param sort case col num i result item1 get searchid item2 get searchid break case col type i result item1 get search types item2 get search types break case col name i result item1 get file name compare no case item2 get file name break case col load i result item1 get node load item2 get node load break case col responses i result item1 get answers item2 get answers break case col packets sent i result item1 get kad packet sent item2 get kad packet sent break default return 0 if hiword l param sort i result i result return i result ckadsearchlistctrl sortproc lparam1 lparam2 lparamsort csearch csearch lparam1 csearch csearch lparam2 iresult lparamsort colnum iresult getsearchid getsearchid coltype iresult getsearchtypes getsearchtypes colname iresult getfilename comparenocase getfilename colload iresult getnodeload getnodeload colresponses iresult getanswers getanswers colpacketssent iresult getkadpacketsent getkadpacketsent lparamsort iresult iresult iresult bool c kad search list ctrl on command wparam w param lparam l param return true ckadsearchlistctrl oncommand wparam lparam void c kad search list ctrl on sys color change c mule list ctrl on sys color change set all icons ckadsearchlistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons void c kad search list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr determine ascending based on whether already sorted on this column int i sort item get sort item bool b old sort ascending get sort ascending bool b sort ascending i sort item pnm list view i sub item true b old sort ascending item is column clicked i sort item pnm list view i sub item sort table update sort history makelong i sort item b sort ascending 0 0x0001 set sort arrow i sort item b sort ascending sort items sort proc makelong i sort item b sort ascending 0 0x0001 p result 0 ckadsearchlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview isortitem getsortitem boldsortascending getsortascending bsortascending isortitem pnmlistview isubitem boldsortascending isortitem pnmlistview isubitem updatesorthistory isortitem bsortascending setsortarrow isortitem bsortascending sortitems sortproc isortitem bsortascending presult c visual stylesxp c visual stylesxp void m hthemedll load library t ux theme dll cvisualstylesxp cvisualstylesxp m_hthemedll loadlibrary _t uxtheme c visual stylesxp c visual stylesxp void if m hthemedll null verify free library m hthemedll m hthemedll null cvisualstylesxp cvisualstylesxp m_hthemedll freelibrary m_hthemedll m_hthemedll void c visual stylesxp set theme app properties dword dw flags static pfnsetthemeappproperties pfn null if pfn null pfn pfnsetthemeappproperties get proc set theme app properties void set theme app properties fail pfn dw flags cvisualstylesxp setthemeappproperties dwflags getproc setthemeappproperties setthemeapppropertiesfail dwflags lpwstr psz size buff int cch max size chars static pfngetcurrentthemename pfn null if pfn null pfn pfngetcurrentthemename get proc get current theme name void get current theme name fail return pfn psz theme file name cch max name chars psz color buff cch max color chars psz size buff cch max size chars pszsizebuff cchmaxsizechars getproc getcurrentthemename getcurrentthemenamefail pszthemefilename cchmaxnamechars pszcolorbuff cchmaxcolorchars pszsizebuff cchmaxsizechars lpwstr psz value buff int cch max val chars static pfngetthemedocumentationproperty pfn null if pfn null pfn pfngetthemedocumentationproperty get proc get theme documentation property void get theme documentation property fail return pfn psz theme name psz property name psz value buff cch max val chars pszvaluebuff cchmaxvalchars getproc getthemedocumentationproperty getthemedocumentationpropertyfail pszthemename pszpropertyname pszvaluebuff cchmaxvalchars hresult c visual stylesxp draw theme parent background hwnd hwnd hdc hdc rect prc static pfndrawthemeparentbackground pfn null if pfn null pfn pfndrawthemeparentbackground get proc draw theme parent background void draw theme parent background fail return pfn hwnd hdc prc cvisualstylesxp drawthemeparentbackground getproc drawthemeparentbackground drawthemeparentbackgroundfail hresult c visual stylesxp enable theming bool f enable static pfnenabletheming pfn null if pfn null pfn pfnenabletheming get proc enable theming void enable theming fail return pfn f enable cvisualstylesxp enabletheming fenable getproc enabletheming enablethemingfail fenable void c visual stylesxp get proc lpcstr sz proc void pfn fail void p ret pfn fail if m hthemedll null p ret get proc address m hthemedll sz proc return p ret cvisualstylesxp getproc szproc pfnfail pret pfnfail m_hthemedll pret getprocaddress m_hthemedll szproc pret c url client c url client m iredirected 0 m clientsoft so url curlclient curlclient m_iredirected m_clientsoft so_url c url client c url client curlclient curlclient bool c url client set url lpctstr psz url uint32 nip uses conversion tchar sz canon url internet max url length dword dw canon url size arrsize sz canon url if internet canonicalize url psz url sz canon url dw canon url size icu no encode return false tchar sz url internet max url length dword dw url size arrsize sz url if internet canonicalize url sz canon url sz url dw url size icu decode icu no encode icu browser mode return false tchar sz scheme internet max scheme length tchar sz host name internet max host name length tchar sz url path internet max path length tchar sz user name internet max user name length tchar sz password internet max password length tchar sz extra info internet max url length url components url 0 url dw struct size sizeof url url lpsz scheme sz scheme url dw scheme length arrsize sz scheme url lpsz host name sz host name url dw host name length arrsize sz host name url lpsz user name sz user name url dw user name length arrsize sz user name url lpsz password sz password url dw password length arrsize sz password url lpsz url path sz url path url dw url path length arrsize sz url path url lpsz extra info sz extra info url dw extra info length arrsize sz extra info if internet crack url sz url 0 0 url return false if url dw scheme length 0 url n scheme internet scheme http we only support http return false if url dw host name length 0 we must know the hostname return false if url dw user name length 0 no support for user password return false if url dw password length 0 no support for user password return false if url dw url path length 0 we must know the url path on that host return false m strhosta sz host name tchar sz encoded url internet max url length dword dw encoded url arrsize sz encoded url if internet canonicalize url sz url sz encoded url dw encoded url icu encode percent return false m strurlpath sz encoded url m nurlstartpos uint64 1 set user name sz url note be very careful with what is stored in the following ip id port members if nip m nconnectip nip else m nconnectip inet addr t2a sz host name if m nconnectip inaddr none m nconnectip 0 m nuseridhybrid htonl m nconnectip assert m nuseridhybrid 0 m nuserport url n port return true curlclient seturl pszurl uses_conversion szcanonurl internet_max_url_length dwcanonurlsize szcanonurl internetcanonicalizeurl pszurl szcanonurl dwcanonurlsize icu_no_encode szurl internet_max_url_length dwurlsize szurl internetcanonicalizeurl szcanonurl szurl dwurlsize icu_decode icu_no_encode icu_browser_mode szscheme internet_max_scheme_length szhostname internet_max_host_name_length szurlpath internet_max_path_length szusername internet_max_user_name_length szpassword internet_max_password_length szextrainfo internet_max_url_length url_components dwstructsize lpszscheme szscheme dwschemelength szscheme lpszhostname szhostname dwhostnamelength szhostname lpszusername szusername dwusernamelength szusername lpszpassword szpassword dwpasswordlength szpassword lpszurlpath szurlpath dwurlpathlength szurlpath lpszextrainfo szextrainfo dwextrainfolength szextrainfo internetcrackurl szurl dwschemelength nscheme internet_scheme_http dwhostnamelength dwusernamelength dwpasswordlength dwurlpathlength m_strhosta szhostname szencodedurl internet_max_url_length dwencodedurl szencodedurl internetcanonicalizeurl szurl szencodedurl dwencodedurl icu_encode_percent m_strurlpath szencodedurl m_nurlstartpos setusername szurl m_nconnectip m_nconnectip inet_addr szhostname m_nconnectip inaddr_none m_nconnectip m_nuseridhybrid m_nconnectip m_nuseridhybrid m_nuserport nport void c url client set request file c part file p req file c up down client set request file p req file if reqfile m npartcount reqfile get part count m abypartstatus new uint8 m npartcount memset m abypartstatus 1 m npartcount m bcompletesource true curlclient setrequestfile cpartfile preqfile cupdownclient setrequestfile preqfile m_npartcount getpartcount m_abypartstatus m_npartcount m_abypartstatus m_npartcount m_bcompletesource bool c url client try to connect bool b ignore max con c runtime class p class socket return c up down client try to connect b ignore max con runtime class c http client down socket curlclient trytoconnect bignoremaxcon cruntimeclass pclasssocket cupdownclient trytoconnect bignoremaxcon runtime_class chttpclientdownsocket bool c url client connect if get connectip 0 get connectip inaddr none return c up down client connect try to always tell the socket to wait for on connect before you call connect socket wait for on connect socket connect m strhosta m nuserport return true curlclient getconnectip getconnectip inaddr_none cupdownclient waitforonconnect waitforonconnect m_strhosta m_nuserport void c url client on socket connected int n error code if n error code 0 send http block requests curlclient onsocketconnected nerrorcode nerrorcode sendhttpblockrequests bool c url client disconnected lpctstr psz reason bool b from socket c http client down socket s static downcast c http client down socket socket trace t hs http state u reason s n function s null 1 s get http state psz reason todo this is a mess if s s get http state http state recv expected s get http state http state recv body m filereasktimes remove key reqfile zz download manager one resk timestamp for each file return c up down client disconnected psz reason b from socket curlclient pszreason bfromsocket chttpclientdownsocket static_downcast chttpclientdownsocket _t httpstate __function__ gethttpstate pszreason gethttpstate httpstaterecvexpected gethttpstate httpstaterecvbody m_filereasktimes removekey downloadmanager cupdownclient pszreason bfromsocket bool c url client send hello packet send http block requests return true curlclient sendhellopacket sendhttpblockrequests void c url client send block requests assert 0 curlclient sendblockrequests bool c url client send http block requests uses conversion m dwlastblockreceived get tick count if reqfile null throw c string t failed to send block requests no reqfile attached create block requests partsize emblocksize if m pendingblocks list is empty set download state ds noneededparts swap to another file t a4af for nnp file url client send http block requests true false false null true true return false position pos m pendingblocks list get head position pending block struct pending m pendingblocks list get next pos m ureqstart pending block start offset m ureqend pending block end offset bool b merge blocks true while pos position pos last pos pending m pendingblocks list get next pos if b merge blocks pending block start offset m ureqend 1 m ureqend pending block end offset else b merge blocks false reqfile remove block from list pending block start offset pending block end offset delete pending block delete pending m pendingblocks list remove at pos last m nurlstartpos m ureqstart c stringa str http request str http request append format get s http 1 0 r n m strurlpath str http request append format accept r n str http request append format range bytes i64u i64u r n m ureqstart m ureqend str http request append format connection keep alive r n str http request append format host s r n m strhosta str http request append format r n if the prefs get debug clienttcp level 0 debug t sending http request n hs str http request c raw packet p http packet new c raw packet str http request the stats add up data overhead file request p http packet size socket send packet p http packet static downcast c http client down socket socket set http state http state recv expected return true curlclient sendhttpblockrequests uses_conversion m_dwlastblockreceived gettickcount cstring _t createblockrequests m_pendingblocks_list isempty setdownloadstate ds_noneededparts swaptoanotherfile _t urlclient sendhttpblockrequests m_pendingblocks_list getheadposition pending_block_struct m_pendingblocks_list getnext m_ureqstart startoffset m_ureqend endoffset bmergeblocks poslast m_pendingblocks_list getnext bmergeblocks startoffset m_ureqend m_ureqend endoffset bmergeblocks removeblockfromlist startoffset endoffset m_pendingblocks_list removeat poslast m_nurlstartpos m_ureqstart cstringa strhttprequest strhttprequest appendformat m_strurlpath strhttprequest appendformat strhttprequest appendformat m_ureqstart m_ureqend strhttprequest appendformat strhttprequest appendformat m_strhosta strhttprequest appendformat theprefs getdebugclienttcplevel _t strhttprequest crawpacket phttppacket crawpacket strhttprequest thestats addupdataoverheadfilerequest phttppacket sendpacket phttppacket static_downcast chttpclientdownsocket sethttpstate httpstaterecvexpected void c url client send file request this may be called in some rare situations depending on socket states just ignore it curlclient sendfilerequest void c url client send cancel transfer packet packet if socket static downcast c http client down socket socket set http state http state unknown socket safe delete curlclient sendcanceltransfer static_downcast chttpclientdownsocket sethttpstate httpstateunknown safe_delete bool c url client process http down response const c stringa array astr headers if reqfile null throw c string t failed to process received http data block no reqfile attached if astr headers get count 0 throw c string t unexpected http response no headers available const c stringa rstr hdr astr headers get at 0 uint u http maj ver u http min ver u http status code if sscanf rstr hdr http u u u u http maj ver u http min ver u http status code 3 c string str error str error format t unexpected http response hs rstr hdr throw str error if u http maj ver 1 u http min ver 0 u http min ver 1 c string str error str error format t unexpected http version hs rstr hdr throw str error bool b expect data u http status code http status ok u http status code http status partial content bool b redirection u http status code http status moved u http status code http status redirect if b expect data b redirection c string str error str error format t unexpected http status code u u http status code throw str error bool b new location false bool b valid content range false for int i 1 i astr headers get count i const c stringa rstr hdr astr headers get at i if b expect data strnicmp rstr hdr content length 15 0 uint64 u content length atoi64 lpcstr rstr hdr 15 if u content length m ureqend m ureqstart 1 if u content length reqfile get file size tolerate this case only c string str error str error format t unexpected http header field hs rstr hdr throw str error trace unexpected http header field s n rstr hdr else if b expect data strnicmp rstr hdr content range 14 0 uint64 ui64 start 0 ui64 end 0 ui64 len 0 if sscanf lpcstr rstr hdr 14 bytes i64u i64u i64u ui64 start ui64 end ui64 len 3 c string str error str error format t unexpected http header field hs rstr hdr throw str error if ui64 start m ureqstart ui64 end m ureqend ui64 len reqfile get file size c string str error str error format t unexpected http header field hs rstr hdr throw str error b valid content range true else if strnicmp rstr hdr server 7 0 if m strclientsoftware is empty m strclientsoftware rstr hdr mid 7 trim else if b redirection strnicmp rstr hdr location 9 0 c string str location rstr hdr mid 9 trim if set url str location c string str error str error format t failed to process http redirection url s str location throw str error b new location true if b new location m iredirected if m iredirected 3 throw c string t max http redirection count exceeded the tricky part socket safe delete mark our parent object for getting deleted if try to connect true replace our parent object with a new one throw c string t failed to connect to redirected url return false tell our old parent object which was marked as to get deleted and which is no longer attached to us to disconnect if b valid content range if the prefs get debug clienttcp level 0 debug http headers astr headers c string str error str error format t unexpected http response no valid http content range found throw str error set download state ds downloading return true curlclient processhttpdownresponse cstringaarray astrheaders cstring _t astrheaders getcount cstring _t cstringa rstrhdr astrheaders getat uhttpmajver uhttpminver uhttpstatuscode rstrhdr uhttpmajver uhttpminver uhttpstatuscode cstring strerror strerror _t rstrhdr strerror uhttpmajver uhttpminver uhttpminver cstring strerror strerror _t rstrhdr strerror bexpectdata uhttpstatuscode http_status_ok uhttpstatuscode http_status_partial_content bredirection uhttpstatuscode http_status_moved uhttpstatuscode http_status_redirect bexpectdata bredirection cstring strerror strerror _t uhttpstatuscode strerror bnewlocation bvalidcontentrange astrheaders getcount cstringa rstrhdr astrheaders getat bexpectdata rstrhdr ucontentlength _atoi64 rstrhdr ucontentlength m_ureqend m_ureqstart ucontentlength getfilesize cstring strerror strerror _t rstrhdr strerror rstrhdr bexpectdata rstrhdr ui64start ui64end ui64len rstrhdr ui64start ui64end ui64len cstring strerror strerror _t rstrhdr strerror ui64start m_ureqstart ui64end m_ureqend ui64len getfilesize cstring strerror strerror _t rstrhdr strerror bvalidcontentrange rstrhdr m_strclientsoftware isempty m_strclientsoftware rstrhdr bredirection rstrhdr cstring strlocation rstrhdr seturl strlocation cstring strerror strerror _t strlocation strerror bnewlocation bnewlocation m_iredirected m_iredirected cstring _t safe_delete trytoconnect cstring _t bvalidcontentrange theprefs getdebugclienttcplevel debughttpheaders astrheaders cstring strerror strerror _t strerror setdownloadstate ds_downloading c upload queue c upload queue verify h timer set timer 0 0 100 upload timer null if the prefs get verbose h timer add debug log line true t failed to create upload queue timer s get error message get last error datarate 0 counter 0 successfullupcount 0 failedupcount 0 totaluploadtime 0 m nlaststartupload 0 statsave 0 khaos iupdateconnstats 0 khaos m dwremovedclientbyscore get tick count m ihighestnumberoffullyactivatedslotssincelastcall 0 m maxactiveclients 0 m maxactiveclientsshorttime 0 m lastcalculateddataratetick 0 m avarage dr sum 0 friend datarate 0 m dwlastresorteduploadslots 0 cuploadqueue cuploadqueue h_timer settimer uploadtimer theprefs getverbose h_timer adddebuglogline _t geterrormessage getlasterror m_nlaststartupload m_dwremovedclientbyscore gettickcount m_ihighestnumberoffullyactivatedslotssincelastcall m_maxactiveclients m_maxactiveclientsshorttime m_lastcalculateddataratetick m_avarage_dr_sum frienddatarate m_dwlastresorteduploadslots c upload queue c upload queue if h timer kill timer 0 h timer cuploadqueue cuploadqueue h_timer killtimer h_timer void c upload queue process dword cur tick get tick count update active clients info cur tick if force new client there s not enough open uploads open another one add up next client t not enough open upload slots for current ul speed the loop that feeds the upload slots with data position pos uploadinglist get head position while pos null get the client note also updates pos as a side effect c up down client cur client uploadinglist get next pos if the prefs m idbgheap 2 assert valid cur client it seems chatting or friend slots can get stuck at times in upload this needs looked into if cur client socket remove from upload queue cur client t uploading to client without socket c upload queue process if cur client disconnected t c upload queue process delete cur client else cur client send block data save used bandwidth for speed calculations uint64 sent bytes the app upload bandwidth throttler get number of sent bytes since last call and reset avarage dr list add tail sent bytes m avarage dr sum sent bytes void the app upload bandwidth throttler get number of sent bytes overhead since last call and reset avarage friend dr list add tail the stats session sent bytes to friend save time beetween each speed snapshot avarage tick list add tail cur tick don t save more than 30 secs of data while avarage tick list get count 3 avarage friend dr list is empty get tick count avarage tick list get head 30 1000 m avarage dr sum avarage dr list remove head avarage friend dr list remove head avarage tick list remove head cuploadqueue curtick gettickcount updateactiveclientsinfo curtick forcenewclient addupnextclient _t getheadposition cupdownclient cur_client getnext theprefs m_idbgheap assert_valid cur_client cur_client removefromuploadqueue cur_client _t cuploadqueue cur_client _t cuploadqueue cur_client cur_client sendblockdata sentbytes theapp uploadbandwidththrottler getnumberofsentbytessincelastcallandreset avarage_dr_list addtail sentbytes m_avarage_dr_sum sentbytes theapp uploadbandwidththrottler getnumberofsentbytesoverheadsincelastcallandreset avarage_friend_dr_list addtail thestats sessionsentbytestofriend avarage_tick_list addtail curtick avarage_tick_list getcount avarage_friend_dr_list isempty gettickcount avarage_tick_list gethead m_avarage_dr_sum avarage_dr_list removehead avarage_friend_dr_list removehead avarage_tick_list removehead void c upload queue add client to queue c up down client client bool b ignore timelimit this is to keep users from abusing the limits we put on lowid callbacks 1 check if we are connected to any network and that we are a lowid although this check shouldn t matter as they wouldn t have found us but maybe i m missing something so it s best to check as a precaution 2 check if the user is connected to kad we do allow all kad callbacks 3 check if the user is in our download list or a friend we give these users a special pass as they are helping us 4 are we connected to a server if we are is the user on the same server tcp lowid callbacks are also allowed 5 if the queue is very short allow anyone in as we want to make sure our upload is always used if the app is connected the app is firewalled client get kad port client get download state ds none client is friend the app serverconnect the app serverconnect is local server client get serverip client get server port get waiting user count 50 return client add asked count client set last up request if b ignore timelimit client add request count client get upload fileid if client is banned return uint16 c sameip 0 check for double position pos1 pos2 for pos1 waitinglist get head position pos2 pos1 null waitinglist get next pos1 c up down client cur client waitinglist get at pos2 if cur client client if client m baddnextconnect accept new client client m baddnextconnect special care is given to lowid clients that missed their upload slot due to the saving bandwidth on callbacks if the prefs get log ul dl events add debug log line true t adding lowid when reconnecting client s client dbg get client info client m baddnextconnect false remove from waiting queue client true add up next client t adding lowid when reconnecting client return client send ranking info the app emuledlg transferwnd queuelistctrl refresh client client return else if client compare cur client the app clientlist add track client client in any case keep track of this client another client with same ip port or hash this happens only in rare cases because same userhash ip ports are assigned to the right client on connecting in most cases if cur client credits null cur client credits get current ident state cur client getip is identified cur client has a valid secure hash don t remove him if the prefs get verbose add debug log line false get res string ids sameuserhash client get user name cur client get user name client get user name return if client credits null client credits get current ident state client getip is identified client has a valid secure hash add him remove other one if the prefs get verbose add debug log line false get res string ids sameuserhash client get user name cur client get user name cur client get user name remove from waiting queue pos2 true if cur client socket if cur client disconnected t add client to queue same userhash 1 delete cur client else remove both since we do not know who the bad one is if the prefs get verbose add debug log line false get res string ids sameuserhash client get user name cur client get user name t both remove from waiting queue pos2 true if cur client socket if cur client disconnected t add client to queue same userhash 2 delete cur client return else if client getip cur client getip same ip different port different userhash c sameip if c sameip 3 do not accept more than 3 clients from the same ip if the prefs get verbose debug only add debug log line false t s s s request to enter the queue was rejected because of too many clients with the same ip client get user name ipstr client get connectip return else if the app clientlist get clients fromip client getip 3 if the prefs get verbose debug only add debug log line false t s s s request to enter the queue was rejected because of too many clients with the same ip found in tracked clients list client get user name ipstr client get connectip return done statistic values c known file reqfile the app sharedfiles get file byid uchar client get upload fileid if reqfile reqfile statistic add request emule collection will bypass the queue if reqfile null c collection has collection extention reqfile get file name reqfile get file size uint64 maxprioritycoll size client is downloading client socket null client socket is connected client set collection upload slot true remove from waiting queue client true add up next client t collection priority slot client return else client set collection upload slot false cap the list the queue limit in prefs is only a soft limit hard limit is 25 higher to let in powershare clients and other high ranking clients after soft limit has been reached uint32 soft queue limit the prefs get queue size uint32 hard queue limit the prefs get queue size max the prefs get queue size 4 200 if soft queue limit has been reached only let in high ranking clients if uint32 waitinglist get count hard queue limit uint32 waitinglist get count soft queue limit soft queue limit is reached client is friend client get friend slot false client is not a friend with friend slot client get combined file prio and credit get average combined file prio and credit and client has lower credits wants lower prio file than average client in queue then block client from getting on queue return if client is downloading he s already downloading and wants probably only another file if the prefs get debug clienttcp level 0 debug send op acceptuploadreq client packet packet new packet op acceptuploadreq 0 the stats add up data overhead file request packet size client socket send packet packet true return if waitinglist is empty force new client true add up next client t direct add with empty queue client else waitinglist add tail client client set upload state us onuploadqueue the app emuledlg transferwnd queuelistctrl add client client true the app emuledlg transferwnd show queue count waitinglist get count client send ranking info cuploadqueue addclienttoqueue cupdownclient bignoretimelimit theapp isconnected theapp isfirewalled getkadport getdownloadstate ds_none isfriend theapp theapp islocalserver getserverip getserverport getwaitingusercount addaskedcount setlastuprequest bignoretimelimit addrequestcount getuploadfileid isbanned csameip getheadposition getnext cupdownclient cur_client getat cur_client m_baddnextconnect acceptnewclient m_baddnextconnect theprefs getloguldlevents adddebuglogline _t dbggetclientinfo m_baddnextconnect removefromwaitingqueue addupnextclient _t sendrankinginfo theapp refreshclient cur_client theapp addtrackclient cur_client cur_client getcurrentidentstate cur_client is_identified cur_client theprefs getverbose adddebuglogline getresstring ids_sameuserhash getusername cur_client getusername getusername getcurrentidentstate is_identified theprefs getverbose adddebuglogline getresstring ids_sameuserhash getusername cur_client getusername cur_client getusername removefromwaitingqueue cur_client cur_client _t addclienttoqueue cur_client theprefs getverbose adddebuglogline getresstring ids_sameuserhash getusername cur_client getusername _t removefromwaitingqueue cur_client cur_client _t addclienttoqueue cur_client cur_client csameip csameip theprefs getverbose debug_only adddebuglogline _t getusername getconnectip theapp getclientsfromip theprefs getverbose debug_only adddebuglogline _t trackedclientslist getusername getconnectip cknownfile theapp getfilebyid getuploadfileid addrequest ccollection hascollectionextention getfilename getfilesize maxprioritycoll_size isdownloading isconnected setcollectionuploadslot removefromwaitingqueue addupnextclient _t setcollectionuploadslot softqueuelimit theprefs getqueuesize hardqueuelimit theprefs getqueuesize theprefs getqueuesize getcount hardqueuelimit getcount softqueuelimit isfriend getfriendslot getcombinedfileprioandcredit getaveragecombinedfileprioandcredit isdownloading theprefs getdebugclienttcplevel debugsend op__acceptuploadreq op_acceptuploadreq thestats addupdataoverheadfilerequest sendpacket isempty forcenewclient addupnextclient _t addtail setuploadstate us_onuploadqueue theapp addclient theapp showqueuecount getcount sendrankinginfo bool c upload queue remove from upload queue c up down client client lpctstr psz reason bool updatewindow bool earlyabort bool result false uint32 slot counter 1 for position pos uploadinglist get head position pos 0 position cur pos pos c up down client cur client uploadinglist get next pos if client cur client if updatewindow the app emuledlg transferwnd uploadlistctrl remove client client if the prefs get log ul dl events add debug log line dlp verylow true t removing client from upload list s client s transferred s session up s queue session payload s psz reason null t psz reason client dbg get client info cast seconds tohm client get up start time delay 1000 cast itox bytes client get session up false false cast itox bytes client get queue session payload up false false client m baddnextconnect false uploadinglist remove at cur pos bool removed the app upload bandwidth throttler remove from standard list client socket bool pc removed the app upload bandwidth throttler remove from standard list c client req socket client m ppcupsocket void removed void pc removed if the prefs get log ul dl events removed pc removed add debug log line false t upload queue didn t find socket to delete adress 0x x client socket if client get session up 0 successfullupcount totaluploadtime client get up start time delay 1000 else if earlyabort false failedupcount c known file requested file the app sharedfiles get file byid client get upload fileid if requested file null requested file update parts info the app clientlist add track client client keep track of this client client set upload state us none client clear upload block requests client set collection upload slot false m ihighestnumberoffullyactivatedslotssincelastcall 0 result true else cur client set slot number slot counter slot counter return result cuploadqueue removefromuploadqueue cupdownclient pszreason slotcounter getheadposition curpos cupdownclient curclient getnext curclient theapp removeclient theprefs getloguldlevents adddebuglogline dlp_verylow _t sessionup queuesessionpayload pszreason _t pszreason dbggetclientinfo castsecondstohm getupstarttimedelay castitoxbytes getsessionup castitoxbytes getqueuesessionpayloadup m_baddnextconnect removeat curpos theapp uploadbandwidththrottler removefromstandardlist pcremoved theapp uploadbandwidththrottler removefromstandardlist cclientreqsocket m_ppcupsocket pcremoved theprefs getloguldlevents pcremoved adddebuglogline _t uploadqueue getsessionup getupstarttimedelay cknownfile requestedfile theapp getfilebyid getuploadfileid requestedfile requestedfile updatepartsinfo theapp addtrackclient setuploadstate us_none clearuploadblockrequests setcollectionuploadslot m_ihighestnumberoffullyactivatedslotssincelastcall curclient setslotnumber slotcounter slotcounter bool c upload queue remove from waiting queue c up down client client bool updatewindow position pos waitinglist find client if pos remove from waiting queue pos updatewindow if updatewindow the app emuledlg transferwnd show queue count waitinglist get count client m baddnextconnect false return true else return false cuploadqueue removefromwaitingqueue cupdownclient removefromwaitingqueue theapp showqueuecount getcount m_baddnextconnect void c upload queue update datarates calculate average datarate if get tick count m lastcalculateddataratetick 500 m lastcalculateddataratetick get tick count if avarage dr list get size 2 avarage tick list get tail avarage tick list get head datarate uint m avarage dr sum avarage dr list get head 1000 avarage tick list get tail avarage tick list get head friend datarate uint avarage friend dr list get tail avarage friend dr list get head 1000 avarage tick list get tail avarage tick list get head cuploadqueue updatedatarates gettickcount m_lastcalculateddataratetick m_lastcalculateddataratetick gettickcount avarage_dr_list getsize avarage_tick_list gettail avarage_tick_list gethead m_avarage_dr_sum avarage_dr_list gethead avarage_tick_list gettail avarage_tick_list gethead frienddatarate avarage_friend_dr_list gettail avarage_friend_dr_list gethead avarage_tick_list gettail avarage_tick_list gethead uint32 c upload queue get datarate return datarate cuploadqueue getdatarate uint32 c upload queue get to network datarate if datarate friend datarate return datarate friend datarate else return 0 cuploadqueue gettonetworkdatarate frienddatarate frienddatarate bool c upload queue check for time over c up down client client if we have nobody in the queue do not remove the current uploads this will save some bandwidth and some unneeded swapping from upload queue upload if waitinglist is empty client get friend slot return false if client has collection upload slot c known file p downloading file the app sharedfiles get file byid client requpfileid if p downloading file null return true if c collection has collection extention p downloading file get file name p downloading file get file size uint64 maxprioritycoll size return false else if the prefs get log ul dl events add debug log line dlp high false t s upload session ended client with collection slot tried to request blocks from another file client get user name return true if the prefs transfer full chunks if client get up start time delay sessionmaxtime try to keep the clients from downloading for ever if the prefs get log ul dl events add debug log line dlp low false t s upload session ended due to max time s client get user name cast seconds tohm sessionmaxtime 1000 return true cache current client score const uint32 score client get score true true check if another client has a bigger score if score get max client score m dwremovedclientbyscore get tick count if the prefs get log ul dl events add debug log line dlp verylow false t s upload session ended due to score client get user name set timer to prevent to many uploadslot getting kick do to score upload slots are delayed by a min of 1 sec and the maxscore is reset every 5 sec so i choose 6 secs to make sure the maxscore it updated before doing this again m dwremovedclientbyscore get tick count sec2ms 6 return true else allow the client to download a specified amount per session if client get queue session payload up sessionmaxtrans if the prefs get log ul dl events add debug log line dlp default false t s upload session ended due to max transferred amount s client get user name cast itox bytes sessionmaxtrans false false return true return false cuploadqueue checkfortimeover cupdownclient isempty getfriendslot hascollectionuploadslot cknownfile pdownloadingfile theapp getfilebyid pdownloadingfile ccollection hascollectionextention pdownloadingfile getfilename pdownloadingfile getfilesize maxprioritycoll_size theprefs getloguldlevents adddebuglogline dlp_high _t getusername theprefs transferfullchunks getupstarttimedelay theprefs getloguldlevents adddebuglogline dlp_low _t getusername castsecondstohm getscore getmaxclientscore m_dwremovedclientbyscore gettickcount theprefs getloguldlevents adddebuglogline dlp_verylow _t getusername m_dwremovedclientbyscore gettickcount getqueuesessionpayloadup theprefs getloguldlevents adddebuglogline dlp_default _t getusername castitoxbytes c up down client c upload queue getwaitingclientbyip udp uint32 dwip uint16 nudp port for position pos waitinglist get head position pos 0 c up down client cur client waitinglist get next pos if dwip cur client getip nudp port cur client getudp port return cur client return 0 cupdownclient cuploadqueue getwaitingclientbyip_udp nudpport getheadposition cupdownclient cur_client getnext cur_client nudpport cur_client getudpport cur_client c up down client c upload queue get waiting client byip uint32 dwip for position pos waitinglist get head position pos 0 c up down client cur client waitinglist get next pos if dwip cur client getip return cur client return 0 cupdownclient cuploadqueue getwaitingclientbyip getheadposition cupdownclient cur_client getnext cur_client cur_client c up down client c upload queue get next client const c up down client lastclient if waitinglist is empty return 0 if lastclient return waitinglist get head position pos waitinglist find const cast c up down client lastclient if pos trace error c upload queue get next client return waitinglist get head waitinglist get next pos if pos return null else return waitinglist get at pos cupdownclient cuploadqueue getnextclient cupdownclient isempty gethead const_cast cupdownclient cuploadqueue getnextclient gethead getnext getat void c upload queue delete all waitinglist remove all uploadinglist remove all pending remove from upload bandwidth throttler as well cuploadqueue deleteall removeall removeall uploadbandwidththrottler uint c upload queue get waiting position c up down client client if is on upload queue client return 0 uint rank 1 uint myscore client get score false for position pos waitinglist get head position pos 0 if waitinglist get next pos get score false myscore rank return rank cuploadqueue getwaitingposition cupdownclient isonuploadqueue getscore getheadposition getnext getscore uint32 c upload queue get average up time if successfullupcount return totaluploadtime successfullupcount return 0 cuploadqueue getaverageuptime c up down client c upload queue find best client in queue position toadd 0 position toaddlow 0 uint32 bestscore 0 uint32 bestlowscore 0 c up down client newclient null c up down client lowclient null position pos1 pos2 for pos1 waitinglist get head position pos2 pos1 null waitinglist get next pos1 c up down client cur client waitinglist get at pos2 while we are going through this list lets check if a client appears to have left the network assert cur client get last up request if get tick count cur client get last up request max purgequeuetime the app sharedfiles get file byid cur client get upload fileid this client has either not been seen in a long time or we no longer share the file he wanted anymore cur client clear wait start time remove from waiting queue pos2 true continue else finished clearing uint32 cur score cur client get score false if cur score bestscore cur client is more worthy than current best client that is ready to go connected if cur client has lowid cur client socket cur client socket is connected this client is a highid or a lowid client that is ready to go connected and it is more worthy bestscore cur score toadd pos2 newclient waitinglist get at toadd else if cur client m baddnextconnect this client is a lowid client that is not ready to go not connected now that we know this client is not ready to go compare it to the best not ready client the best not ready client may be better than the best ready client so we need to check against that client if cur score bestlowscore it is more worthy keep it bestlowscore cur score toaddlow pos2 lowclient waitinglist get at toaddlow if bestlowscore bestscore lowclient lowclient m baddnextconnect true if toadd return null else return waitinglist get at toadd cupdownclient cuploadqueue findbestclientinqueue cupdownclient cupdownclient getheadposition getnext cupdownclient cur_client getat cur_client getlastuprequest gettickcount cur_client getlastuprequest max_purgequeuetime theapp getfilebyid cur_client getuploadfileid cur_client clearwaitstarttime removefromwaitingqueue cur_score cur_client getscore cur_score cur_client cur_client haslowid cur_client cur_client isconnected cur_score getat cur_client m_baddnextconnect cur_score cur_score getat m_baddnextconnect getat void c upload queue re sort upload slots bool force dword curtick get tick count if force curtick m dwlastresorteduploadslots 10 1000 m dwlastresorteduploadslots curtick the app upload bandwidth throttler pause true c typed ptr list c ptr list c up down client temp uploadinglist remove all clients from uploading list and store in temp list position ulpos uploadinglist get head position while ulpos null position curpos ulpos uploadinglist get next ulpos get and remove the client from upload list c up down client cur client uploadinglist get at curpos uploadinglist remove at curpos remove the found client from upload bandwidth throttler the app upload bandwidth throttler remove from standard list cur client socket the app upload bandwidth throttler remove from standard list c client req socket cur client m ppcupsocket temp uploadinglist add tail cur client remove one at a time from temp list and reinsert in correct position in uploading list position temp pos temp uploadinglist get head position while temp pos null position curpos temp pos temp uploadinglist get next temp pos get and remove the client from upload list c up down client cur client temp uploadinglist get at curpos temp uploadinglist remove at curpos this will insert in correct place insert in uploading list cur client the app upload bandwidth throttler pause false cuploadqueue resortuploadslots gettickcount m_dwlastresorteduploadslots m_dwlastresorteduploadslots theapp uploadbandwidththrottler ctypedptrlist cptrlist cupdownclient tempuploadinglist templist getheadposition getnext cupdownclient cur_client getat removeat uploadbandwidththrottler theapp uploadbandwidththrottler removefromstandardlist cur_client theapp uploadbandwidththrottler removefromstandardlist cclientreqsocket cur_client m_ppcupsocket tempuploadinglist addtail cur_client temppos tempuploadinglist getheadposition temppos temppos tempuploadinglist getnext temppos cupdownclient cur_client tempuploadinglist getat tempuploadinglist removeat insertinuploadinglist cur_client theapp uploadbandwidththrottler void c upload queue remove from waiting queue position pos bool updatewindow c up down client todelete waitinglist get at pos waitinglist remove at pos if updatewindow the app emuledlg transferwnd queuelistctrl remove client todelete todelete set upload state us none cuploadqueue removefromwaitingqueue cupdownclient getat removeat theapp removeclient setuploadstate us_none bool c upload queue accept new client bool add on next connect uint32 cur upload slots uint32 uploadinglist get count we allow one extra slot to be created to accommodate lowid users this is because we skip these users when it was actually their turn to get an upload slot if add on next connect cur upload slots 0 cur upload slots return accept new client cur upload slots cuploadqueue acceptnewclient addonnextconnect curuploadslots getcount addonnextconnect curuploadslots curuploadslots acceptnewclient curuploadslots bool c upload queue accept new client uint32 cur upload slots check if we can allow a new client to start downloading from us if cur upload slots min up clients allowed return true uint16 max speed if the prefs is dyn up enabled max speed uint16 the app last common route finder get upload 1024 else max speed the prefs get max upload if cur upload slots max up clients allowed cur upload slots 4 cur upload slots datarate upload check client dr cur upload slots uint32 max speed 1024 upload client datarate the prefs get max upload unlimited the prefs is dyn up enabled the prefs get max graph upload rate true 0 cur upload slots uint32 the prefs get max graph upload rate false 1024 upload client datarate max number of clients to allow for all circumstances return false return true cuploadqueue acceptnewclient curuploadslots curuploadslots min_up_clients_allowed maxspeed theprefs isdynupenabled maxspeed theapp lastcommonroutefinder getupload maxspeed theprefs getmaxupload curuploadslots max_up_clients_allowed curuploadslots curuploadslots upload_check_client_dr curuploadslots maxspeed upload_client_datarate theprefs getmaxupload theprefs isdynupenabled theprefs getmaxgraphuploadrate curuploadslots theprefs getmaxgraphuploadrate upload_client_datarate bool c upload queue force new client bool allow empty waiting queue if allow empty waiting queue waitinglist get size 0 return false if get tick count m nlaststartupload 1000 datarate 102400 return false uint32 cur upload slots uint32 uploadinglist get count if cur upload slots min up clients allowed return true if accept new client cur upload slots the app last common route finder accept new client upload speed sense can veto a new slot if uss enabled return false uint16 max speed if the prefs is dyn up enabled max speed uint16 the app last common route finder get upload 1024 else max speed the prefs get max upload uint32 up per client upload client datarate if throttler doesn t require another slot go with a slightly more restrictive method if max speed 20 max speed unlimited up per client datarate 43 if up per client 7680 up per client 7680 now the final check if max speed unlimited if cur upload slots datarate up per client return true else uint16 n max slots if max speed 12 n max slots uint16 float max speed 1024 up per client else if max speed 7 n max slots min up clients allowed 2 else if max speed 3 n max slots min up clients allowed 1 else n max slots min up clients allowed add log line true maxslots u up per client u datarateslot u u u n max slots up per client datarate upload check client dr datarate upload check client dr if cur upload slots n max slots return true if m ihighestnumberoffullyactivatedslotssincelastcall uint32 uploadinglist get size upload throttler requests another slot if throttler says it needs another slot we will allow more slots than what we require ourself never allow more slots than to give each slot high enough average transfer speed though checked above if the prefs get log ul dl events waitinglist get size 0 add debug log line false t upload queue added new slot since throttler needs it m ihighestnumberoffullyactivatedslotssincelastcall i uploadinglist get size i tick i m ihighestnumberoffullyactivatedslotssincelastcall uploadinglist get size get tick count return true nope return false cuploadqueue forcenewclient allowemptywaitingqueue allowemptywaitingqueue getsize gettickcount m_nlaststartupload curuploadslots getcount curuploadslots min_up_clients_allowed acceptnewclient curuploadslots theapp lastcommonroutefinder acceptnewclient uploadspeedsense maxspeed theprefs isdynupenabled maxspeed theapp lastcommonroutefinder getupload maxspeed theprefs getmaxupload upperclient upload_client_datarate maxspeed maxspeed upperclient upperclient upperclient maxspeed curuploadslots upperclient nmaxslots maxspeed nmaxslots maxspeed upperclient maxspeed nmaxslots min_up_clients_allowed maxspeed nmaxslots min_up_clients_allowed nmaxslots min_up_clients_allowed addlogline upperclient nmaxslots upperclient upload_check_client_dr upload_check_client_dr curuploadslots nmaxslots m_ihighestnumberoffullyactivatedslotssincelastcall getsize uploadthrottler theprefs getloguldlevents getsize adddebuglogline _t uploadqueue m_ihighestnumberoffullyactivatedslotssincelastcall getsize m_ihighestnumberoffullyactivatedslotssincelastcall getsize gettickcount bool c upload queue add up next client lpctstr psz reason c up down client directadd c up down client newclient null select next client or use given client if directadd newclient find best client in queue if newclient remove from waiting queue newclient true the app emuledlg transferwnd show queue count waitinglist get count else newclient directadd if newclient null return false if the prefs transfer full chunks update max client score refresh score caching now that the highest score is removed if is downloading newclient return false if psz reason the prefs get log ul dl events add debug log line false t adding client to upload list s client s psz reason newclient dbg get client info if newclient has collection upload slot directadd null assert false newclient set collection upload slot false tell the client that we are now ready to upload if newclient socket newclient socket is connected newclient set upload state us connecting if newclient try to connect true return false else if the prefs get debug clienttcp level 0 debug send op acceptuploadreq newclient packet packet new packet op acceptuploadreq 0 the stats add up data overhead file request packet size newclient socket send packet packet true newclient set upload state us uploading newclient set up start time newclient reset session up insert in uploading list newclient m nlaststartupload get tick count statistic c known file reqfile the app sharedfiles get file byid uchar newclient get upload fileid if reqfile reqfile statistic add accepted the app emuledlg transferwnd uploadlistctrl add client newclient return true cuploadqueue addupnextclient pszreason cupdownclient cupdownclient findbestclientinqueue removefromwaitingqueue theapp showqueuecount getcount theprefs transferfullchunks updatemaxclientscore isdownloading pszreason theprefs getloguldlevents adddebuglogline _t pszreason dbggetclientinfo hascollectionuploadslot setcollectionuploadslot isconnected setuploadstate us_connecting trytoconnect theprefs getdebugclienttcplevel debugsend op__acceptuploadreq op_acceptuploadreq thestats addupdataoverheadfilerequest sendpacket setuploadstate us_uploading setupstarttime resetsessionup insertinuploadinglist m_nlaststartupload gettickcount cknownfile theapp getfilebyid getuploadfileid addaccepted theapp addclient void c upload queue update max client score m imaxscore 0 for position pos waitinglist get head position pos 0 uint32 score waitinglist get next pos get score true false if score m imaxscore m imaxscore score cuploadqueue updatemaxclientscore m_imaxscore getheadposition getnext getscore m_imaxscore m_imaxscore void c upload queue update active clients info dword cur tick save number of active clients for statistics uint32 temp highest the app upload bandwidth throttler get highest number of fully activated slots since last call and reset if the prefs get log ul dl events the app upload bandwidth throttler get standard list size uint32 uploadinglist get size debug info will remove this when i m done add debug log line false t upload queue error throttler has more slots than upload queue throttler i upload queue i tick i the app upload bandwidth throttler get standard list size uploadinglist get size get tick count if temp highest uint32 uploadinglist get size 1 temp highest uploadinglist get size 1 m ihighestnumberoffullyactivatedslotssincelastcall temp highest save some data about number of fully active clients uint32 temp max removed 0 while activeclients tick list is empty activeclients list is empty cur tick activeclients tick list get head 20 1000 activeclients tick list remove head uint32 removed activeclients list remove head if removed temp max removed temp max removed removed activeclients list add tail m ihighestnumberoffullyactivatedslotssincelastcall activeclients tick list add tail cur tick if activeclients tick list get size 1 uint32 temp max active clients m ihighestnumberoffullyactivatedslotssincelastcall uint32 temp max active clients short time m ihighestnumberoffullyactivatedslotssincelastcall position active clients tick pos activeclients tick list get tail position position active clients list pos activeclients list get tail position while active clients list pos null temp max removed temp max active clients temp max removed m maxactiveclients cur tick activeclients tick list get at active clients tick pos 10 1000 dword active clients tick snapshot activeclients tick list get at active clients tick pos uint32 active clients snapshot activeclients list get at active clients list pos if active clients snapshot temp max active clients temp max active clients active clients snapshot if active clients snapshot temp max active clients short time cur tick active clients tick snapshot 10 1000 temp max active clients short time active clients snapshot activeclients tick list get prev active clients tick pos activeclients list get prev active clients list pos if temp max removed m maxactiveclients temp max active clients m maxactiveclients m maxactiveclients temp max active clients m maxactiveclientsshorttime temp max active clients short time else m maxactiveclients m ihighestnumberoffullyactivatedslotssincelastcall m maxactiveclientsshorttime m ihighestnumberoffullyactivatedslotssincelastcall cuploadqueue updateactiveclientsinfo curtick temphighest theapp uploadbandwidththrottler gethighestnumberoffullyactivatedslotssincelastcallandreset theprefs getloguldlevents theapp uploadbandwidththrottler getstandardlistsize getsize adddebuglogline _t uploadqueue uploadqueue uploadqueue theapp uploadbandwidththrottler getstandardlistsize getsize gettickcount temphighest getsize temphighest getsize m_ihighestnumberoffullyactivatedslotssincelastcall temphighest tempmaxremoved activeclients_tick_list isempty activeclients_list isempty curtick activeclients_tick_list gethead activeclients_tick_list removehead activeclients_list removehead tempmaxremoved tempmaxremoved activeclients_list addtail m_ihighestnumberoffullyactivatedslotssincelastcall activeclients_tick_list addtail curtick activeclients_tick_list getsize tempmaxactiveclients m_ihighestnumberoffullyactivatedslotssincelastcall tempmaxactiveclientsshorttime m_ihighestnumberoffullyactivatedslotssincelastcall activeclientstickpos activeclients_tick_list gettailposition activeclientslistpos activeclients_list gettailposition activeclientslistpos tempmaxremoved tempmaxactiveclients tempmaxremoved m_maxactiveclients curtick activeclients_tick_list getat activeclientstickpos activeclientsticksnapshot activeclients_tick_list getat activeclientstickpos activeclientssnapshot activeclients_list getat activeclientslistpos activeclientssnapshot tempmaxactiveclients tempmaxactiveclients activeclientssnapshot activeclientssnapshot tempmaxactiveclientsshorttime curtick activeclientsticksnapshot tempmaxactiveclientsshorttime activeclientssnapshot activeclients_tick_list getprev activeclientstickpos activeclients_list getprev activeclientslistpos tempmaxremoved m_maxactiveclients tempmaxactiveclients m_maxactiveclients m_maxactiveclients tempmaxactiveclients m_maxactiveclientsshorttime tempmaxactiveclientsshorttime m_maxactiveclients m_ihighestnumberoffullyactivatedslotssincelastcall m_maxactiveclientsshorttime m_ihighestnumberoffullyactivatedslotssincelastcall void c upload queue insert in uploading list c up down client newclient lets make sure any client that is added to the list has this flag reset newclient m baddnextconnect false add it last the app upload bandwidth throttler add to standard list uploadinglist get count newclient get file upload socket uploadinglist add tail newclient newclient set slot number uploadinglist get count cuploadqueue insertinuploadinglist cupdownclient m_baddnextconnect theapp uploadbandwidththrottler addtostandardlist getcount getfileuploadsocket addtail setslotnumber getcount float c upload queue get average combined file prio and credit dword cur tick get tick count if cur tick m dwlastcalculatedaveragecombinedfileprioandcredit 5 1000 m dwlastcalculatedaveragecombinedfileprioandcredit cur tick todo is there a risk of overflow i don t think so double sum 0 for position pos waitinglist get head position pos null c up down client cur client waitinglist get next pos sum cur client get combined file prio and credit m faveragecombinedfileprioandcredit float sum waitinglist get size return m faveragecombinedfileprioandcredit cuploadqueue getaveragecombinedfileprioandcredit curtick gettickcount curtick m_dwlastcalculatedaveragecombinedfileprioandcredit m_dwlastcalculatedaveragecombinedfileprioandcredit curtick getheadposition cupdownclient cur_client getnext cur_client getcombinedfileprioandcredit m_faveragecombinedfileprioandcredit getsize m_faveragecombinedfileprioandcredit c server connect c server connect c server list in serverlist connectedsocket null used list in serverlist max simcons the prefs is safe server connect enabled 1 2 connecting false connected false clientid 0 singleconnecting false if the prefs get serverudp port 0 udpsocket new cudp socket initalize socket for udp packets if udpsocket create delete udpsocket udpsocket null else udpsocket null m idretrytimer 0 last start at 0 init localip cserverconnect cserverconnect cserverlist in_serverlist used_list in_serverlist max_simcons theprefs issafeserverconnectenabled theprefs getserverudpport cudpsocket m_idretrytimer laststartat initlocalip c server connect c server connect stop all connections stop connection try close connected socket if any destroy socket connectedsocket connectedsocket null close udp socket if udpsocket udpsocket close delete udpsocket cserverconnect cserverconnect stopconnectiontry destroysocket void c server connect connection failed c server socket sender if connecting false sender connectedsocket just return cleanup is done by the socket itself return messages c server update switch sender get connection state case cs fatalerror log error log statusbar get res string ids err fatal break case cs disconnected the app sharedfiles cleared2k publish info log error log statusbar get res string ids err lostc sender cur server get list name sender cur server get fullip sender cur server get port break case cs serverdead log error log statusbar get res string ids err dead sender cur server get list name sender cur server get fullip sender cur server get port update the app serverlist get server by address sender cur server get address sender cur server get port if update update add failed count the app emuledlg serverwnd serverlistctrl refresh server update break case cs error break case cs serverfull log error log statusbar get res string ids err full sender cur server get list name sender cur server get fullip sender cur server get port break case cs notconnected break important mark this socket not to be deleted in stop connection try because it will delete itself after this function sender m bisdeleting true switch sender get connection state case cs fatalerror bool autoretry singleconnecting stop connection try if the prefs reconnect autoretry m idretrytimer log warning get res string ids reconnect cs retryconnecttime verify m idretrytimer set timer null 0 1000 cs retryconnecttime retry connect timer null if the prefs get verbose m idretrytimer debug log error t failed to create server connect retry timer s get error message get last error break case cs disconnected the app sharedfiles cleared2k publish info connected false if connectedsocket connectedsocket close connectedsocket null the app emuledlg searchwnd cancel ed2k search khaos tell our total server duration thinkymajig to update the stats server connect time 0 the stats add2 total server duration khaos if the prefs reconnect connecting connect to any server if the prefs get notifier on important error the app emuledlg show notifier get res string ids connectionlost tbn importantevent break case cs error case cs notconnected if connecting break case cs serverdead case cs serverfull if connecting break if singleconnecting stop connection try break dword tmpkey c server socket tmpsock position pos connectionattemps get start position while pos connectionattemps get next assoc pos tmpkey tmpsock if tmpsock sender connectionattemps remove key tmpkey break try another connectionrequest the app emuledlg show connection state cserverconnect connectionfailed cserversocket cserver getconnectionstate cs_fatalerror logerror log_statusbar getresstring ids_err_fatal cs_disconnected theapp cleared2kpublishinfo logerror log_statusbar getresstring ids_err_lostc cur_server getlistname cur_server getfullip cur_server getport cs_serverdead logerror log_statusbar getresstring ids_err_dead cur_server getlistname cur_server getfullip cur_server getport theapp getserverbyaddress cur_server getaddress cur_server getport addfailedcount theapp refreshserver cs_error cs_serverfull logerror log_statusbar getresstring ids_err_full cur_server getlistname cur_server getfullip cur_server getport cs_notconnected stopconnectiontry m_bisdeleting getconnectionstate cs_fatalerror stopconnectiontry theprefs m_idretrytimer logwarning getresstring ids_reconnect cs_retryconnecttime m_idretrytimer settimer cs_retryconnecttime retryconnecttimer theprefs getverbose m_idretrytimer debuglogerror _t geterrormessage getlasterror cs_disconnected theapp cleared2kpublishinfo theapp canceled2ksearch thestats serverconnecttime thestats add2totalserverduration theprefs connecttoanyserver theprefs getnotifieronimportanterror theapp shownotifier getresstring ids_connectionlost tbn_importantevent cs_error cs_notconnected cs_serverdead cs_serverfull stopconnectiontry cserversocket getstartposition getnextassoc removekey tryanotherconnectionrequest theapp showconnectionstate void c server connect connection established c server socket sender if connecting false we are already connected to another server destroy socket sender return init localip if sender get connection state cs waitforlogin add log line false get res string ids connectedtoreq sender cur server get list name sender cur server get fullip sender cur server get port c server update the app serverlist get server by address sender cur server get address sender cur server get port if update update reset failed count the app emuledlg serverwnd serverlistctrl refresh server update send loginpacket c safe mem file data 256 data write hash16 the prefs get user hash data writeu int32 get clientid data writeu int16 the prefs get port uint32 tagcount 4 data writeu int32 tagcount c tag tag name ct name the prefs get user nick tag name write tag to file data c tag tag version ct version edonkeyversion tag version write tag to file data ifdef support large files c tag tag flags ct server flags srvcap zlib srvcap newtags srvcap largefiles srvcap unicode else c tag tag flags ct server flags srvcap zlib srvcap newtags srvcap unicode endif tag flags write tag to file data e mule version 14 mar 2004 requested by lugdunummaster need for lowid clients which have no chance to send an hello packet to the server during the callback test c tag tag mule version ct emule version u compatible clientid 24 cemule app m nversionmjr 17 cemule app m nversionmin 10 cemule app m nversionupd 7 tag mule version write tag to file data packet packet new packet data packet opcode op loginrequest if the prefs get debug servertcp level 0 debug t sending op loginrequest n the stats add up data overhead server packet size send packet packet true sender else if sender get connection state cs connected the stats reconnects the stats server connect time get tick count connected true log log success log statusbar get res string ids connectedto sender cur server get list name the app emuledlg show connection state connectedsocket sender stop connection try the app sharedfiles cleared2k publish info the app sharedfiles send list to server the app emuledlg serverwnd serverlistctrl remove all dead servers tecxx 1609 2002 serverlist update if the prefs get add servers from server packet packet new packet op getserverlist 0 if the prefs get debug servertcp level 0 debug t sending op getserverlist n the stats add up data overhead server packet size send packet packet true c server update the app serverlist get server by address sender cur server get address sender cur server get port the app emuledlg serverwnd serverlistctrl refresh server update the app emuledlg show connection state cserverconnect connectionestablished cserversocket destroysocket initlocalip getconnectionstate cs_waitforlogin addlogline getresstring ids_connectedtoreq cur_server getlistname cur_server getfullip cur_server getport cserver theapp getserverbyaddress cur_server getaddress cur_server getport resetfailedcount theapp refreshserver csafememfile writehash16 theprefs getuserhash writeuint32 getclientid writeuint16 theprefs getport writeuint32 ctag tagname ct_name theprefs getusernick tagname writetagtofile ctag tagversion ct_version tagversion writetagtofile support_large_files ctag tagflags ct_server_flags srvcap_zlib srvcap_newtags srvcap_largefiles srvcap_unicode ctag tagflags ct_server_flags srvcap_zlib srvcap_newtags srvcap_unicode tagflags writetagtofile emule ctag tagmuleversion ct_emule_version ucompatibleclientid cemuleapp m_nversionmjr cemuleapp m_nversionmin cemuleapp m_nversionupd tagmuleversion writetagtofile op_loginrequest theprefs getdebugservertcplevel _t op__loginrequest thestats addupdataoverheadserver sendpacket getconnectionstate cs_connected thestats thestats serverconnecttime gettickcount log_success log_statusbar getresstring ids_connectedto cur_server getlistname theapp showconnectionstate stopconnectiontry theapp cleared2kpublishinfo theapp sendlisttoserver theapp removealldeadservers theprefs getaddserversfromserver op_getserverlist theprefs getdebugservertcplevel _t op__getserverlist thestats addupdataoverheadserver sendpacket cserver theapp getserverbyaddress cur_server getaddress cur_server getport theapp refreshserver theapp showconnectionstate void c server connect connect to any server uint32 start at bool prio sort bool is auto last start at start at stop connection try disconnect connecting true singleconnecting false the app emuledlg show connection state barry only auto connect to static server option if the prefs get auto connect to static servers only is auto bool anystatic false c server next server used list set server position start at while next server used list get next server null if next server is static member anystatic true break if anystatic connecting false log error log statusbar get res string ids err novalidserversfound return used list set server position start at if the prefs get use server priorities prio sort used list sort if used list get server count 0 connecting false log error log statusbar get res string ids err novalidserversfound return the app listensocket process try another connectionrequest cserverconnect connecttoanyserver startat priosort isauto laststartat startat stopconnectiontry theapp showconnectionstate theprefs getautoconnecttostaticserversonly isauto cserver next_server used_list setserverposition startat next_server used_list getnextserver next_server isstaticmember logerror log_statusbar getresstring ids_err_novalidserversfound used_list setserverposition startat theprefs getuseserverpriorities priosort used_list used_list getservercount logerror log_statusbar getresstring ids_err_novalidserversfound theapp tryanotherconnectionrequest void c server connect connect to server c server server bool multiconnect if multiconnect stop connection try disconnect connecting true singleconnecting multiconnect the app emuledlg show connection state c server socket newsocket new c server socket this m lstopensockets add tail void newsocket newsocket create 0 sock stream fd read fd write fd close fd connect the prefs get bind addra newsocket connect to server server connectionattemps set at get tick count newsocket cserverconnect connecttoserver cserver stopconnectiontry theapp showconnectionstate cserversocket cserversocket m_lstopensockets addtail sock_stream fd_read fd_write fd_close fd_connect theprefs getbindaddra connecttoserver setat gettickcount void c server connect stop connection try connectionattemps remove all connecting false singleconnecting false the app emuledlg show connection state if m idretrytimer kill timer null m idretrytimer m idretrytimer 0 close all currenty opened sockets except the one which is connected to our current server for position pos m lstopensockets get head position pos null c server socket p sck c server socket m lstopensockets get next pos if p sck connectedsocket don t destroy socket which is connected to server continue if p sck m bisdeleting false don t destroy socket if it is going to destroy itself later on destroy socket p sck cserverconnect stopconnectiontry removeall theapp showconnectionstate m_idretrytimer killtimer m_idretrytimer m_idretrytimer m_lstopensockets getheadposition cserversocket psck cserversocket m_lstopensockets getnext psck psck m_bisdeleting destroysocket psck void callback c server connect retry connect timer hwnd h wnd uint n msg uint n id dword dw time note always handle all type of mfc exceptions in timer procs otherwise we ll get mem leaks try c server connect this the app serverconnect assert this this stop connection try if this is connected return this connect to any server catch dflt exceptions t c server connect retry connect timer cserverconnect retryconnecttimer hwnd nmsg nid dwtime timerprocs cserverconnect _this theapp _this _this stopconnectiontry _this isconnected _this connecttoanyserver catch_dflt_exceptions _t cserverconnect retryconnecttimer void c server connect check for timeout dword dw server connect timeout conservtimeout if we are using a proxy increase server connection timeout to default connection timeout if the prefs get proxy settings use proxy dw server connect timeout max dw server connect timeout connection timeout dword dw cur tick get tick count dword tmpkey c server socket tmpsock position pos connectionattemps get start position while pos connectionattemps get next assoc pos tmpkey tmpsock if tmpsock if the prefs get verbose debug log error t error socket invalid at timeoutcheck connectionattemps remove key tmpkey return if dw cur tick tmpkey dw server connect timeout log warning get res string ids err contimeout tmpsock cur server get list name tmpsock cur server get fullip tmpsock cur server get port connectionattemps remove key tmpkey try another connectionrequest destroy socket tmpsock cserverconnect checkfortimeout dwserverconnecttimeout theprefs getproxysettings useproxy dwserverconnecttimeout dwserverconnecttimeout connection_timeout dwcurtick gettickcount cserversocket getstartposition getnextassoc theprefs getverbose debuglogerror _t removekey dwcurtick dwserverconnecttimeout logwarning getresstring ids_err_contimeout cur_server getlistname cur_server getfullip cur_server getport removekey tryanotherconnectionrequest destroysocket void c server connect destroy socket c server socket p sck if p sck null return remove socket from list of opened sockets for position pos m lstopensockets get head position pos null position pos del pos c server socket p test sck c server socket m lstopensockets get next pos if p test sck p sck m lstopensockets remove at pos del break if p sck m socketdata h socket invalid socket deadlake proxysupport changed to async socket ex p sck async select 0 p sck close delete p sck cserverconnect destroysocket cserversocket psck psck m_lstopensockets getheadposition posdel cserversocket ptestsck cserversocket m_lstopensockets getnext ptestsck psck m_lstopensockets removeat posdel psck m_socketdata hsocket invalid_socket asyncsocketex psck asyncselect psck psck bool c server connect send packet packet packet bool delpacket c server socket to if to if connected connectedsocket send packet packet delpacket true else if delpacket delete packet return false else to send packet packet delpacket true return true cserverconnect sendpacket cserversocket sendpacket sendpacket bool c server connect sendudp packet packet packet c server host bool delpacket if the app is connected if udpsocket null udpsocket send packet packet host if delpacket delete packet return true cserverconnect sendudppacket cserver theapp isconnected sendpacket void c server connect keep connection alive dword dw server keep alive timeout the prefs get server keep alive timeout if dw server keep alive timeout connected connectedsocket connectedsocket connectionstate cs connected get tick count connectedsocket get last transmission dw server keep alive timeout ping the server if the tcp connection was not used for the specified interval with an empty publish files packet recommended by lugdunummaster himself c safe mem file files 4 files writeu int32 0 nr of files packet packet new packet files packet opcode op offerfiles if the prefs get verbose add debug log line false t refreshing server connection if the prefs get debug servertcp level 0 debug t sending op offerfiles keep alive to server n the stats add up data overhead server packet size connectedsocket send packet packet true cserverconnect keepconnectionalive dwserverkeepalivetimeout theprefs getserverkeepalivetimeout dwserverkeepalivetimeout cs_connected gettickcount getlasttransmission dwserverkeepalivetimeout csafememfile writeuint32 op_offerfiles theprefs getverbose adddebuglogline _t theprefs getdebugservertcplevel _t op__offerfiles keepalive thestats addupdataoverheadserver sendpacket bool c server connect disconnect if connected connectedsocket the app sharedfiles cleared2k publish info connected false c server update the app serverlist get server by address connectedsocket cur server get address connectedsocket cur server get port the app emuledlg serverwnd serverlistctrl refresh server update the app set publicip 0 destroy socket connectedsocket connectedsocket null the app emuledlg show connection state the app emuledlg add server message line t the app emuledlg add server message line t the app emuledlg add server message line t the app emuledlg add server message line t khaos tell our total server duration thinkymajig to update the stats server connect time 0 the stats add2 total server duration khaos return true else return false cserverconnect theapp cleared2kpublishinfo cserver theapp getserverbyaddress cur_server getaddress cur_server getport theapp refreshserver theapp setpublicip destroysocket theapp showconnectionstate theapp addservermessageline _t theapp addservermessageline _t theapp addservermessageline _t theapp addservermessageline _t thestats serverconnecttime thestats add2totalserverduration c server c server connect get current server if is connected connectedsocket return connectedsocket cur server return null cserver cserverconnect getcurrentserver isconnected cur_server bool c server connect is lowid return is lowid clientid cserverconnect islowid islowid void c server connect set clientid uint32 newid clientid newid if is lowid newid the app set publicip newid the app emuledlg show connection state cserverconnect setclientid islowid theapp setpublicip theapp showconnectionstate bool c server connect is local server uint32 dwip uint16 n port if is connected if connectedsocket cur server getip dwip connectedsocket cur server get port n port return true return false cserverconnect islocalserver nport isconnected cur_server cur_server getport nport void c server connect try another connectionrequest if connectionattemps get count the prefs is safe server connect enabled 1 2 c server next server used list get next server if next server null if connectionattemps get count 0 if m idretrytimer 0 05 nov 2003 if we have a very short server list we could put serious load on those few servers if we start the next connection tries without waiting log warning log statusbar get res string ids outofservers add log line false get res string ids reconnect cs retryconnecttime verify m idretrytimer set timer null 0 1000 cs retryconnecttime retry connect timer null if the prefs get verbose m idretrytimer debug log error t failed to create server connect retry timer s get error message get last error return barry only auto connect to static server option if the prefs get auto connect to static servers only if next server is static member connect to server next server true else connect to server next server true cserverconnect tryanotherconnectionrequest getcount theprefs issafeserverconnectenabled cserver next_server used_list getnextserver next_server getcount m_idretrytimer logwarning log_statusbar getresstring ids_outofservers addlogline getresstring ids_reconnect cs_retryconnecttime m_idretrytimer settimer cs_retryconnecttime retryconnecttimer theprefs getverbose m_idretrytimer debuglogerror _t geterrormessage getlasterror theprefs getautoconnecttostaticserversonly next_server isstaticmember connecttoserver next_server connecttoserver next_server void c server connect init localip m nlocalip 0 don t use gethostbyname null the winsock dll may be replaced by a dll from a third party which is not fully compatible to the original winsock dll ppl reported crash with scorsock dll when using gethostbyname null try char sz host 256 if gethostname sz host sizeof sz host 0 hostent p host ent gethostbyname sz host if p host ent null p host ent h length 4 p host ent h addr list 0 null m nlocalip uint32 p host ent h addr list 0 except exception execute handler at least two ppl reported crashs when using gethostbyname with third party winsock dl ls if the prefs get verbose debug log error t unknown exception in c server connect init localip assert 0 cserverconnect initlocalip m_nlocalip __try szhost szhost szhost phostent szhost phostent phostent h_length phostent h_addr_list m_nlocalip phostent h_addr_list __except exception_execute_handler dlls theprefs getverbose debuglogerror _t cserverconnect initlocalip m btextformat false m collectionfilesmap init hash table 1031 m scollectionname format t new collection u get tick count m pabycollectionauthorkey null m nkeysize 0 m_btextformat m_collectionfilesmap inithashtable m_scollectionname _t gettickcount m_pabycollectionauthorkey m_nkeysize c collection c collection const c collection p collection m scollectionname p collection m scollectionname if p collection m pabycollectionauthorkey null m nkeysize p collection m nkeysize m pabycollectionauthorkey new byte m nkeysize memcpy m pabycollectionauthorkey p collection m pabycollectionauthorkey m nkeysize m scollectionauthorname p collection m scollectionauthorname else m nkeysize 0 m pabycollectionauthorkey null m btextformat p collection m btextformat m collectionfilesmap init hash table 1031 position pos p collection m collectionfilesmap get start position c collection file p collection file cs key key while pos null p collection m collectionfilesmap get next assoc pos key p collection file add file to collection p collection file true ccollection ccollection ccollection pcollection m_scollectionname pcollection m_scollectionname pcollection m_pabycollectionauthorkey m_nkeysize pcollection m_nkeysize m_pabycollectionauthorkey m_nkeysize m_pabycollectionauthorkey pcollection m_pabycollectionauthorkey m_nkeysize m_scollectionauthorname pcollection m_scollectionauthorname m_nkeysize m_pabycollectionauthorkey m_btextformat pcollection m_btextformat m_collectionfilesmap inithashtable pcollection m_collectionfilesmap getstartposition ccollectionfile pcollectionfile cskey pcollection m_collectionfilesmap getnextassoc pcollectionfile addfiletocollection pcollectionfile c collection c collection void delete m pabycollectionauthorkey position pos m collectionfilesmap get start position c collection file p collection file cs key key while pos null m collectionfilesmap get next assoc pos key p collection file delete p collection file m collectionfilesmap remove all ccollection ccollection m_pabycollectionauthorkey m_collectionfilesmap getstartposition ccollectionfile pcollectionfile cskey m_collectionfilesmap getnextassoc pcollectionfile pcollectionfile m_collectionfilesmap removeall bool c collection init collection from file const c string s file path c string s file name debug only s file name replace collection fileextension t bool b collection loaded false c safe file data if data open s file path c file mode read c file share deny write c file type binary try uint32 n version data readu int32 if n version collection file version1 initial n version collection file version2 largefiles uint32 header tag count data readu int32 while header tag count c tag tag data true switch tag get nameid case ft filename if tag is str m scollectionname tag get str break case ft collectionauthor if tag is str m scollectionauthorname tag get str break case ft collectionauthorkey if tag is blob set collection author key tag get blob tag get blob size break header tag count uint32 file count data readu int32 while file count c collection file p collection file new c collection file data if p collection file add file to collection p collection file false file count b collection loaded true if m pabycollectionauthorkey null bool b result false if data get length data get position using namespace cryptopp uint32 n pos uint32 data get position data seek to begin byte p message new byte n pos verify data read p message n pos n pos string source ss pubkey m pabycollectionauthorkey m nkeysize true 0 rsassa pkcs1v15 sha verifier pubkey ss pubkey int n sign len int data get length data get position byte p signature new byte n sign len verify data read p signature n sign len uint n sign len b result pubkey verify message p message n pos p signature n sign len delete p message delete p signature if b result debug log warning t collection s verifying of public key failed m scollectionname delete m pabycollectionauthorkey m pabycollectionauthorkey null m nkeysize 0 m scollectionauthorname t else debug log t collection s public key verified m scollectionname else m scollectionauthorname t data close catch c file exception error error delete return false catch assert false data close return false else return false if b collection loaded c stdio file data if data open s file path c file mode read c file share deny write c file type text try c string s link while data read string s link ignore all lines that start with these lines can be used for future features if s link find t 0 try c collection file p collection file new c collection file if p collection file init from link s link add file to collection p collection file false else delete p collection file catch assert false data close return false data close m scollectionname s file name b collection loaded true m btextformat true catch c file exception error error delete return false catch assert false data close return false return b collection loaded ccollection initcollectionfromfile cstring sfilepath cstring sfilename debug_only sfilename collection_fileextension _t bcollectionloaded csafefile sfilepath cfile moderead cfile sharedenywrite cfile typebinary nversion readuint32 nversion collection_file_version1_initial nversion collection_file_version2_largefiles headertagcount readuint32 headertagcount ctag getnameid ft_filename isstr m_scollectionname getstr ft_collectionauthor isstr m_scollectionauthorname getstr ft_collectionauthorkey isblob setcollectionauthorkey getblob getblobsize headertagcount filecount readuint32 filecount ccollectionfile pcollectionfile ccollectionfile pcollectionfile addfiletocollection pcollectionfile filecount bcollectionloaded m_pabycollectionauthorkey bresult getlength getposition npos getposition seektobegin pmessage npos pmessage npos npos stringsource ss_pubkey m_pabycollectionauthorkey m_nkeysize rsassa_pkcs1v15_sha_verifier ss_pubkey nsignlen getlength getposition psignature nsignlen psignature nsignlen nsignlen bresult verifymessage pmessage npos psignature nsignlen pmessage psignature bresult debuglogwarning _t m_scollectionname m_pabycollectionauthorkey m_pabycollectionauthorkey m_nkeysize m_scollectionauthorname _t debuglog _t m_scollectionname m_scollectionauthorname _t cfileexception bcollectionloaded cstdiofile sfilepath cfile moderead cfile sharedenywrite cfile typetext cstring slink readstring slink slink _t ccollectionfile pcollectionfile ccollectionfile pcollectionfile initfromlink slink addfiletocollection pcollectionfile pcollectionfile m_scollectionname sfilename bcollectionloaded m_btextformat cfileexception bcollectionloaded c collection file c collection add file to collection c abstract file p abstract file bool b create clone cs key key p abstract file get file hash c collection file p collection file if m collectionfilesmap lookup key p collection file assert 0 return p collection file p collection file null if b create clone p collection file new c collection file p abstract file else if p abstract file is kind of runtime class c collection file p collection file c collection file p abstract file if p collection file m collectionfilesmap set at key p collection file return p collection file ccollectionfile ccollection addfiletocollection cabstractfile pabstractfile bcreateclone cskey pabstractfile getfilehash ccollectionfile pcollectionfile m_collectionfilesmap pcollectionfile pcollectionfile pcollectionfile bcreateclone pcollectionfile ccollectionfile pabstractfile pabstractfile iskindof runtime_class ccollectionfile pcollectionfile ccollectionfile pabstractfile pcollectionfile m_collectionfilesmap setat pcollectionfile pcollectionfile void c collection remove file from collection c abstract file p abstract file cs key key p abstract file get file hash c collection file p collection file if m collectionfilesmap lookup key p collection file m collectionfilesmap remove key key delete p collection file else assert 0 ccollection removefilefromcollection cabstractfile pabstractfile cskey pabstractfile getfilehash ccollectionfile pcollectionfile m_collectionfilesmap pcollectionfile m_collectionfilesmap removekey pcollectionfile void c collection set collection author key const byte aby collection author key uint32 n size delete m pabycollectionauthorkey m pabycollectionauthorkey null m nkeysize 0 if aby collection author key null m pabycollectionauthorkey new byte n size memcpy m pabycollectionauthorkey aby collection author key n size m nkeysize n size ccollection setcollectionauthorkey abycollectionauthorkey nsize m_pabycollectionauthorkey m_pabycollectionauthorkey m_nkeysize abycollectionauthorkey m_pabycollectionauthorkey nsize m_pabycollectionauthorkey abycollectionauthorkey nsize m_nkeysize nsize c string c collection get collection author key string if m pabycollectionauthorkey null return encode base16 m pabycollectionauthorkey m nkeysize else return c string t cstring ccollection getcollectionauthorkeystring m_pabycollectionauthorkey encodebase16 m_pabycollectionauthorkey m_nkeysize cstring _t bool c collection has collection extention const c string s file name if s file name find collection fileextension 1 return false return true ccollection hascollectionextention cstring sfilename sfilename collection_fileextension c string c collection get author key hash string if m pabycollectionauthorkey null md5 sum md5 m pabycollectionauthorkey m nkeysize c string str result md5 get hash str result make upper return str result return c string t cstring ccollection getauthorkeyhashstring m_pabycollectionauthorkey md5sum m_pabycollectionauthorkey m_nkeysize cstring strresult gethash strresult makeupper strresult cstring _t c server c server const servermet struct in data port in data port ip in data ip tcscpy ipfull ipstr ip files 0 users 0 m upreference 0 ping 0 failedcount 0 lastpinged 0 lastpingedtime 0 staticservermember false maxusers 0 softfiles 0 hardfiles 0 lastdescpingedcout 0 m utcpflags 0 m uudpflags 0 m udescreqchallenge 0 m ulowidusers 0 challenge 0 cserver cserver servermet_struct in_data in_data in_data _tcscpy m_upreference m_utcpflags m_uudpflags m_udescreqchallenge m_ulowidusers c server c server uint16 in port lpctstr i addr uses conversion port in port if ip inet addr t2ca i addr inaddr none tcscmp i addr t 255 255 255 255 0 m strdynip i addr ip 0 tcscpy ipfull ipstr ip files 0 users 0 m upreference 0 ping 0 failedcount 0 lastpinged 0 lastpingedtime 0 staticservermember false maxusers 0 softfiles 0 hardfiles 0 lastdescpingedcout 0 m utcpflags 0 m uudpflags 0 m udescreqchallenge 0 m ulowidusers 0 challenge 0 cserver cserver in_port i_addr uses_conversion in_port inet_addr i_addr inaddr_none _tcscmp i_addr _t m_strdynip i_addr _tcscpy m_upreference m_utcpflags m_uudpflags m_udescreqchallenge m_ulowidusers c server c server const c server p old port p old port ip p old ip staticservermember p old is static member tcscpy ipfull p old ipfull files p old files users p old users m upreference p old m upreference ping p old ping failedcount p old failedcount lastpinged p old lastpinged lastpingedtime p old lastpingedtime maxusers p old maxusers softfiles p old softfiles hardfiles p old hardfiles lastdescpingedcout p old lastdescpingedcout m strdescription p old m strdescription m strname p old m strname m strdynip p old m strdynip m strversion p old m strversion m utcpflags p old m utcpflags m uudpflags p old m uudpflags m udescreqchallenge p old m udescreqchallenge m ulowidusers p old m ulowidusers challenge p old challenge cserver cserver cserver pold pold pold pold isstaticmember _tcscpy pold pold pold m_upreference pold m_upreference pold pold pold pold pold pold pold pold m_strdescription pold m_strdescription m_strname pold m_strname m_strdynip pold m_strdynip m_strversion pold m_strversion m_utcpflags pold m_utcpflags m_uudpflags pold m_uudpflags m_udescreqchallenge pold m_udescreqchallenge m_ulowidusers pold m_ulowidusers pold c server c server cserver cserver bool c server add tag from file c file dataio servermet c tag tag new c tag servermet false switch tag get nameid case st servername assert tag is str if tag is str if m strname is empty m strname tag get str break case st description assert tag is str if tag is str if m strdescription is empty m strdescription tag get str break case st ping assert tag is int if tag is int ping tag get int break case st fail assert tag is int if tag is int failedcount tag get int break case st preference assert tag is int if tag is int m upreference tag get int break case st dynip assert tag is str if tag is str if m strdynip is empty m strdynip tag get str break case st maxusers assert tag is int if tag is int maxusers tag get int break case st softfiles assert tag is int if tag is int softfiles tag get int break case st hardfiles assert tag is int if tag is int hardfiles tag get int break case st lastping assert tag is int if tag is int lastpingedtime tag get int break case st version if tag is str if m strversion is empty m strversion tag get str else if tag is int m strversion format t u u tag get int 16 tag get int 0xffff else assert 0 break case st udpflags assert tag is int if tag is int m uudpflags tag get int break case st lowidusers assert tag is int if tag is int m ulowidusers tag get int break case st port assert tag is int break case st ip assert tag is int break default if tag get nameid 0 cmped2k tag name tag get name files assert tag is int if tag is int files tag get int else if tag get nameid 0 cmped2k tag name tag get name users assert tag is int if tag is int users tag get int else trace t unknown tag in server met s n tag get full info delete tag return true cserver addtagfromfile cfiledataio ctag ctag getnameid st_servername isstr isstr m_strname isempty m_strname getstr st_description isstr isstr m_strdescription isempty m_strdescription getstr st_ping isint isint getint st_fail isint isint getint st_preference isint isint m_upreference getint st_dynip isstr isstr m_strdynip isempty m_strdynip getstr st_maxusers isint isint getint st_softfiles isint isint getint st_hardfiles isint isint getint st_lastping isint isint getint st_version isstr m_strversion isempty m_strversion getstr isint m_strversion _t getint getint st_udpflags isint isint m_uudpflags getint st_lowidusers isint isint m_ulowidusers getint st_port isint st_ip isint getnameid cmped2ktagname getname isint isint getint getnameid cmped2ktagname getname isint isint getint _t getfullinfo void c server set list name lpctstr newname m strname newname cserver setlistname m_strname void c server set description lpctstr newname m strdescription newname cserver setdescription m_strdescription void c server setip uint32 newip ip newip tcscpy ipfull ipstr ip cserver _tcscpy void c server set dynip lpctstr newdynip m strdynip newdynip cserver setdynip m_strdynip lpctstr c server get address const if m strdynip is empty return m strdynip else return ipfull cserver getaddress m_strdynip isempty m_strdynip void c server set last desc pinged count bool b reset if b reset lastdescpingedcout 0 else lastdescpingedcout cserver setlastdescpingedcount breset breset bool c server is equal const c server p server const if get port p server get port return false if has dynip p server has dynip return get dynip compare no case p server get dynip 0 if has dynip p server has dynip return false return getip p server getip cserver isequal cserver pserver getport pserver getport hasdynip pserver hasdynip getdynip comparenocase pserver getdynip hasdynip pserver hasdynip pserver c server list ctrl c server list ctrl server list null set general purpose find true m tooltip new c tool tip ctrlx cserverlistctrl cserverlistctrl server_list setgeneralpurposefind m_tooltip ctooltipctrlx c server list ctrl c server list ctrl delete m tooltip cserverlistctrl cserverlistctrl m_tooltip bool c server list ctrl init c server list in list set name t server list ctrl server list in list modify style 0 lvs singlesel lvs report modify style lvs singlesel lvs list lvs icon lvs smallicon lvs report here the c list ctrl is set to report style set extended style get extended style lvs ex infotip c tool tip ctrl tooltip get tool tips if tooltip m tooltip subclass window tooltip tooltip modify style 0 tts noprefix tooltip set delay time ttdt autopop 20000 tooltip set delay time ttdt initial the prefs get tool tip delay 1000 insert column 0 get res string ids sl servername lvcfmt left 150 insert column 1 get res string ids ip lvcfmt left 140 insert column 2 get res string ids description lvcfmt left 150 insert column 3 get res string ids ping lvcfmt right 50 insert column 4 get res string ids uusers lvcfmt right 50 insert column 5 get res string ids maxclient lvcfmt right 50 insert column 6 get res string ids pw files lvcfmt right 50 insert column 7 get res string ids preference lvcfmt left 60 insert column 8 get res string ids ufailed lvcfmt right 50 insert column 9 get res string ids staticserver lvcfmt left 50 insert column 10 get res string ids softfiles lvcfmt right 50 insert column 11 get res string ids hardfiles lvcfmt right 50 insert column 12 get res string ids version lvcfmt left 50 insert column 13 get res string ids idlow lvcfmt right 50 set all icons localize load settings barry use preferred sort order from preferences set sort arrow sort items sort proc makelong get sort item get sort ascending 0 0x0001 show server count return true cserverlistctrl cserverlist in_list setname _t serverlistctrl server_list in_list modifystyle lvs_singlesel lvs_report modifystyle lvs_singlesel lvs_list lvs_icon lvs_smallicon lvs_report clistctrl setextendedstyle getextendedstyle lvs_ex_infotip ctooltipctrl gettooltips m_tooltip subclasswindow modifystyle tts_noprefix setdelaytime ttdt_autopop setdelaytime ttdt_initial theprefs gettooltipdelay insertcolumn getresstring ids_sl_servername lvcfmt_left insertcolumn getresstring ids_ip lvcfmt_left insertcolumn getresstring ids_description lvcfmt_left insertcolumn getresstring ids_ping lvcfmt_right insertcolumn getresstring ids_uusers lvcfmt_right insertcolumn getresstring ids_maxclient lvcfmt_right insertcolumn getresstring ids_pw_files lvcfmt_right insertcolumn getresstring ids_preference lvcfmt_left insertcolumn getresstring ids_ufailed lvcfmt_right insertcolumn getresstring ids_staticserver lvcfmt_left insertcolumn getresstring ids_softfiles lvcfmt_right insertcolumn getresstring ids_hardfiles lvcfmt_right insertcolumn getresstring ids_version lvcfmt_left insertcolumn getresstring ids_idlow lvcfmt_right setallicons loadsettings setsortarrow sortitems sortproc getsortitem getsortascending showservercount bool c server list ctrl add server const c server p server bool b add to list if server list add server p server return false if b add to list insert item lvif text lvif param get item count p server get list name 0 0 1 lparam p server refresh server p server show server count return true cserverlistctrl addserver cserver pserver baddtolist server_list addserver pserver baddtolist insertitem lvif_text lvif_param getitemcount pserver getlistname pserver refreshserver pserver showservercount void c server list ctrl remove server const c server p server lvfindinfo find find flags lvfi param find l param lparam p server int i item find item find if i item 1 server list remove server p server delete item i item show server count cserverlistctrl removeserver cserver pserver lvfi_param lparam pserver iitem finditem iitem server_list removeserver pserver deleteitem iitem showservercount bool c server list ctrl add server met to list const c string str file set redraw false bool b result server list add server met to list str file true remove all dead servers show server count set redraw true return b result cserverlistctrl addservermettolist cstring strfile setredraw bresult server_list addservermettolist strfile removealldeadservers showservercount setredraw bresult void c server list ctrl refresh server const c server server if server the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam server int itemnr find item find if itemnr 1 return c string temp temp format t s i server get address server get port set item text itemnr 1 temp set item text itemnr 0 server get list name set item text itemnr 2 server get description ping if server get ping temp format t i server get ping set item text itemnr 3 temp else set item text itemnr 3 t users if server get users set item text itemnr 4 cast itoi short server get users else set item text itemnr 4 t max users if server get max users set item text itemnr 5 cast itoi short server get max users else set item text itemnr 5 t files if server get files set item text itemnr 6 cast itoi short server get files else set item text itemnr 6 t switch server get preference case srv pr low set item text itemnr 7 get res string ids priolow break case srv pr normal set item text itemnr 7 get res string ids prionormal break case srv pr high set item text itemnr 7 get res string ids priohigh break default set item text itemnr 7 get res string ids prionopref failed count temp format t i server get failed count set item text itemnr 8 temp static server if server is static member set item text itemnr 9 get res string ids yes else set item text itemnr 9 get res string ids no soft files if server get soft files set item text itemnr 10 cast itoi short server get soft files else set item text itemnr 10 t hard files if server get hard files set item text itemnr 11 cast itoi short server get hard files else set item text itemnr 11 t temp server get version if the prefs get debug serverudp level 0 if server getudp flags 0 if temp is empty temp t temp append format t extudp x server getudp flags if the prefs get debug servertcp level 0 if server gettcp flags 0 if temp is empty temp t temp append format t exttcp x server gettcp flags set item text itemnr 12 temp lowid users if server get lowid users set item text itemnr 13 cast itoi short server get lowid users else set item text itemnr 13 t cserverlistctrl refreshserver cserver theapp isrunning lvfi_param lparam finditem cstring _t getaddress getport setitemtext setitemtext getlistname setitemtext getdescription getping _t getping setitemtext setitemtext _t getusers setitemtext castitoishort getusers setitemtext _t getmaxusers setitemtext castitoishort getmaxusers setitemtext _t getfiles setitemtext castitoishort getfiles setitemtext _t getpreference srv_pr_low setitemtext getresstring ids_priolow srv_pr_normal setitemtext getresstring ids_prionormal srv_pr_high setitemtext getresstring ids_priohigh setitemtext getresstring ids_prionopref _t getfailedcount setitemtext isstaticmember setitemtext getresstring ids_yes setitemtext getresstring ids_no getsoftfiles setitemtext castitoishort getsoftfiles setitemtext _t gethardfiles setitemtext castitoishort gethardfiles setitemtext _t getversion theprefs getdebugserverudplevel getudpflags isempty _t appendformat _t getudpflags theprefs getdebugservertcplevel gettcpflags isempty _t appendformat _t gettcpflags setitemtext getlowidusers setitemtext castitoishort getlowidusers setitemtext _t void c server list ctrl remove all dead servers show window sw hide for position pos server list list get head position pos null server list list get next pos const c server cur server server list list get at pos if cur server get failed count the prefs get dead server retries remove server cur server pos server list list get head position show window sw show cserverlistctrl removealldeadservers showwindow sw_hide server_list getheadposition server_list getnext cserver cur_server server_list getat cur_server getfailedcount theprefs getdeadserverretries removeserver cur_server server_list getheadposition showwindow sw_show void c server list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res str res get res string ids sl servername hdi psz text const cast lptstr lpctstr str res p header ctrl set item 0 hdi str res get res string ids ip hdi psz text const cast lptstr lpctstr str res p header ctrl set item 1 hdi str res get res string ids description hdi psz text const cast lptstr lpctstr str res p header ctrl set item 2 hdi str res get res string ids ping hdi psz text const cast lptstr lpctstr str res p header ctrl set item 3 hdi str res get res string ids uusers hdi psz text const cast lptstr lpctstr str res p header ctrl set item 4 hdi str res get res string ids maxclient hdi psz text const cast lptstr lpctstr str res p header ctrl set item 5 hdi str res get res string ids pw files hdi psz text const cast lptstr lpctstr str res p header ctrl set item 6 hdi str res get res string ids preference hdi psz text const cast lptstr lpctstr str res p header ctrl set item 7 hdi str res get res string ids ufailed hdi psz text const cast lptstr lpctstr str res p header ctrl set item 8 hdi str res get res string ids staticserver hdi psz text const cast lptstr lpctstr str res p header ctrl set item 9 hdi str res get res string ids softfiles hdi psz text const cast lptstr lpctstr str res p header ctrl set item 10 hdi str res get res string ids hardfiles hdi psz text const cast lptstr lpctstr str res p header ctrl set item 11 hdi str res get res string ids version hdi psz text const cast lptstr lpctstr str res p header ctrl set item 12 hdi str res get res string ids idlow hdi psz text const cast lptstr lpctstr str res p header ctrl set item 13 hdi int i items get item count for int i 0 i i items i refresh server c server get item data i cserverlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres strres getresstring ids_sl_servername psztext const_cast strres pheaderctrl setitem strres getresstring ids_ip psztext const_cast strres pheaderctrl setitem strres getresstring ids_description psztext const_cast strres pheaderctrl setitem strres getresstring ids_ping psztext const_cast strres pheaderctrl setitem strres getresstring ids_uusers psztext const_cast strres pheaderctrl setitem strres getresstring ids_maxclient psztext const_cast strres pheaderctrl setitem strres getresstring ids_pw_files psztext const_cast strres pheaderctrl setitem strres getresstring ids_preference psztext const_cast strres pheaderctrl setitem strres getresstring ids_ufailed psztext const_cast strres pheaderctrl setitem strres getresstring ids_staticserver psztext const_cast strres pheaderctrl setitem strres getresstring ids_softfiles psztext const_cast strres pheaderctrl setitem strres getresstring ids_hardfiles psztext const_cast strres pheaderctrl setitem strres getresstring ids_version psztext const_cast strres pheaderctrl setitem strres getresstring ids_idlow psztext const_cast strres pheaderctrl setitem iitems getitemcount iitems refreshserver cserver getitemdata void c server list ctrl show server count c string counter counter format t i get item count the app emuledlg serverwnd get dlg item idc servlist text set window text get res string ids sv serverlist counter cserverlistctrl showservercount cstring _t getitemcount theapp getdlgitem idc_servlist_text setwindowtext getresstring ids_sv_serverlist bool c server list ctrl static server file append c server server try remove any entry before writing to avoid duplicates static server file remove server file staticservers tfsopen the prefs get config dir t staticservers dat t a sh denywr if staticservers null log error log statusbar get res string ids error ssf return false if ftprintf staticservers t s i i s n server get address server get port server get preference server get list name eof add log line false t s i s s server get address server get port server get list name get res string ids added2ssf server set is static member true the app emuledlg serverwnd serverlistctrl refresh server server fclose staticservers catch assert 0 return false return true cserverlistctrl staticserverfileappend cserver staticserverfileremove _tfsopen theprefs getconfigdir _t _t _sh_denywr logerror log_statusbar getresstring ids_error_ssf _ftprintf _t getaddress getport getpreference getlistname addlogline _t getaddress getport getlistname getresstring ids_added2ssf setisstaticmember theapp refreshserver bool c server list ctrl static server file remove c server server bool removed false try if server is static member return true c string str line c string str test tchar buffer 1024 int len buf 1024 int pos c string static file path the prefs get config dir t staticservers dat c string static temp path the prefs get config dir t statictemp dat file staticservers tfsopen static file path t r sh denywr file statictemp tfsopen static temp path t w sh denywr if staticservers null statictemp null if staticservers fclose staticservers if statictemp fclose statictemp log error log statusbar get res string ids error ssf return false while feof staticservers if fgetts buffer len buf staticservers 0 break str line buffer ignore comments or invalid lines if str line get at 0 t str line get at 0 t continue if str line get length 5 continue only interested in host port pos str line find t if pos 1 continue str line str line left pos get host and port from given server str test format t s i server get address server get port compare if not the same server write original line to temp file if str line compare str test 0 ftprintf statictemp buffer else server set is static member false removed true fclose staticservers fclose statictemp all ok remove the existing file and replace with the new one c file remove static file path c file rename static temp path static file path catch assert 0 return false return removed cserverlistctrl staticserverfileremove cserver isstaticmember cstring strline cstring strtest lenbuf cstring staticfilepath theprefs getconfigdir _t cstring statictemppath theprefs getconfigdir _t _tfsopen staticfilepath _t _sh_denywr _tfsopen statictemppath _t _sh_denywr logerror log_statusbar getresstring ids_error_ssf _fgetts lenbuf strline strline getat _t strline getat _t strline getlength strline _t strline strline strtest _t getaddress getport strline strtest _ftprintf setisstaticmember cfile staticfilepath cfile statictemppath staticfilepath void c server list ctrl set selected servers priority uint u priority bool b update static servers file false position pos get first selected item position while pos null c server p server c server get item data get next selected item pos if p server get preference u priority p server set preference u priority if p server is static member b update static servers file true the app emuledlg serverwnd serverlistctrl refresh server p server if b update static servers file server list save static servers cserverlistctrl setselectedserverspriority upriority bupdatestaticserversfile getfirstselecteditemposition cserver pserver cserver getitemdata getnextselecteditem pserver getpreference upriority pserver setpreference upriority pserver isstaticmember bupdatestaticserversfile theapp refreshserver pserver bupdatestaticserversfile server_list savestaticservers void c server list ctrl set all icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t server himagelist himl apply image list iml detach if himl imagelist destroy himl cserverlistctrl setallicons cimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t applyimagelist imagelist_destroy int c server list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort const c server item1 c server l param1 const c server item2 c server l param2 if item1 null item2 null return 0 define undefined str at bottom s1 s2 if s1 is empty s2 is empty return 0 if s1 is empty return 1 if s2 is empty return 1 define undefined int at bottom i1 i2 if i1 i2 return 0 if i1 0 return 1 if i2 0 return 1 int i result switch loword l param sort case 0 undefined str at bottom item1 get list name item2 get list name i result item1 get list name compare no case item2 get list name break case 1 if item1 has dynip item2 has dynip i result item1 get dynip compare no case item2 get dynip else if item1 has dynip i result 1 else if item2 has dynip i result 1 else uint32 uip1 htonl item1 getip uint32 uip2 htonl item2 getip if uip1 uip2 i result 1 else if uip1 uip2 i result 1 else i result compare unsigned item1 get port item2 get port break case 2 undefined str at bottom item1 get description item2 get description i result item1 get description compare no case item2 get description break case 3 undefined int at bottom item1 get ping item2 get ping i result compare unsigned item1 get ping item2 get ping break case 4 undefined int at bottom item1 get users item2 get users i result compare unsigned item1 get users item2 get users break case 5 undefined int at bottom item1 get max users item2 get max users i result compare unsigned item1 get max users item2 get max users break case 6 undefined int at bottom item1 get files item2 get files i result compare unsigned item1 get files item2 get files break case 7 if item2 get preference item1 get preference i result 0 else if item2 get preference srv pr low i result 1 else if item1 get preference srv pr low i result 1 else if item2 get preference srv pr high i result 1 else if item1 get preference srv pr high i result 1 else i result 0 break case 8 i result compare unsigned item1 get failed count item2 get failed count break case 9 i result int item1 is static member int item2 is static member break case 10 undefined int at bottom item1 get soft files item2 get soft files i result compare unsigned item1 get soft files item2 get soft files break case 11 undefined int at bottom item1 get hard files item2 get hard files i result compare unsigned item1 get hard files item2 get hard files break case 12 undefined str at bottom item1 get version item2 get version i result item1 get version compare no case item2 get version break case 13 undefined int at bottom item1 get lowid users item2 get lowid users i result compare unsigned item1 get lowid users item2 get lowid users break default i result 0 int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if i result 0 dw next sort the app emuledlg serverwnd serverlistctrl get next sort order l param sort 1 i result sort proc l param1 l param2 dw next sort if hiword l param sort i result i result return i result cserverlistctrl sortproc lparam1 lparam2 lparamsort cserver cserver lparam1 cserver cserver lparam2 undefined_str_at_bottom isempty isempty isempty isempty undefined_int_at_bottom iresult lparamsort undefined_str_at_bottom getlistname getlistname iresult getlistname comparenocase getlistname hasdynip hasdynip iresult getdynip comparenocase getdynip hasdynip iresult hasdynip iresult iresult iresult iresult compareunsigned getport getport undefined_str_at_bottom getdescription getdescription iresult getdescription comparenocase getdescription undefined_int_at_bottom getping getping iresult compareunsigned getping getping undefined_int_at_bottom getusers getusers iresult compareunsigned getusers getusers undefined_int_at_bottom getmaxusers getmaxusers iresult compareunsigned getmaxusers getmaxusers undefined_int_at_bottom getfiles getfiles iresult compareunsigned getfiles getfiles getpreference getpreference iresult getpreference srv_pr_low iresult getpreference srv_pr_low iresult getpreference srv_pr_high iresult getpreference srv_pr_high iresult iresult iresult compareunsigned getfailedcount getfailedcount iresult isstaticmember isstaticmember undefined_int_at_bottom getsoftfiles getsoftfiles iresult compareunsigned getsoftfiles getsoftfiles undefined_int_at_bottom gethardfiles gethardfiles iresult compareunsigned gethardfiles gethardfiles undefined_str_at_bottom getversion getversion iresult getversion comparenocase getversion undefined_int_at_bottom getlowidusers getlowidusers iresult compareunsigned getlowidusers getlowidusers iresult dwnextsort iresult dwnextsort theapp getnextsortorder lparamsort iresult sortproc lparam1 lparam2 dwnextsort lparamsort iresult iresult iresult bool c server list ctrl on command wparam w param lparam l param w param loword w param if w param mp removeall if afx message box get res string ids removeallservers mb iconquestion mb yesno mb defbutton2 idyes return true if the app serverconnect is connecting the app downloadqueue stopudp requests the app serverconnect stop connection try the app serverconnect disconnect the app emuledlg show connection state show window sw hide server list remove all servers delete all items show window sw show show server count return true else if w param mp find on find start return true else if w param mp paste if the app is ed2k server link in clipboard the app emuledlg serverwnd paste server from clipboard return true int item get next item 1 lvis selected lvis focused if item 1 if c server get item data item null switch w param case mp connectto case ida enter if get selected count 1 c server a server the app serverconnect disconnect position pos get first selected item position while pos null item get next selected item pos if item 1 a server c server get item data item the app serverlist move server down a server the app serverconnect connect to any server the app serverlist get server count this get selected count false false else the app serverconnect connect to server c server get item data item the app emuledlg show connection state return true case mp remove case mpg delete set redraw false position pos while get first selected item position null pos get first selected item position item get next selected item pos server list remove server c server get item data item delete item item show server count set redraw true set focus auto select item return true case mp addtostatic position pos get first selected item position while pos null c server change c server get item data get next selected item pos if static server file append change return false the app emuledlg serverwnd serverlistctrl refresh server change return true case mp removefromstatic position pos get first selected item position while pos null c server change c server get item data get next selected item pos if static server file remove change return false the app emuledlg serverwnd serverlistctrl refresh server change return true case mp priolow set selected servers priority srv pr low return true case mp prionormal set selected servers priority srv pr normal return true case mp priohigh set selected servers priority srv pr high return true case mp copyselected case mp geted2klink position pos get first selected item position c string buffer link while pos null const c server change c server get item data get next selected item pos buffer format t ed2k server s d change get fullip change get port if link get length 0 buffer t r n buffer link buffer the app copy text to clipboard link return true case irc setsendlink position pos get first selected item position c string buffer link while pos null const c server change c server get item data get next selected item pos buffer format t ed2k server s d change get fullip change get port if link get length 0 buffer t r n buffer link buffer the app emuledlg ircwnd set send file string link return true return false cserverlistctrl oncommand wparam lparam wparam wparam wparam mp_removeall afxmessagebox getresstring ids_removeallservers mb_iconquestion mb_yesno mb_defbutton2 theapp isconnecting theapp stopudprequests theapp stopconnectiontry theapp theapp showconnectionstate showwindow sw_hide server_list removeallservers deleteallitems showwindow sw_show showservercount wparam mp_find onfindstart wparam mp_paste theapp ised2kserverlinkinclipboard theapp pasteserverfromclipboard getnextitem lvis_selected lvis_focused cserver getitemdata wparam mp_connectto ida_enter getselectedcount cserver aserver theapp getfirstselecteditemposition getnextselecteditem aserver cserver getitemdata theapp moveserverdown aserver theapp connecttoanyserver theapp getservercount getselectedcount theapp connecttoserver cserver getitemdata theapp showconnectionstate mp_remove mpg_delete setredraw getfirstselecteditemposition getfirstselecteditemposition getnextselecteditem server_list removeserver cserver getitemdata deleteitem showservercount setredraw setfocus autoselectitem mp_addtostatic getfirstselecteditemposition cserver cserver getitemdata getnextselecteditem staticserverfileappend theapp refreshserver mp_removefromstatic getfirstselecteditemposition cserver cserver getitemdata getnextselecteditem staticserverfileremove theapp refreshserver mp_priolow setselectedserverspriority srv_pr_low mp_prionormal setselectedserverspriority srv_pr_normal mp_priohigh setselectedserverspriority srv_pr_high mp_copyselected mp_geted2klink getfirstselecteditemposition cstring cserver cserver getitemdata getnextselecteditem _t getfullip getport getlength _t theapp copytexttoclipboard irc_setsendlink getfirstselecteditemposition cstring cserver cserver getitemdata getnextselecteditem _t getfullip getport getlength _t theapp setsendfilestring void c server list ctrl on sys color change c mule list ctrl on sys color change set all icons cserverlistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons void c server list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr barry store sort order in preferences determine ascending based on whether already sorted on this column bool b sort ascending get sort item pnm list view i sub item true get sort ascending sort table update sort history makelong pnm list view i sub item b sort ascending 0 0x0001 set sort arrow pnm list view i sub item b sort ascending sort items sort proc makelong pnm list view i sub item b sort ascending 0 0x0001 invalidate p result 0 cserverlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview bsortascending getsortitem pnmlistview isubitem getsortascending updatesorthistory pnmlistview isubitem bsortascending setsortarrow pnmlistview isubitem bsortascending sortitems sortproc pnmlistview isubitem bsortascending presult void c server list ctrl on context menu c wnd p wnd c point point get merged settings bool b first item true int i selected items get selected count int i static servers 0 uint u prio menu item 0 position pos get first selected item position while pos const c server p server c server get item data get next selected item pos i static servers p server is static member 1 0 uint u cur prio menu item 0 if p server get preference srv pr low u cur prio menu item mp priolow else if p server get preference srv pr normal u cur prio menu item mp prionormal else if p server get preference srv pr high u cur prio menu item mp priohigh else assert 0 if b first item u prio menu item u cur prio menu item else if u prio menu item u cur prio menu item u prio menu item 0 b first item false c title menu server menu server menu create popup menu server menu add menu title get res string ids em server true server menu append menu mf string i selected items 0 mf enabled mf grayed mp connectto get res string ids connectthis t connect server menu set default item i selected items 0 mp connectto 1 c menu server prio menu server prio menu create menu if i selected items 0 server prio menu append menu mf string mp priolow get res string ids priolow server prio menu append menu mf string mp prionormal get res string ids prionormal server prio menu append menu mf string mp priohigh get res string ids priohigh server prio menu check menu radio item mp priolow mp priohigh u prio menu item 0 server menu append menu mf popup i selected items 0 mf enabled mf grayed uint ptr server prio menu m hmenu get res string ids priority t priority enable add remove from static server list if there is at least one selected server which can be used for the action server menu append menu mf string i static servers i selected items mf enabled mf grayed mp addtostatic get res string ids addtostatic t list add server menu append menu mf string i static servers 0 mf enabled mf grayed mp removefromstatic get res string ids removefromstatic t list remove server menu append menu mf separator server menu append menu mf string i selected items 0 mf enabled mf grayed mp geted2klink get res string ids dl link1 t ed2klink server menu append menu mf string the app is ed2k server link in clipboard mf enabled mf grayed mp paste get res string ids sw directdownload t pastelink server menu append menu mf string i selected items 0 mf enabled mf grayed mp remove get res string ids removethis t deleteselected server menu append menu mf string get item count 0 mf enabled mf grayed mp removeall get res string ids removeall t delete server menu append menu mf separator server menu append menu mf enabled get item count 0 mf enabled mf grayed mp find get res string ids find t search get popup menu pos this point server menu track popup menu tpm leftalign tpm rightbutton point x point y this verify server prio menu destroy menu verify server menu destroy menu cserverlistctrl oncontextmenu cwnd pwnd cpoint bfirstitem iselecteditems getselectedcount istaticservers upriomenuitem getfirstselecteditemposition cserver pserver cserver getitemdata getnextselecteditem istaticservers pserver isstaticmember ucurpriomenuitem pserver getpreference srv_pr_low ucurpriomenuitem mp_priolow pserver getpreference srv_pr_normal ucurpriomenuitem mp_prionormal pserver getpreference srv_pr_high ucurpriomenuitem mp_priohigh bfirstitem upriomenuitem ucurpriomenuitem upriomenuitem ucurpriomenuitem upriomenuitem bfirstitem ctitlemenu servermenu servermenu createpopupmenu servermenu addmenutitle getresstring ids_em_server servermenu appendmenu mf_string iselecteditems mf_enabled mf_grayed mp_connectto getresstring ids_connectthis _t servermenu setdefaultitem iselecteditems mp_connectto cmenu serverpriomenu serverpriomenu createmenu iselecteditems serverpriomenu appendmenu mf_string mp_priolow getresstring ids_priolow serverpriomenu appendmenu mf_string mp_prionormal getresstring ids_prionormal serverpriomenu appendmenu mf_string mp_priohigh getresstring ids_priohigh serverpriomenu checkmenuradioitem mp_priolow mp_priohigh upriomenuitem servermenu appendmenu mf_popup iselecteditems mf_enabled mf_grayed uint_ptr serverpriomenu m_hmenu getresstring ids_priority _t servermenu appendmenu mf_string istaticservers iselecteditems mf_enabled mf_grayed mp_addtostatic getresstring ids_addtostatic _t listadd servermenu appendmenu mf_string istaticservers mf_enabled mf_grayed mp_removefromstatic getresstring ids_removefromstatic _t listremove servermenu appendmenu mf_separator servermenu appendmenu mf_string iselecteditems mf_enabled mf_grayed mp_geted2klink getresstring ids_dl_link1 _t servermenu appendmenu mf_string theapp ised2kserverlinkinclipboard mf_enabled mf_grayed mp_paste getresstring ids_sw_directdownload _t servermenu appendmenu mf_string iselecteditems mf_enabled mf_grayed mp_remove getresstring ids_removethis _t servermenu appendmenu mf_string getitemcount mf_enabled mf_grayed mp_removeall getresstring ids_removeall _t servermenu appendmenu mf_separator servermenu appendmenu mf_enabled getitemcount mf_enabled mf_grayed mp_find getresstring ids_find _t getpopupmenupos servermenu trackpopupmenu tpm_leftalign tpm_rightbutton serverpriomenu destroymenu servermenu destroymenu void c server list ctrl onnm ldblclk nmhdr pnmhdr lresult p result int i sel get next item 1 lvis selected lvis focused if i sel 1 the app serverconnect connect to server c server get item data i sel the app emuledlg show connection state cserverlistctrl onnmldblclk presult isel getnextitem lvis_selected lvis_focused isel theapp connecttoserver cserver getitemdata isel theapp showconnectionstate void c server list ctrl on lvn get info tip nmhdr pnmhdr lresult p result lpnmlvgetinfotip p get info tip reinterpret cast lpnmlvgetinfotip pnmhdr if p get info tip i sub item 0 lvhittestinfo hti 0 get cursor pos hti pt screen to client hti pt bool b over main item sub item hit test hti 1 hti i item p get info tip i item hti i sub item 0 those tooltips are very nice for debugging testing but pretty annoying for general usage enable tooltips only if shift ctrl is currently pressed bool b show info tip get selected count 1 get key state vk shift 0x8000 get key state vk control 0x8000 if b show info tip if b over main item don show the default label tip for the main item if the mouse is not over the main item if p get info tip dw flags lvgit unfolded 0 p get info tip cch text max 0 p get info tip psz text 0 0 p get info tip psz text 0 0 return if get selected count 1 else int i selected 0 ulonglong ul total users 0 ulonglong ul total low id users 0 ulonglong ul total files 0 position pos get first selected item position while pos const c server p server c server get item data get next selected item pos if p server i selected ul total users p server get users ul total files p server get files ul total low id users p server get lowid users if i selected 0 c string str info str info format t s u r n s s r n s s r n s s get res string ids fstat servers i selected get res string ids uusers cast itoi short ul total users get res string ids idlow cast itoi short ul total low id users get res string ids pw files cast itoi short ul total files tcsncpy p get info tip psz text str info p get info tip cch text max p get info tip psz text p get info tip cch text max 1 t 0 p result 0 cserverlistctrl onlvngetinfotip presult pgetinfotip reinterpret_cast pgetinfotip isubitem getcursorpos screentoclient bovermainitem subitemhittest iitem pgetinfotip iitem isubitem bshowinfotip getselectedcount getkeystate vk_shift getkeystate vk_control bshowinfotip bovermainitem pgetinfotip dwflags lvgit_unfolded pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip psztext getselectedcount iselected ultotalusers ultotallowidusers ultotalfiles getfirstselecteditemposition cserver pserver cserver getitemdata getnextselecteditem pserver iselected ultotalusers pserver getusers ultotalfiles pserver getfiles ultotallowidusers pserver getlowidusers iselected cstring strinfo strinfo _t getresstring ids_fstat_servers iselected getresstring ids_uusers castitoishort ultotalusers getresstring ids_idlow castitoishort ultotallowidusers getresstring ids_pw_files castitoishort ultotalfiles _tcsncpy pgetinfotip psztext strinfo pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip cchtextmax _t presult void c server list ctrl onnm customdraw nmhdr pnmhdr lresult pl result lpnmlvcustomdraw pnmlvcd lpnmlvcustomdraw pnmhdr if pnmlvcd nmcd dw draw stage cdds prepaint pl result cdrf notifyitemdraw return if pnmlvcd nmcd dw draw stage cdds itemprepaint const c server p server const c server pnmlvcd nmcd l iteml param const c server p connected server the app serverconnect get current server the server which we are connected to always has a valid numerical ip member assigned therefor we do not need to call c server is equal which is little expensive if p connected server p connected server is equal p server if p connected server p connected server getip p server getip p connected server get port p server get port pnmlvcd clr text rgb 32 32 255 else if p server get failed count the prefs get dead server retries pnmlvcd clr text rgb 192 192 192 else if p server get failed count 2 pnmlvcd clr text rgb 128 128 128 pl result cdrf dodefault cserverlistctrl onnmcustomdraw plresult dwdrawstage cdds_prepaint plresult cdrf_notifyitemdraw dwdrawstage cdds_itemprepaint cserver pserver cserver litemlparam cserver pconnectedserver theapp getcurrentserver cserver isequal pconnectedserver pconnectedserver isequal pserver pconnectedserver pconnectedserver pserver pconnectedserver getport pserver getport clrtext pserver getfailedcount theprefs getdeadserverretries clrtext pserver getfailedcount clrtext plresult cdrf_dodefault c search dlg c search dlg m pwndparams new c search params wnd m pwndresults null csearchdlg csearchdlg m_pwndparams csearchparamswnd m_pwndresults c search dlg c search dlg delete m pwndparams csearchdlg csearchdlg m_pwndparams bool c search dlg create c wnd p parent the initial size of that frame window must not exceed the window size of the dialog resource template of the client window the search results window the dialog resource template s window size of the search results window must not exceed the minimum client area of the frame window otherwise we may get scrollbars in the search results window c rect rc 0 0 50 50 return c frame wnd create null t search ws child rc p parent null 0 null csearchdlg cwnd pparent crect cframewnd _t ws_child pparent void c search dlg localize m pwndresults localize m pwndparams localize csearchdlg m_pwndresults m_pwndparams void c search dlg create menus m pwndresults searchlistctrl create menues csearchdlg createmenus m_pwndresults createmenues void c search dlg remove result const c search file p file m pwndresults searchlistctrl remove result p file csearchdlg removeresult csearchfile pfile m_pwndresults removeresult pfile bool c search dlg do new ed2k search s search params p params return m pwndresults do new ed2k search p params csearchdlg donewed2ksearch ssearchparams pparams m_pwndresults donewed2ksearch pparams bool c search dlg do new kad search s search params p params return m pwndresults do new kad search p params csearchdlg donewkadsearch ssearchparams pparams m_pwndresults donewkadsearch pparams void c search dlg cancel ed2k search m pwndresults cancel ed2k search csearchdlg canceled2ksearch m_pwndresults canceled2ksearch void c search dlg cancel kad search uint u searchid m pwndresults cancel kad search u searchid csearchdlg cancelkadsearch usearchid m_pwndresults cancelkadsearch usearchid bool c search dlg can search related files const return m pwndresults can search related files csearchdlg cansearchrelatedfiles m_pwndresults cansearchrelatedfiles void c search dlg search related files const c abstract file file m pwndresults search related files file csearchdlg searchrelatedfiles cabstractfile m_pwndresults searchrelatedfiles void c search dlg download selected m pwndresults download selected csearchdlg downloadselected m_pwndresults downloadselected void c search dlg download selected bool b paused m pwndresults download selected b paused csearchdlg downloadselected bpaused m_pwndresults downloadselected bpaused bool c search dlg can delete search uint32 n searchid const return m pwndresults can delete search n searchid csearchdlg candeletesearch nsearchid m_pwndresults candeletesearch nsearchid bool c search dlg can delete all searches const return m pwndresults can delete all searches csearchdlg candeleteallsearches m_pwndresults candeleteallsearches void c search dlg delete search uint32 n searchid m pwndresults delete search n searchid csearchdlg deletesearch nsearchid m_pwndresults deletesearch nsearchid void c search dlg delete all searches m pwndresults delete all searches csearchdlg deleteallsearches m_pwndresults deleteallsearches void c search dlg local ed2k search end uint n count bool b more results available m pwndresults local ed2k search end n count b more results available csearchdlg localed2ksearchend ncount bmoreresultsavailable m_pwndresults localed2ksearchend ncount bmoreresultsavailable void c search dlg add global ed2k search results uint n count m pwndresults add global ed2k search results n count csearchdlg addglobaled2ksearchresults ncount m_pwndresults addglobaled2ksearchresults ncount bool c search dlg create new tab s search params p params return m pwndresults create new tab p params csearchdlg createnewtab ssearchparams pparams m_pwndresults createnewtab pparams c closable tab ctrl c search dlg get search selector return m pwndresults searchselect cclosabletabctrl csearchdlg getsearchselector m_pwndresults int c search dlg get selected cat return m pwndresults get selected cat csearchdlg getselectedcat m_pwndresults getselectedcat void c search dlg update cat tabs m pwndresults update cat tabs csearchdlg updatecattabs m_pwndresults updatecattabs void c search dlg save all settings m pwndparams save settings csearchdlg saveallsettings m_pwndparams savesettings void c search dlg reset history m pwndparams reset history csearchdlg resethistory m_pwndparams resethistory void c search dlg set tool tips delay uint u delay c tool tip ctrl tooltip m pwndresults searchlistctrl get tool tips if tooltip tooltip set delay time ttdt initial u delay csearchdlg settooltipsdelay udelay ctooltipctrl m_pwndresults gettooltips setdelaytime ttdt_initial udelay void c search dlg delete all search list ctrl items m pwndresults searchlistctrl delete all items csearchdlg deleteallsearchlistctrlitems m_pwndresults deleteallitems bool c search dlg is search params wnd visible const return m pwndparams is window visible csearchdlg issearchparamswndvisible m_pwndparams iswindowvisible void c search dlg open parameters wnd show control bar m pwndparams true true csearchdlg openparameterswnd showcontrolbar m_pwndparams void c search dlg dock parameters wnd if m pwndparams is floating uint umru dockid afx idw dockbar top if m pwndparams m pdockcontext umru dockid m pwndparams m pdockcontext m umrudockid dock control bar m pwndparams umru dockid csearchdlg dockparameterswnd m_pwndparams isfloating umrudockid afx_idw_dockbar_top m_pwndparams m_pdockcontext umrudockid m_pwndparams m_pdockcontext m_umrudockid dockcontrolbar m_pwndparams umrudockid void c search dlg update search c search file p search file if m pwndresults m pwndresults searchlistctrl update search p search file csearchdlg updatesearch csearchfile psearchfile m_pwndresults m_pwndresults updatesearch psearchfile bool c search dlg pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 ugly because this window is a c frame wnd rather than a c dialog like the other e mule main windows we can not use mfc s message routing need to explicitly send that message to the main window the app emuledlg post message p msg message p msg w param p msg l param return true return c frame wnd pre translate message p msg csearchdlg pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control cframewnd cdialog emule theapp postmessage pmsg pmsg wparam pmsg lparam cframewnd pretranslatemessage pmsg int c search dlg on create lpcreatestruct lp create struct if c frame wnd on create lp create struct 1 return 1 c create context context context m pcurrentframe this context m pcurrentdoc null context m pnewviewclass runtime class c search results wnd context m pnewdoctemplate null m pwndresults c search results wnd create view context m pwndparams m searchdlg m pwndresults m pwndresults modify style ws border 0 m pwndresults modify style ex ws ex clientedge ws ex staticedge m pwndparams create this idd search params ws child ws visible cbrs top cbrs size fixed cbrs size dynamic cbrs gripper idbar search params m pwndparams set window text get res string ids searchparams m pwndparams enable docking cbrs align any enable docking cbrs align any dock control bar m pwndparams afx idw dockbar top lprect null m pwndresults m pwndparams m pwndparams m pwndresults send message wm initialupdate load bar state search params profile dock parameters wnd too much bug reports about vanished search parameters window force to dock show control bar m pwndparams true true localize return 0 csearchdlg oncreate lpcreatestruct cframewnd oncreate lpcreatestruct ccreatecontext m_pcurrentframe m_pcurrentdoc m_pnewviewclass runtime_class csearchresultswnd m_pnewdoctemplate m_pwndresults csearchresultswnd createview m_pwndparams m_searchdlg m_pwndresults m_pwndresults modifystyle ws_border m_pwndresults modifystyleex ws_ex_clientedge ws_ex_staticedge m_pwndparams idd_search_params ws_child ws_visible cbrs_top cbrs_size_fixed cbrs_size_dynamic cbrs_gripper idbar_search_params m_pwndparams setwindowtext getresstring ids_searchparams m_pwndparams enabledocking cbrs_align_any enabledocking cbrs_align_any dockcontrolbar m_pwndparams afx_idw_dockbar_top m_pwndresults m_pwndparams m_pwndparams m_pwndresults sendmessage wm_initialupdate loadbarstate search_params_profile dockparameterswnd showcontrolbar m_pwndparams void c search dlg on show window bool b show uint n status c frame wnd on show window b show n status if m pwndparams is floating show control bar m pwndparams b show true dock parameters wnd too much bug reports about vanished search parameters window force to dock csearchdlg onshowwindow bshow nstatus cframewnd onshowwindow bshow nstatus m_pwndparams isfloating showcontrolbar m_pwndparams bshow dockparameterswnd void c search dlg on set focus c wnd p old wnd c frame wnd on set focus p old wnd if m pwndparams m hwnd m pwndparams set focus csearchdlg onsetfocus cwnd poldwnd cframewnd onsetfocus poldwnd m_pwndparams m_hwnd m_pwndparams setfocus void c search dlg on close save bar state search params profile c frame wnd on close csearchdlg onclose savebarstate search_params_profile cframewnd onclose void c search dlg on sys command uint nid lparam l param if nid sc keymenu if l param emule hotmenu accel the app emuledlg send message wm command idc hotmenu else the app emuledlg send message wm syscommand nid l param return c frame wnd on sys command nid l param csearchdlg onsyscommand lparam sc_keymenu lparam emule_hotmenu_accel theapp sendmessage wm_command idc_hotmenu theapp sendmessage wm_syscommand lparam cframewnd onsyscommand lparam c resizable dialog c server wnd idd p parent servermsgbox new cht rich edit ctrl logbox new cht rich edit ctrl debuglog new cht rich edit ctrl m pacservermeturl null m ulangid makelangid lang english sublang default icon srvlist null memset m cfdef 0 sizeof m cfdef memset m cfbold 0 sizeof m cfbold status selector m bcloseable false cresizabledialog cserverwnd pparent chtricheditctrl chtricheditctrl chtricheditctrl m_pacservermeturl m_ulangid lang_english sublang_default icon_srvlist m_cfdef m_cfdef m_cfbold m_cfbold statusselector m_bcloseable c server wnd c server wnd if icon srvlist verify destroy icon icon srvlist if m pacservermeturl m pacservermeturl unbind m pacservermeturl release delete debuglog delete logbox delete servermsgbox cserverwnd cserverwnd icon_srvlist destroyicon icon_srvlist m_pacservermeturl m_pacservermeturl m_pacservermeturl void c server wnd localize serverlistctrl localize if the prefs get languageid m ulangid m ulangid the prefs get languageid get dlg item idc servlist text set window text get res string ids sv serverlist m ctrlnewserverfrm set window text get res string ids sv newserver get dlg item idc sstatic4 set window text get res string ids sv address get dlg item idc sstatic7 set window text get res string ids sv port get dlg item idc sstatic3 set window text get res string ids sw name get dlg item idc addserver set window text get res string ids sv add m ctrlupdateserverfrm set window text get res string ids sv met get dlg item idc updateservermetfromurl set window text get res string ids sv update get dlg item idc logreset set window text get res string ids pw reset m ctrlmyinfofrm set window text get res string ids myinfo tcitem item c string name name get res string ids sv serverinfo item mask tcif text item psz text const cast lptstr lpctstr name status selector set item pane server info item name get res string ids sv log item mask tcif text item psz text const cast lptstr lpctstr name status selector set item pane log item name sz debug log title item mask tcif text item psz text const cast lptstr lpctstr name status selector set item pane verbose log item update log tab selection update controls state cserverwnd theprefs getlanguageid m_ulangid m_ulangid theprefs getlanguageid getdlgitem idc_servlist_text setwindowtext getresstring ids_sv_serverlist m_ctrlnewserverfrm setwindowtext getresstring ids_sv_newserver getdlgitem idc_sstatic4 setwindowtext getresstring ids_sv_address getdlgitem idc_sstatic7 setwindowtext getresstring ids_sv_port getdlgitem idc_sstatic3 setwindowtext getresstring ids_sw_name getdlgitem idc_addserver setwindowtext getresstring ids_sv_add m_ctrlupdateserverfrm setwindowtext getresstring ids_sv_met getdlgitem idc_updateservermetfromurl setwindowtext getresstring ids_sv_update getdlgitem idc_logreset setwindowtext getresstring ids_pw_reset m_ctrlmyinfofrm setwindowtext getresstring ids_myinfo cstring getresstring ids_sv_serverinfo tcif_text psztext const_cast statusselector setitem paneserverinfo getresstring ids_sv_log tcif_text psztext const_cast statusselector setitem panelog sz_debug_log_title tcif_text psztext const_cast statusselector setitem paneverboselog updatelogtabselection updatecontrolsstate bool c server wnd update server met fromurl c string strurl if strurl is empty strurl find t 1 not a valid url log error log statusbar get res string ids invalidurl return false add entered url to lru list even if it s not yet known whether we can download from this url it s just more convenient this way if m pacservermeturl m pacservermeturl is bound m pacservermeturl add item strurl 0 c string str temp filename str temp filename format t stemp d server met the prefs get config dir get tick count try to download server met log get res string ids downloading servermet from strurl c http download dlg dlg download dlg download m strtitle get res string ids downloading servermet dlg download m surltodownload strurl dlg download m sfiletodownloadinto str temp filename if dlg download do modal idok log error log statusbar get res string ids err faileddownloadmet strurl return false add content of server met to serverlist serverlistctrl hide serverlistctrl add server met to list str temp filename serverlistctrl visable tremove str temp filename return true cserverwnd updateservermetfromurl cstring isempty _t logerror log_statusbar getresstring ids_invalidurl m_pacservermeturl m_pacservermeturl isbound m_pacservermeturl additem cstring strtempfilename strtempfilename _t theprefs getconfigdir gettickcount getresstring ids_downloading_servermet_from chttpdownloaddlg dlgdownload dlgdownload m_strtitle getresstring ids_downloading_servermet dlgdownload m_surltodownload dlgdownload m_sfiletodownloadinto strtempfilename dlgdownload domodal logerror log_statusbar getresstring ids_err_faileddownloadmet addservermettolist strtempfilename _tremove strtempfilename void c server wnd toggle debug window int cur sel status selector get cur sel if the prefs get verbose debug tcitem newitem c string name name sz debug log title newitem mask tcif text tcif image newitem psz text const cast lptstr lpctstr name newitem i image 0 status selector insert item status selector get item count newitem debug true else if the prefs get verbose debug if cur sel pane verbose log status selector set cur sel pane log status selector set focus debuglog show window sw hide servermsgbox show window sw hide logbox show window sw show status selector delete item pane verbose log debug false cserverwnd toggledebugwindow cur_sel statusselector getcursel theprefs getverbose cstring sz_debug_log_title tcif_text tcif_image psztext const_cast iimage statusselector insertitem statusselector getitemcount theprefs getverbose cur_sel paneverboselog statusselector setcursel panelog statusselector setfocus showwindow sw_hide showwindow sw_hide showwindow sw_show statusselector deleteitem paneverboselog void c server wnd update my info m myinfo set redraw false m myinfo set window text t create network info m myinfo m cfdef m cfbold m myinfo set redraw true m myinfo invalidate cserverwnd updatemyinfo m_myinfo setredraw m_myinfo setwindowtext _t createnetworkinfo m_myinfo m_cfdef m_cfbold m_myinfo setredraw m_myinfo void c server wnd update log tab selection int cur sel status selector get cur sel if cur sel 1 return if cur sel pane verbose log servermsgbox show window sw hide logbox show window sw hide debuglog show window sw show if debuglog is auto scroll status selector get item state cur sel tcis highlighted tcis highlighted debuglog scroll to last line true debuglog invalidate status selector highlight item cur sel false if cur sel pane log debuglog show window sw hide servermsgbox show window sw hide logbox show window sw show if logbox is auto scroll status selector get item state cur sel tcis highlighted tcis highlighted logbox scroll to last line true logbox invalidate status selector highlight item cur sel false if cur sel pane server info debuglog show window sw hide logbox show window sw hide servermsgbox show window sw show if servermsgbox is auto scroll status selector get item state cur sel tcis highlighted tcis highlighted servermsgbox scroll to last line true servermsgbox invalidate status selector highlight item cur sel false cserverwnd updatelogtabselection cur_sel statusselector getcursel cur_sel cur_sel paneverboselog showwindow sw_hide showwindow sw_hide showwindow sw_show isautoscroll statusselector getitemstate cur_sel tcis_highlighted tcis_highlighted scrolltolastline statusselector highlightitem cur_sel cur_sel panelog showwindow sw_hide showwindow sw_hide showwindow sw_show isautoscroll statusselector getitemstate cur_sel tcis_highlighted tcis_highlighted scrolltolastline statusselector highlightitem cur_sel cur_sel paneserverinfo showwindow sw_hide showwindow sw_hide showwindow sw_show isautoscroll statusselector getitemstate cur_sel tcis_highlighted tcis_highlighted scrolltolastline statusselector highlightitem cur_sel void c server wnd save all settings the prefs set last log paneid status selector get cur sel save server met strings cserverwnd saveallsettings theprefs setlastlogpaneid statusselector getcursel saveservermetstrings bool c server wnd save server met strings if m pacservermeturl null return false return m pacservermeturl save list the prefs get config dir servermet strings profile cserverwnd saveservermetstrings m_pacservermeturl m_pacservermeturl savelist theprefs getconfigdir servermet_strings_profile void c server wnd show network info c network info dlg dlg dlg do modal cserverwnd shownetworkinfo cnetworkinfodlg domodal void c server wnd update controls state c string str label if the app serverconnect is connected str label get res string ids main btn disconnect else if the app serverconnect is connecting str label get res string ids main btn cancel else str label get res string ids main btn connect str label remove t get dlg item idc ed2kconnect set window text str label cserverwnd updatecontrolsstate cstring strlabel theapp isconnected strlabel getresstring ids_main_btn_disconnect theapp isconnecting strlabel getresstring ids_main_btn_cancel strlabel getresstring ids_main_btn_connect strlabel _t getdlgitem idc_ed2kconnect setwindowtext strlabel void c server wnd reset history if m pacservermeturl null return get dlg item idc servermeturl send message wm keydown vk escape 0x00510001 m pacservermeturl clear cserverwnd resethistory m_pacservermeturl getdlgitem idc_servermeturl sendmessage wm_keydown vk_escape m_pacservermeturl void c server wnd paste server from clipboard c string str server the app copy text from clipboard str server trim if str server is empty return int n pos 0 c string str tok str server tokenize t t r n n pos while str tok is empty uint32 nip 0 uint16 n port 0 ced2k link p link null try p link ced2k link create link from url str tok if p link p link get kind ced2k link k server ced2k server link p server link p link get server link if p server link nip p server link getip n port p server link get port catch c string str error afx message box str error delete p link if nip 0 n port 0 break void add server n port ipstr nip t false str tok str server tokenize t t r n n pos cserverwnd pasteserverfromclipboard cstring strserver theapp copytextfromclipboard strserver strserver isempty npos cstring strtok strserver _t npos strtok isempty nport ced2klink plink plink ced2klink createlinkfromurl strtok plink plink getkind ced2klink kserver ced2kserverlink pserverlink plink getserverlink pserverlink pserverlink nport pserverlink getport cstring strerror afxmessagebox strerror plink nport addserver nport _t strtok strserver _t npos bool c server wnd add server uint16 n port c string strip c string str name bool b show errormb c server toadd new c server n port strip barry default all manually added servers to high priority if the prefs get manual added servers high priority toadd set preference srv pr high if str name is empty str name strip toadd set list name str name if serverlistctrl add server toadd true c server update the app serverlist get server by address toadd get address toadd get port if update static const tchar aszserverprefix t server if tcsnicmp toadd get list name aszserverprefix arrsize aszserverprefix 1 0 update set list name toadd get list name serverlistctrl refresh server update else if b show errormb afx message box get res string ids srv notadded delete toadd return false else add log line true get res string ids serveradded toadd get list name return true cserverwnd addserver nport cstring cstring strname bshowerrormb cserver cserver nport theprefs getmanualaddedservershighpriority setpreference srv_pr_high strname isempty strname setlistname strname addserver cserver theapp getserverbyaddress getaddress getport _aszserverprefix _t _tcsnicmp getlistname _aszserverprefix _aszserverprefix setlistname getlistname refreshserver bshowerrormb afxmessagebox getresstring ids_srv_notadded addlogline getresstring ids_serveradded getlistname c string c server wnd get my info string c string buffer m myinfo get window text buffer return buffer cstring cserverwnd getmyinfostring cstring m_myinfo getwindowtext void c server wnd do resize int delta c splitter control change height serverlistctrl delta cw topalign c splitter control change height status selector delta cw bottomalign c splitter control change height servermsgbox delta cw bottomalign c splitter control change height logbox delta cw bottomalign c splitter control change height debuglog delta cw bottomalign update splitter range cserverwnd doresize csplittercontrol changeheight cw_topalign csplittercontrol changeheight statusselector cw_bottomalign csplittercontrol changeheight cw_bottomalign csplittercontrol changeheight cw_bottomalign csplittercontrol changeheight cw_bottomalign updatesplitterrange void c server wnd update splitter range c rect rc wnd get window rect rc wnd screen to client rc wnd c rect rc dlg item serverlistctrl get window rect rc dlg item screen to client rc dlg item m wndsplitter set range rc wnd top 100 rc wnd bottom 50 rc dlg item top rc dlg item2 bottom 50 long splitpos rc dlg item bottom svwnd splitter yoff the prefs set splitterbar position server splitpos 100 rc wnd height get dlg item idc logreset get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 9 rc dlg item bottom splitpos 30 get dlg item idc logreset move window rc dlg item reattach anchors cserverwnd updatesplitterrange crect rcwnd getwindowrect rcwnd screentoclient rcwnd crect rcdlgitem getwindowrect rcdlgitem screentoclient rcdlgitem m_wndsplitter setrange rcwnd rcwnd rcdlgitem rcdlgitem2 rcdlgitem svwnd_splitter_yoff theprefs setsplitterbarpositionserver rcwnd getdlgitem idc_logreset getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem getdlgitem idc_logreset movewindow rcdlgitem reattachanchors void c server wnd init splitter c rect rc wnd get window rect rc wnd screen to client rc wnd m wndsplitter set range rc wnd top 100 rc wnd bottom 50 long splitpos 5 the prefs get splitterbar position server rc wnd height 100 c rect rc dlg item serverlistctrl get window rect rc dlg item screen to client rc dlg item rc dlg item bottom splitpos 10 serverlistctrl move window rc dlg item get dlg item idc logreset get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 9 rc dlg item bottom splitpos 30 get dlg item idc logreset move window rc dlg item status selector get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 10 rc dlg item bottom rc wnd bottom 5 status selector move window rc dlg item servermsgbox get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 35 rc dlg item bottom rc wnd bottom 12 servermsgbox move window rc dlg item logbox get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 35 rc dlg item bottom rc wnd bottom 12 logbox move window rc dlg item debuglog get window rect rc dlg item screen to client rc dlg item rc dlg item top splitpos 35 rc dlg item bottom rc wnd bottom 12 debuglog move window rc dlg item long right rc dlg item right get dlg item idc splitter server get window rect rc dlg item screen to client rc dlg item rc dlg item right right get dlg item idc splitter server move window rc dlg item reattach anchors cserverwnd initsplitter crect rcwnd getwindowrect rcwnd screentoclient rcwnd m_wndsplitter setrange rcwnd rcwnd theprefs getsplitterbarpositionserver rcwnd crect rcdlgitem getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem movewindow rcdlgitem getdlgitem idc_logreset getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem getdlgitem idc_logreset movewindow rcdlgitem statusselector getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem rcwnd statusselector movewindow rcdlgitem getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem rcwnd movewindow rcdlgitem getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem rcwnd movewindow rcdlgitem getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem rcdlgitem rcwnd movewindow rcdlgitem rcdlgitem getdlgitem idc_splitter_server getwindowrect rcdlgitem screentoclient rcdlgitem rcdlgitem getdlgitem idc_splitter_server movewindow rcdlgitem reattachanchors void c server wnd reattach anchors remove anchor serverlistctrl remove anchor status selector remove anchor idc logreset remove anchor servermsgbox remove anchor logbox remove anchor debuglog add anchor serverlistctrl top left c size 100 the prefs get splitterbar position server add anchor status selector c size 0 the prefs get splitterbar position server bottom right add anchor idc logreset bottom right add anchor servermsgbox c size 0 the prefs get splitterbar position server bottom right add anchor logbox c size 0 the prefs get splitterbar position server bottom right add anchor debuglog c size 0 the prefs get splitterbar position server bottom right get dlg item idc logreset invalidate if servermsgbox is window visible servermsgbox invalidate if logbox is window visible logbox invalidate if debuglog is window visible debuglog invalidate cserverwnd reattachanchors removeanchor removeanchor statusselector removeanchor idc_logreset removeanchor removeanchor removeanchor addanchor top_left csize theprefs getsplitterbarpositionserver addanchor statusselector csize theprefs getsplitterbarpositionserver bottom_right addanchor idc_logreset bottom_right addanchor csize theprefs getsplitterbarpositionserver bottom_right addanchor csize theprefs getsplitterbarpositionserver bottom_right addanchor csize theprefs getsplitterbarpositionserver bottom_right getdlgitem idc_logreset iswindowvisible iswindowvisible iswindowvisible void c server wnd set all icons m ctrlnewserverfrm set icon t add server m ctrlupdateserverfrm set icon t server updatemet m ctrlmyinfofrm set icon t info c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml add c temp icon loader t log iml add c temp icon loader t server info status selector set image list iml m imllogpanes delete image list m imllogpanes attach iml detach if icon srvlist verify destroy icon icon srvlist icon srvlist the app load icon t server list 16 16 c static get dlg item idc servlst ico set icon icon srvlist cserverwnd setallicons m_ctrlnewserverfrm seticon _t addserver m_ctrlupdateserverfrm seticon _t serverupdatemet m_ctrlmyinfofrm seticon _t cimagelist theapp m_idfltimagelistcolorflags ilc_mask ctempiconloader _t ctempiconloader _t serverinfo statusselector setimagelist m_imllogpanes deleteimagelist m_imllogpanes icon_srvlist destroyicon icon_srvlist icon_srvlist theapp loadicon _t serverlist cstatic getdlgitem idc_servlst_ico seticon icon_srvlist void c server wnd do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc servlist serverlistctrl ddx control pdx idc sstatic m ctrlnewserverfrm ddx control pdx idc sstatic6 m ctrlupdateserverfrm ddx control pdx idc myinfo m ctrlmyinfofrm ddx control pdx idc tab3 status selector ddx control pdx idc myinfolist m myinfo cserverwnd dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_servlist ddx_control idc_sstatic m_ctrlnewserverfrm ddx_control idc_sstatic6 m_ctrlupdateserverfrm ddx_control idc_myinfo m_ctrlmyinfofrm ddx_control idc_tab3 statusselector ddx_control idc_myinfolist m_myinfo bool c server wnd on init dialog if the app m fontlog m hobject null c font p font get dlg item idc sstatic get font logfont lf p font get object sizeof lf lf the app m fontlog create font indirect lf replace rich edit ctrl get dlg item idc myinfolist this get dlg item idc sstatic get font c resizable dialog on init dialog using es nohidesel is actually not needed but it helps to get around a tricky window update problem define log pane richedit styles ws child ws visible ws vscroll ws hscroll es multiline es readonly es nohidesel c rect rect get dlg item idc servmsg get window rect rect get dlg item idc servmsg destroy window map window points null m hwnd lppoint rect 2 if servermsgbox create log pane richedit styles rect this idc servmsg servermsgbox set profile skin key t server info log servermsgbox modify style ex 0 ws ex staticedge swp framechanged servermsgbox send message em setmargins ec leftmargin ec rightmargin makelong 3 3 servermsgbox set event mask servermsgbox get event mask enm link servermsgbox set font the app m fonthypertext servermsgbox apply skin servermsgbox set title get res string ids sv serverinfo servermsgbox append text t e mule v the app m strcurversionlong t n mod note do not remove this part merkur m strclicknewversion get res string ids emulew t get res string ids emulew3 t get res string ids emulew2 servermsgbox append hyper link t t m strclicknewversion t mod note end servermsgbox append text t n n get dlg item idc logbox get window rect rect get dlg item idc logbox destroy window map window points null m hwnd lppoint rect 2 if logbox create log pane richedit styles rect this idc logbox logbox set profile skin key t log logbox modify style ex 0 ws ex staticedge swp framechanged logbox send message em setmargins ec leftmargin ec rightmargin makelong 3 3 if the app m fontlog m hobject logbox set font the app m fontlog logbox apply skin logbox set title get res string ids sv log logbox set autourl detect false get dlg item idc debug log get window rect rect get dlg item idc debug log destroy window map window points null m hwnd lppoint rect 2 if debuglog create log pane richedit styles rect this idc debug log debuglog set profile skin key t verbose log debuglog modify style ex 0 ws ex staticedge swp framechanged debuglog send message em setmargins ec leftmargin ec rightmargin makelong 3 3 if the app m fontlog m hobject debuglog set font the app m fontlog debuglog apply skin debuglog set title sz debug log title debuglog set autourl detect false set all icons localize serverlistctrl init the app serverlist c edit get dlg item idc sport set limit text 5 get dlg item idc sport set window text t 4661 tcitem newitem c string name name get res string ids sv serverinfo newitem mask tcif text tcif image newitem psz text const cast lptstr lpctstr name newitem i image 1 verify status selector insert item status selector get item count newitem pane server info name get res string ids sv log newitem mask tcif text tcif image newitem psz text const cast lptstr lpctstr name newitem i image 0 verify status selector insert item status selector get item count newitem pane log name sz debug log title newitem mask tcif text tcif image newitem psz text const cast lptstr lpctstr name newitem i image 0 verify status selector insert item status selector get item count newitem pane verbose log add anchor idc servlst ico top left add anchor idc servlist text top left add anchor serverlistctrl top left middle right add anchor m ctrlnewserverfrm top right add anchor idc sstatic4 top right add anchor idc sstatic7 top right add anchor idc ipaddress top right add anchor idc sstatic3 top right add anchor idc sname top right add anchor idc addserver top right add anchor idc sstatic5 top right add anchor m ctrlmyinfofrm top right bottom right add anchor m myinfo top right bottom right add anchor idc sport top right add anchor m ctrlupdateserverfrm top right add anchor idc servermeturl top right add anchor idc updateservermetfromurl top right add anchor status selector middle left bottom right add anchor idc logreset middle right avoid resizing gui glitches with the tab control by adding this control as the last one z order add anchor idc ed2kconnect top right add anchor idc dd top right the resizing of those log controls rich edit controls works better when added as last anchors add anchor servermsgbox middle left bottom right add anchor logbox middle left bottom right add anchor debuglog middle left bottom right set the tab control to the bottom of the z order this solves a lot of strange repainting problems with the rich edit controls the log panes set window pos status selector hwnd bottom 0 0 0 0 swp noactivate swp nocopybits swp nomove swp nosize debug true toggle debug window debuglog show window sw hide logbox show window sw hide servermsgbox show window sw show optional restore last used log pane if the prefs get restore last log pane if the prefs get last log paneid 0 the prefs get last log paneid status selector get item count int i cur sel status selector get cur sel status selector set cur sel the prefs get last log paneid if the prefs get last log paneid status selector get cur sel update log tab selection else status selector set cur sel i cur sel m myinfo send message em setmargins ec leftmargin ec rightmargin makelong 3 3 m myinfo set autourl detect m myinfo set event mask m myinfo get event mask enm link paraformat pf 0 pf cb size sizeof pf if m myinfo get para format pf pf dw mask pfm tabstops pf c tab count 4 pf rgx tabs 0 900 pf rgx tabs 1 1000 pf rgx tabs 2 1100 pf rgx tabs 3 1200 m myinfo set para format pf m cfdef cb size sizeof m cfdef if m myinfo get selection char format m cfdef m cfbold m cfdef m cfbold dw mask cfm bold m cfbold dw effects cfe bold if the prefs get use autocompletion m pacservermeturl new c custom auto complete m pacservermeturl add ref if m pacservermeturl bind get dlg item m hwnd idc servermeturl aco updownkeydropslist aco autosuggest aco filterprefixes m pacservermeturl load list the prefs get config dir servermet strings profile if the app m fontsymbol m hobject get dlg item idc dd set font the app m fontsymbol get dlg item idc dd set window text t 6 show a down arrow else get dlg item idc dd show window sw hide init window styles this splitter c rect rc spl rc spl left 55 rc spl right 300 rc dlg item right rc spl top 55 rc spl bottom rc spl top svwnd splitter height m wndsplitter create ws child ws visible rc spl this idc splitter server init splitter return true cserverwnd oninitdialog theapp m_fontlog m_hobject cfont pfont getdlgitem idc_sstatic getfont pfont getobject theapp m_fontlog createfontindirect replacericheditctrl getdlgitem idc_myinfolist getdlgitem idc_sstatic getfont cresizabledialog oninitdialog es_nohidesel log_pane_richedit_styles ws_child ws_visible ws_vscroll ws_hscroll es_multiline es_readonly es_nohidesel crect getdlgitem idc_servmsg getwindowrect getdlgitem idc_servmsg destroywindow mapwindowpoints m_hwnd log_pane_richedit_styles idc_servmsg setprofileskinkey _t serverinfolog modifystyleex ws_ex_staticedge swp_framechanged sendmessage em_setmargins ec_leftmargin ec_rightmargin seteventmask geteventmask enm_link setfont theapp m_fonthypertext applyskin settitle getresstring ids_sv_serverinfo appendtext _t emule theapp m_strcurversionlong _t m_strclicknewversion getresstring ids_emulew _t getresstring ids_emulew3 _t getresstring ids_emulew2 appendhyperlink _t _t m_strclicknewversion _t appendtext _t getdlgitem idc_logbox getwindowrect getdlgitem idc_logbox destroywindow mapwindowpoints m_hwnd log_pane_richedit_styles idc_logbox setprofileskinkey _t modifystyleex ws_ex_staticedge swp_framechanged sendmessage em_setmargins ec_leftmargin ec_rightmargin theapp m_fontlog m_hobject setfont theapp m_fontlog applyskin settitle getresstring ids_sv_log setautourldetect getdlgitem idc_debug_log getwindowrect getdlgitem idc_debug_log destroywindow mapwindowpoints m_hwnd log_pane_richedit_styles idc_debug_log setprofileskinkey _t verboselog modifystyleex ws_ex_staticedge swp_framechanged sendmessage em_setmargins ec_leftmargin ec_rightmargin theapp m_fontlog m_hobject setfont theapp m_fontlog applyskin settitle sz_debug_log_title setautourldetect setallicons theapp cedit getdlgitem idc_sport setlimittext getdlgitem idc_sport setwindowtext _t cstring getresstring ids_sv_serverinfo tcif_text tcif_image psztext const_cast iimage statusselector insertitem statusselector getitemcount paneserverinfo getresstring ids_sv_log tcif_text tcif_image psztext const_cast iimage statusselector insertitem statusselector getitemcount panelog sz_debug_log_title tcif_text tcif_image psztext const_cast iimage statusselector insertitem statusselector getitemcount paneverboselog addanchor idc_servlst_ico top_left addanchor idc_servlist_text top_left addanchor top_left middle_right addanchor m_ctrlnewserverfrm top_right addanchor idc_sstatic4 top_right addanchor idc_sstatic7 top_right addanchor idc_ipaddress top_right addanchor idc_sstatic3 top_right addanchor idc_sname top_right addanchor idc_addserver top_right addanchor idc_sstatic5 top_right addanchor m_ctrlmyinfofrm top_right bottom_right addanchor m_myinfo top_right bottom_right addanchor idc_sport top_right addanchor m_ctrlupdateserverfrm top_right addanchor idc_servermeturl top_right addanchor idc_updateservermetfromurl top_right addanchor statusselector middle_left bottom_right addanchor idc_logreset middle_right addanchor idc_ed2kconnect top_right addanchor idc_dd top_right addanchor middle_left bottom_right addanchor middle_left bottom_right addanchor middle_left bottom_right setwindowpos statusselector hwnd_bottom swp_noactivate swp_nocopybits swp_nomove swp_nosize toggledebugwindow showwindow sw_hide showwindow sw_hide showwindow sw_show theprefs getrestorelastlogpane theprefs getlastlogpaneid theprefs getlastlogpaneid statusselector getitemcount icursel statusselector getcursel statusselector setcursel theprefs getlastlogpaneid theprefs getlastlogpaneid statusselector getcursel updatelogtabselection statusselector setcursel icursel m_myinfo sendmessage em_setmargins ec_leftmargin ec_rightmargin m_myinfo setautourldetect m_myinfo seteventmask m_myinfo geteventmask enm_link cbsize m_myinfo getparaformat dwmask pfm_tabstops ctabcount rgxtabs rgxtabs rgxtabs rgxtabs m_myinfo setparaformat m_cfdef cbsize m_cfdef m_myinfo getselectioncharformat m_cfdef m_cfbold m_cfdef m_cfbold dwmask cfm_bold m_cfbold dweffects cfe_bold theprefs getuseautocompletion m_pacservermeturl ccustomautocomplete m_pacservermeturl addref m_pacservermeturl getdlgitem m_hwnd idc_servermeturl aco_updownkeydropslist aco_autosuggest aco_filterprefixes m_pacservermeturl loadlist theprefs getconfigdir servermet_strings_profile theapp m_fontsymbol m_hobject getdlgitem idc_dd setfont theapp m_fontsymbol getdlgitem idc_dd setwindowtext _t getdlgitem idc_dd showwindow sw_hide initwindowstyles crect rcspl rcspl rcspl rcdlgitem rcspl rcspl rcspl svwnd_splitter_height m_wndsplitter ws_child ws_visible rcspl idc_splitter_server initsplitter bool c server wnd pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 return false if p msg w param vk escape return false if m pacservermeturl m pacservermeturl is bound p msg w param vk delete p msg hwnd get dlg item idc servermeturl m hwnd get async key state vk menu 0 get async key state vk control 0 m pacservermeturl clear if p msg w param vk return if p msg hwnd get dlg item idc ipaddress m hwnd p msg hwnd get dlg item idc sport m hwnd p msg hwnd get dlg item idc sname m hwnd on bn clicked addserver return true else if p msg hwnd get dlg item idc servermeturl m hwnd if m pacservermeturl m pacservermeturl is bound c string str text get dlg item idc servermeturl get window text str text if str text is empty get dlg item idc servermeturl set window text t this seems to be the only chance to let the dropdown list to disapear get dlg item idc servermeturl set window text str text c edit get dlg item idc servermeturl set sel str text get length str text get length on bn clicked update server met from url return true return c resizable dialog pre translate message p msg cserverwnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control pmsg wparam vk_escape m_pacservermeturl m_pacservermeturl isbound pmsg wparam vk_delete pmsg getdlgitem idc_servermeturl m_hwnd getasynckeystate vk_menu getasynckeystate vk_control m_pacservermeturl pmsg wparam vk_return pmsg getdlgitem idc_ipaddress m_hwnd pmsg getdlgitem idc_sport m_hwnd pmsg getdlgitem idc_sname m_hwnd onbnclickedaddserver pmsg getdlgitem idc_servermeturl m_hwnd m_pacservermeturl m_pacservermeturl isbound cstring strtext getdlgitem idc_servermeturl getwindowtext strtext strtext isempty getdlgitem idc_servermeturl setwindowtext _t getdlgitem idc_servermeturl setwindowtext strtext cedit getdlgitem idc_servermeturl setsel strtext getlength strtext getlength onbnclickedupdateservermetfromurl cresizabledialog pretranslatemessage pmsg lresult c server wnd def window proc uint message wparam w param lparam l param switch message arrange transferwindow layout case wm paint if m wndsplitter c rect rc wnd get window rect rc wnd if rc wnd height 0 c rect rc down serverlistctrl get window rect rc down screen to client rc down splitter paint update c rect rc spl rc spl left 10 rc spl right rc down right rc spl top rc down bottom svwnd splitter yoff rc spl bottom rc spl top svwnd splitter height m wndsplitter move window rc spl true update splitter range break return c resizable dialog def window proc message w param l param cserverwnd defwindowproc wparam lparam wm_paint m_wndsplitter crect rcwnd getwindowrect rcwnd rcwnd crect rcdown getwindowrect rcdown screentoclient rcdown crect rcspl rcspl rcspl rcdown rcspl rcdown svwnd_splitter_yoff rcspl rcspl svwnd_splitter_height m_wndsplitter movewindow rcspl updatesplitterrange cresizabledialog defwindowproc wparam lparam void c server wnd on bn clicked addserver c string serveraddr if get dlg item idc ipaddress get window text length afx message box get res string ids srv addr return else get dlg item idc ipaddress get window text serveraddr uint16 u port 0 if tcsncmp serveraddr t ed2k 7 0 ced2k link p link null try p link ced2k link create link from url serveraddr serveraddr empty if p link p link get kind ced2k link k server ced2k server link p server link p link get server link if p server link uint32 n serverip p server link getip u port p server link get port serveraddr ipstr n serverip set dlg item text idc ipaddress serveraddr set dlg item int idc sport u port false catch c string str error afx message box str error serveraddr empty delete p link else if get dlg item idc sport get window text length afx message box get res string ids srv port return bool b translated false u port uint16 get dlg item int idc sport b translated false if b translated afx message box get res string ids srv port return if serveraddr is empty u port 0 afx message box get res string ids srv addr return c string str server name get dlg item idc sname get window text str server name add server u port serveraddr str server name cserverwnd onbnclickedaddserver cstring getdlgitem idc_ipaddress getwindowtextlength afxmessagebox getresstring ids_srv_addr getdlgitem idc_ipaddress getwindowtext uport _tcsncmp _t ced2klink plink plink ced2klink createlinkfromurl plink plink getkind ced2klink kserver ced2kserverlink pserverlink plink getserverlink pserverlink nserverip pserverlink uport pserverlink getport nserverip setdlgitemtext idc_ipaddress setdlgitemint idc_sport uport cstring strerror afxmessagebox strerror plink getdlgitem idc_sport getwindowtextlength afxmessagebox getresstring ids_srv_port btranslated uport getdlgitemint idc_sport btranslated btranslated afxmessagebox getresstring ids_srv_port isempty uport afxmessagebox getresstring ids_srv_addr cstring strservername getdlgitem idc_sname getwindowtext strservername addserver uport strservername void c server wnd on bn clicked update server met from url c string strurl get dlg item idc servermeturl get window text strurl if strurl is empty if the prefs addresses list is empty add log line true get res string ids srv nourlav else bool b downloaded false position pos the prefs addresses list get head position while b downloaded pos null strurl the prefs addresses list get next pos b downloaded update server met fromurl strurl else update server met fromurl strurl cserverwnd onbnclickedupdateservermetfromurl cstring getdlgitem idc_servermeturl getwindowtext isempty theprefs addresses_list isempty addlogline getresstring ids_srv_nourlav bdownloaded theprefs addresses_list getheadposition bdownloaded theprefs addresses_list getnext bdownloaded updateservermetfromurl updateservermetfromurl void c server wnd on bn clicked reset log int cur sel status selector get cur sel if cur sel 1 return if cur sel pane verbose log the app emuledlg reset debug log the app emuledlg statusbar set text t s bar log 0 if cur sel pane log the app emuledlg reset log the app emuledlg statusbar set text t s bar log 0 if cur sel pane server info servermsgbox reset the statusbar does not contain any server log related messages so it s not cleared cserverwnd onbnclickedresetlog cur_sel statusselector getcursel cur_sel cur_sel paneverboselog theapp resetdebuglog theapp settext _t sbarlog cur_sel panelog theapp resetlog theapp settext _t sbarlog cur_sel paneserverinfo void c server wnd on bn connect if the app serverconnect is connected the app serverconnect disconnect else if the app serverconnect is connecting the app serverconnect stop connection try else the app serverconnect connect to any server cserverwnd onbnconnect theapp isconnected theapp theapp isconnecting theapp stopconnectiontry theapp connecttoanyserver void c server wnd on tcn selchange tab3 nmhdr pnmhdr lresult p result update log tab selection p result 0 cserverwnd ontcnselchangetab3 presult updatelogtabselection presult void c server wnd on en link server box nmhdr pnmhdr lresult p result p result 0 enlink p en link reinterpret cast enlink pnmhdr if p en link p en link msg wm lbuttondown c string str url servermsgbox get text range p en link chrg cp min p en link chrg cp max str url if str url m strclicknewversion mod note do not remove this part merkur str url format t en version check php version i language i the app m ucurversioncheck the prefs get languageid str url the prefs get version check baseurl str url mod note end shell execute null null str url null null sw showdefault p result 1 cserverwnd onenlinkserverbox presult presult penlink reinterpret_cast penlink penlink wm_lbuttondown cstring strurl gettextrange penlink cpmin penlink cpmax strurl strurl m_strclicknewversion strurl _t version_check theapp m_ucurversioncheck theprefs getlanguageid strurl theprefs getversioncheckbaseurl strurl shellexecute strurl sw_showdefault presult void c server wnd on sys color change c resizable dialog on sys color change set all icons cserverwnd onsyscolorchange cresizabledialog onsyscolorchange setallicons void c server wnd ondd clicked c wnd box get dlg item idc servermeturl box set focus box set window text t box send message wm keydown vk down 0x00510001 cserverwnd onddclicked cwnd getdlgitem idc_servermeturl setfocus setwindowtext _t sendmessage wm_keydown vk_down void c server wnd on svr text change get dlg item idc addserver enable window get dlg item idc ipaddress get window text length get dlg item idc updateservermetfromurl enable window get dlg item idc servermeturl get window text length 0 cserverwnd onsvrtextchange getdlgitem idc_addserver enablewindow getdlgitem idc_ipaddress getwindowtextlength getdlgitem idc_updateservermetfromurl enablewindow getdlgitem idc_servermeturl getwindowtextlength bool c server wnd on help info helpinfo p help info the app show help emule faq update server return true cserverwnd onhelpinfo phelpinfo theapp showhelp emule_faq_update_server void c server wnd on stn dblclick servlst ico the app emuledlg show preferences idd ppg server cserverwnd onstndblclickservlstico theapp showpreferences idd_ppg_server void c server wnd on splitter moved nmhdr pnmhdr lresult p result spc nmhdr p hdr spc nmhdr pnmhdr do resize p hdr delta cserverwnd onsplittermoved presult spc_nmhdr phdr spc_nmhdr doresize phdr void c server wnd on window pos changed windowpos lpwndpos if m wndsplitter c rect rc wnd get window rect rc wnd if rc wnd height 0 invalidate c resizable dialog on window pos changed lpwndpos cserverwnd onwindowposchanged m_wndsplitter crect rcwnd getwindowrect rcwnd rcwnd cresizabledialog onwindowposchanged c rich edit ctrlx c rich edit ctrlx m bdisableselectonfocus true m bselfupdate false m bforcearrowcursor false m harrowcursor load cursor null idc arrow cricheditctrlx cricheditctrlx m_bdisableselectonfocus m_bselfupdate m_bforcearrowcursor m_harrowcursor loadcursor idc_arrow c rich edit ctrlx c rich edit ctrlx cricheditctrlx cricheditctrlx void c rich edit ctrlx set disable select on focus bool b disable m bdisableselectonfocus b disable cricheditctrlx setdisableselectonfocus bdisable m_bdisableselectonfocus bdisable void c rich edit ctrlx set syntax coloring const lpctstr ppsz keywords lpctstr psz seperators int i 0 while ppsz keywords i null m astrkeywords add ppsz keywords i m strseperators psz seperators if m astrkeywords get count 0 m strseperators empty else set event mask get event mask enm change get default char format m cfdef m cfkeyword m cfdef m cfkeyword dw mask cfm color m cfkeyword dw effects cfe autocolor m cfkeyword cr text color rgb 0 0 255 assert get text mode tm multilevelundo cricheditctrlx setsyntaxcoloring ppszkeywords pszseperators ppszkeywords m_astrkeywords ppszkeywords m_strseperators pszseperators m_astrkeywords getcount m_strseperators seteventmask geteventmask enm_change getdefaultcharformat m_cfdef m_cfkeyword m_cfdef m_cfkeyword dwmask cfm_color m_cfkeyword dweffects cfe_autocolor m_cfkeyword crtextcolor gettextmode tm_multilevelundo c rich edit ctrlx c rich edit ctrlx operator char psz uses conversion replace sel a2t psz return this cricheditctrlx cricheditctrlx uses_conversion replacesel c rich edit ctrlx c rich edit ctrlx operator uint u val c string str val str val format t u u val replace sel str val return this cricheditctrlx cricheditctrlx uval cstring strval strval _t uval replacesel strval c rich edit ctrlx c rich edit ctrlx operator int i val c string str val str val format t d i val replace sel str val return this cricheditctrlx cricheditctrlx ival cstring strval strval _t ival replacesel strval c rich edit ctrlx c rich edit ctrlx operator double f val c string str val str val format t 3f f val replace sel str val return this cricheditctrlx cricheditctrlx fval cstring strval strval _t fval replacesel strval void c rich edit ctrlx update syntax coloring c string str text get window text str text if str text is empty return m bselfupdate true long l cur sel start l cur sel end get sel l cur sel start l cur sel end set sel 0 1 set selection char format m cfdef set sel l cur sel start l cur sel end lptstr psz start const cast lptstr lpctstr str text lpctstr psz psz start while psz t 0 if psz t lpctstr psz end tcschr psz 1 t if psz end psz psz end 1 else break else bool b found keyword false for int k 0 k m astrkeywords get count k const c string rstr keyword m astrkeywords k int i kw len rstr keyword get length if tcsncmp psz rstr keyword i kw len 0 psz i kw len t 0 tcschr m strseperators psz i kw len null int i start psz psz start int i end i start i kw len long l cur sel start l cur sel end get sel l cur sel start l cur sel end set sel i start i end set selection char format m cfkeyword set sel l cur sel start l cur sel end psz i kw len b found keyword true break if b found keyword psz update window m bselfupdate false cricheditctrlx updatesyntaxcoloring cstring strtext getwindowtext strtext strtext isempty m_bselfupdate lcurselstart lcurselend getsel lcurselstart lcurselend setsel setselectioncharformat m_cfdef setsel lcurselstart lcurselend pszstart const_cast strtext pszstart _t _t pszend _tcschr _t pszend pszend bfoundkeyword m_astrkeywords getcount cstring rstrkeyword m_astrkeywords ikwlen rstrkeyword getlength _tcsncmp rstrkeyword ikwlen ikwlen _t _tcschr m_strseperators ikwlen istart pszstart iend istart ikwlen lcurselstart lcurselend getsel lcurselstart lcurselend setsel istart iend setselectioncharformat m_cfkeyword setsel lcurselstart lcurselend ikwlen bfoundkeyword bfoundkeyword updatewindow m_bselfupdate bool c rich edit ctrlx on command wparam w param lparam l param switch w param case mp undo undo break case mp cut cut break case mp copyselected copy break case mp paste paste break case mp removeselected clear break case mp selectall set sel 0 1 break return true cricheditctrlx oncommand wparam lparam wparam mp_undo mp_cut mp_copyselected mp_paste mp_removeselected mp_selectall setsel uint c rich edit ctrlx on get dlg code if m bdisableselectonfocus avoid that the edit control will select the entire contents if the focus is moved via tab into the edit control dlgc wantallkeys is needed if the control is within a wizard property page and the user presses the enter key to invoke the default button of the property sheet return c rich edit ctrl on get dlg code dlgc hassetsel dlgc wantallkeys if there is an auto complete control attached to the rich edit control we have to explicitly disable dlgc wanttab return c rich edit ctrl on get dlg code dlgc wanttab cricheditctrlx ongetdlgcode m_bdisableselectonfocus dlgc_wantallkeys cricheditctrl ongetdlgcode dlgc_hassetsel dlgc_wantallkeys dlgc_wanttab cricheditctrl ongetdlgcode dlgc_wanttab bool c rich edit ctrlx on en link nmhdr pnmhdr lresult p result bool b msg handled false p result 0 enlink p en link reinterpret cast enlink pnmhdr if p en link p en link msg wm lbuttondown c string str url get text range p en link chrg cp min p en link chrg cp max str url shell execute null null str url null null sw showdefault p result 1 b msg handled true do not route this message to any parent return b msg handled cricheditctrlx onenlink presult bmsghandled presult penlink reinterpret_cast penlink penlink wm_lbuttondown cstring strurl gettextrange penlink cpmin penlink cpmax strurl shellexecute strurl sw_showdefault presult bmsghandled bmsghandled void c rich edit ctrlx on context menu c wnd p wnd c point point long i sel start i sel end get sel i sel start i sel end int i text len get window text length context menu of standard edit control undo cut copy paste delete select all bool b read only get style es readonly 0 c menu menu menu create popup menu if b read only menu append menu mf string mp undo get res string ids undo menu append menu mf separator if b read only menu append menu mf string mp cut get res string ids cut menu append menu mf string mp copyselected get res string ids copy if b read only menu append menu mf string mp paste get res string ids paste menu append menu mf string mp removeselected get res string ids deleteselected menu append menu mf separator menu append menu mf string mp selectall get res string ids selectall menu enable menu item mp undo can undo mf enabled mf grayed menu enable menu item mp cut i sel end i sel start mf enabled mf grayed menu enable menu item mp copyselected i sel end i sel start mf enabled mf grayed menu enable menu item mp paste can paste mf enabled mf grayed menu enable menu item mp removeselected i sel end i sel start mf enabled mf grayed menu enable menu item mp selectall i text len 0 mf enabled mf grayed if point x 1 point y 1 point x 16 point y 32 client to screen point cheap workaround for the text cursor is showing while context menu is open glitch it could be solved properly with the re s com interface but because the according messages are not routed with a unique control id it s not really useable e g if there are more re controls in one window would to envelope each re window to get a unique id m bforcearrowcursor true menu track popup menu tpm leftalign tpm rightbutton point x point y this m bforcearrowcursor false cricheditctrlx oncontextmenu cwnd pwnd cpoint iselstart iselend getsel iselstart iselend itextlen getwindowtextlength breadonly getstyle es_readonly cmenu createpopupmenu breadonly appendmenu mf_string mp_undo getresstring ids_undo appendmenu mf_separator breadonly appendmenu mf_string mp_cut getresstring ids_cut appendmenu mf_string mp_copyselected getresstring ids_copy breadonly appendmenu mf_string mp_paste getresstring ids_paste appendmenu mf_string mp_removeselected getresstring ids_deleteselected appendmenu mf_separator appendmenu mf_string mp_selectall getresstring ids_selectall enablemenuitem mp_undo canundo mf_enabled mf_grayed enablemenuitem mp_cut iselend iselstart mf_enabled mf_grayed enablemenuitem mp_copyselected iselend iselstart mf_enabled mf_grayed enablemenuitem mp_paste canpaste mf_enabled mf_grayed enablemenuitem mp_removeselected iselend iselstart mf_enabled mf_grayed enablemenuitem mp_selectall itextlen mf_enabled mf_grayed clienttoscreen m_bforcearrowcursor trackpopupmenu tpm_leftalign tpm_rightbutton m_bforcearrowcursor void c rich edit ctrlx on key down uint n char uint n rep cnt uint n flags if n char a get key state vk control 0x8000 ctrl a select all set sel 0 1 else if n char c get key state vk control 0x8000 ctrl c copy selected contents to clipboard copy c rich edit ctrl on key down n char n rep cnt n flags cricheditctrlx onkeydown nchar nrepcnt nflags nchar getkeystate vk_control setsel nchar getkeystate vk_control cricheditctrl onkeydown nchar nrepcnt nflags void c rich edit ctrlx on en change if m bselfupdate m astrkeywords get count update syntax coloring cricheditctrlx onenchange m_bselfupdate m_astrkeywords getcount updatesyntaxcoloring bool c rich edit ctrlx on set cursor c wnd p wnd uint n hit test uint message cheap workaround for the text cursor is showing while context menu is open glitch it could be solved properly with the re s com interface but because the according messages are not routed with a unique control id it s not really useable e g if there are more re controls in one window would to envelope each re window to get a unique id if m bforcearrowcursor m harrowcursor set cursor m harrowcursor return true return c rich edit ctrl on set cursor p wnd n hit test message cricheditctrlx onsetcursor cwnd pwnd nhittest m_bforcearrowcursor m_harrowcursor setcursor m_harrowcursor cricheditctrl onsetcursor pwnd nhittest c closable tab ctrl c closable tab ctrl m bcloseable true memset m iiclosebutton 0 sizeof m iiclosebutton m ptctxmenu set point 1 1 cclosabletabctrl cclosabletabctrl m_bcloseable m_iiclosebutton m_iiclosebutton m_ptctxmenu setpoint c closable tab ctrl c closable tab ctrl cclosabletabctrl cclosabletabctrl void c closable tab ctrl internal init modify style 0 tcs ownerdrawfixed set all icons cclosabletabctrl internalinit modifystyle tcs_ownerdrawfixed setallicons void c closable tab ctrl set all icons if m bcloseable m imglstclosebutton delete image list m imglstclosebutton create 8 8 the app m idfltimagelistcolorflags ilc mask 0 1 m imglstclosebutton set bk color clr none m imglstclosebutton add c temp icon loader t close tab 8 8 m imglstclosebutton get image info 0 m iiclosebutton invalidate cclosabletabctrl setallicons m_bcloseable m_imglstclosebutton deleteimagelist m_imglstclosebutton theapp m_idfltimagelistcolorflags ilc_mask m_imglstclosebutton setbkcolor clr_none m_imglstclosebutton ctempiconloader _t closetab m_imglstclosebutton getimageinfo m_iiclosebutton void c closable tab ctrl get close button rect const c rect rc item c rect rc close button rc close button top rc item top 2 rc close button bottom rc close button top m iiclosebutton rc image bottom m iiclosebutton rc image top rc close button right rc item right 2 rc close button left rc close button right m iiclosebutton rc image right m iiclosebutton rc image left cclosabletabctrl getclosebuttonrect crect rcitem crect rcclosebutton rcclosebutton rcitem rcclosebutton rcclosebutton m_iiclosebutton rcimage m_iiclosebutton rcimage rcclosebutton rcitem rcclosebutton rcclosebutton m_iiclosebutton rcimage m_iiclosebutton rcimage void c closable tab ctrl pre subclass window c tab ctrl pre subclass window internal init cclosabletabctrl presubclasswindow ctabctrl presubclasswindow internalinit void c closable tab ctrl draw item lpdrawitemstruct lp draw item struct c rect rect lp draw item struct rc item int n tab index lp draw item struct itemid if n tab index 0 return bool b selected n tab index get cur sel tchar sz label 256 tc item tci tci mask tcif text tcif image tcif state tci psz text sz label tci cch text max arrsize sz label tci dw state mask tcis highlighted if get item n tab index tci return cdc pdc cdc from handle lp draw item struct hdc if pdc return int i old bk mode pdc set bk mode transparent draw image on left side c image list piml get image list if tci i image 0 piml piml m himagelist imageinfo ii piml get image info 0 ii rect left b selected 8 4 piml draw pdc tci i image c point rect left rect top 2 ild transparent rect left ii rc image right ii rc image left if b selected rect left 4 bool b closeable m bcloseable if b closeable get parent send message um querytab n tab index b closeable false draw close button at right side if b closeable m imglstclosebutton m himagelist c rect rc close button get close button rect rect rc close button m imglstclosebutton draw pdc 0 rc close button top left ild transparent rect right rc close button left 2 colorref cr old color rgb 0 0 0 if tci dw state tcis highlighted cr old color pdc set text color rgb 192 0 0 rect top 4 pdc draw text sz label rect dt singleline dt top dt center dt noprefix if tci dw state tcis highlighted pdc set text color cr old color pdc set bk mode i old bk mode cclosabletabctrl drawitem lpdrawitemstruct crect lpdrawitemstruct rcitem ntabindex lpdrawitemstruct ntabindex bselected ntabindex getcursel szlabel tc_item tcif_text tcif_image tcif_state psztext szlabel cchtextmax szlabel dwstatemask tcis_highlighted getitem ntabindex fromhandle lpdrawitemstruct ioldbkmode setbkmode cimagelist getimagelist iimage m_himagelist getimageinfo bselected iimage cpoint ild_transparent rcimage rcimage bselected bcloseable m_bcloseable bcloseable getparent sendmessage um_querytab ntabindex bcloseable bcloseable m_imglstclosebutton m_himagelist crect rcclosebutton getclosebuttonrect rcclosebutton m_imglstclosebutton rcclosebutton topleft ild_transparent rcclosebutton croldcolor dwstate tcis_highlighted croldcolor settextcolor drawtext szlabel dt_singleline dt_top dt_center dt_noprefix dwstate tcis_highlighted settextcolor croldcolor setbkmode ioldbkmode bool c closable tab ctrl on command wparam w param lparam l param if w param mp remove if m ptctxmenu x 1 m ptctxmenu y 1 int i tabs get item count for int i 0 i i tabs i c rect rc item get item rect i rc item if rc item pt in rect m ptctxmenu get parent send message um closetab wparam i break return true return c tab ctrl on command w param l param cclosabletabctrl oncommand wparam lparam wparam mp_remove m_ptctxmenu m_ptctxmenu itabs getitemcount itabs crect rcitem getitemrect rcitem rcitem ptinrect m_ptctxmenu getparent sendmessage um_closetab ctabctrl oncommand wparam lparam int c closable tab ctrl on create lpcreatestruct lp create struct if c tab ctrl on create lp create struct 1 return 1 internal init return 0 cclosabletabctrl oncreate lpcreatestruct ctabctrl oncreate lpcreatestruct internalinit void c closable tab ctrl onl button up uint n flags c point point if m bcloseable int i tabs get item count for int i 0 i i tabs i c rect rc item get item rect i rc item c rect rc close button get close button rect rc item rc close button rc close button top 2 rc close button left 4 rc close button right 2 rc close button bottom 4 if rc close button pt in rect point get parent send message um closetab wparam i return c tab ctrl onl button up n flags point cclosabletabctrl onlbuttonup nflags cpoint m_bcloseable itabs getitemcount itabs crect rcitem getitemrect rcitem crect rcclosebutton getclosebuttonrect rcitem rcclosebutton rcclosebutton rcclosebutton rcclosebutton rcclosebutton rcclosebutton ptinrect getparent sendmessage um_closetab ctabctrl onlbuttonup nflags void c closable tab ctrl onm button up uint n flags c point point if m bcloseable int i tabs get item count for int i 0 i i tabs i c rect rc item get item rect i rc item if rc item pt in rect point get parent send message um closetab wparam i return c tab ctrl onm button up n flags point cclosabletabctrl onmbuttonup nflags cpoint m_bcloseable itabs getitemcount itabs crect rcitem getitemrect rcitem rcitem ptinrect getparent sendmessage um_closetab ctabctrl onmbuttonup nflags void c closable tab ctrl onl button dbl clk uint n flags c point point int i tabs get item count for int i 0 i i tabs i c rect rc item get item rect i rc item if rc item pt in rect point get parent send message um dblclicktab wparam i return c tab ctrl onl button dbl clk n flags point cclosabletabctrl onlbuttondblclk nflags cpoint itabs getitemcount itabs crect rcitem getitemrect rcitem rcitem ptinrect getparent sendmessage um_dblclicktab ctabctrl onlbuttondblclk nflags void c closable tab ctrl on sys color change c tab ctrl on sys color change set all icons cclosabletabctrl onsyscolorchange ctabctrl onsyscolorchange setallicons void c closable tab ctrl on context menu c wnd p wnd c point point if m bcloseable c menu menu menu create popup menu menu append menu mf string mp remove get res string ids fd close m ptctxmenu point screen to client m ptctxmenu menu track popup menu tpm leftalign tpm rightbutton point x point y this cclosabletabctrl oncontextmenu cwnd pwnd cpoint m_bcloseable cmenu createpopupmenu appendmenu mf_string mp_remove getresstring ids_fd_close m_ptctxmenu screentoclient m_ptctxmenu trackpopupmenu tpm_leftalign tpm_rightbutton lresult c closable tab ctrl onthemechanged owner drawn tab control seems to have troubles with updating itself due to an xp theme change modify style tcs ownerdrawfixed 0 reset control style to not owner drawn default process original wm themechanged message modify style 0 tcs ownerdrawfixed apply owner drawn style again return 0 cclosabletabctrl _onthemechanged modifystyle tcs_ownerdrawfixed wm_themechanged modifystyle tcs_ownerdrawfixed c tool tip ctrlx c tool tip ctrlx m bcol1bold true reset system metrics m dwcol1drawtextflags dflt drawtext flags dt left m dwcol2drawtextflags dflt drawtext flags dt left ctooltipctrlx ctooltipctrlx m_bcol1bold resetsystemmetrics m_dwcol1drawtextflags dflt_drawtext_flags dt_left m_dwcol2drawtextflags dflt_drawtext_flags dt_left c tool tip ctrlx c tool tip ctrlx ctooltipctrlx ctooltipctrlx void c tool tip ctrlx set col1 draw text flags dword dw flags m dwcol1drawtextflags dflt drawtext flags dw flags ctooltipctrlx setcol1drawtextflags dwflags m_dwcol1drawtextflags dflt_drawtext_flags dwflags void c tool tip ctrlx set col2 draw text flags dword dw flags m dwcol2drawtextflags dflt drawtext flags dw flags ctooltipctrlx setcol2drawtextflags dwflags m_dwcol2drawtextflags dflt_drawtext_flags dwflags void c tool tip ctrlx reset system metrics m fontbold delete object m crtooltipbkcolor get sys color color infobk m rcscreen left 0 m rcscreen top 0 m rcscreen right get system metrics sm cxscreen m rcscreen bottom get system metrics sm cyscreen m iscreenwidth4 m rcscreen width 4 ctooltipctrlx resetsystemmetrics m_fontbold deleteobject m_crtooltipbkcolor getsyscolor color_infobk m_rcscreen m_rcscreen m_rcscreen getsystemmetrics sm_cxscreen m_rcscreen getsystemmetrics sm_cyscreen m_iscreenwidth4 m_rcscreen void c tool tip ctrlx onnm custom draw nmhdr pnmhdr lresult p result lpnmttcustomdraw pnmcd reinterpret cast lpnmttcustomdraw pnmhdr if pnmcd nmcd dw draw stage cdds prepaint c wnd pwnd c wnd from handle pnmcd nmcd hdr hwnd from cdc pdc cdc from handle pnmcd nmcd hdc c string str text pwnd get window text str text c rect rc wnd pwnd get window rect rc wnd c rect rc border rc border left pnmcd nmcd rc left rc wnd left rc border top pnmcd nmcd rc top rc wnd top rc border right rc wnd right pnmcd nmcd rc right rc border bottom rc wnd bottom pnmcd nmcd rc bottom if m bcol1bold m fontbold m hobject null c font p font pwnd get font if p font logfont lf p font get log font lf lf lf weight fw bold verify m fontbold create font indirect lf int i text height 0 int i max col1 width 0 int i max col2 width 0 int i max single line width 0 c size siz text 0 int i pos 0 while i pos 1 c string str line get next string str text t n i pos int i colon str line find t if i colon 1 c font p old font m bcol1bold pdc select object m fontbold null c size siz pdc get text extent str line i colon 1 if p old font pdc select object p old font i max col1 width max i max col1 width siz cx i text height siz cy update height with col1 string because col2 string might be empty and therefore has no height siz text cy siz cy lpctstr psz col2 lpctstr str line i colon 1 while istspace psz col2 psz col2 if psz col2 t 0 siz pdc get text extent psz col2 lpctstr str line str line get length psz col2 i max col2 width max i max col2 width siz cx else if str line is empty c size siz pdc get text extent str line i max single line width max i max single line width siz cx siz text cy siz cy else c size siz pdc get text extent t 1 siz text cy siz cy i max col1 width min m iscreenwidth4 i max col1 width i max col2 width min m iscreenwidth4 2 i max col2 width const int i middle margin 6 i max single line width max i max single line width i max col1 width i middle margin i max col2 width siz text cx i max single line width rc wnd right rc wnd left rc border left siz text cx rc border right rc wnd bottom rc wnd top rc border top siz text cy rc border bottom if rc wnd left m rcscreen left if rc wnd right m rcscreen right rc wnd width m rcscreen width rc wnd offset rect rc wnd right m rcscreen right 0 if rc wnd top m rcscreen top if rc wnd bottom m rcscreen bottom rc wnd height m rcscreen height rc wnd offset rect 0 rc wnd bottom m rcscreen bottom pwnd move window rc wnd pwnd screen to client rc wnd pdc fill solid rect rc wnd m crtooltipbkcolor c point pt text pnmcd nmcd rc left pnmcd nmcd rc top i pos 0 while i pos 1 c string str line get next string str text t n i pos int i colon str line find t if i colon 1 c rect rcdt pt text x pt text y pt text x i max col1 width pt text y i text height don t draw empty col1 strings they are still handy to use for skipping the col1 space if i colon 0 c font p old font m bcol1bold pdc select object m fontbold null pdc draw text str line i colon 1 rcdt m dwcol1drawtextflags if p old font pdc select object p old font lpctstr psz col2 lpctstr str line i colon 1 while istspace psz col2 psz col2 if psz col2 t 0 rcdt left pt text x i max col1 width i middle margin rcdt right rcdt left i max col2 width pdc draw text psz col2 lpctstr str line str line get length psz col2 rcdt m dwcol2drawtextflags pt text y i text height else c size siz pdc tabbed text out pt text x pt text y str line 0 null 0 pt text y siz cy p result cdrf skipdefault return p result cdrf dodefault ctooltipctrlx onnmcustomdraw presult reinterpret_cast dwdrawstage cdds_prepaint cwnd cwnd fromhandle hwndfrom fromhandle cstring strtext getwindowtext strtext crect rcwnd getwindowrect rcwnd crect rcborder rcborder rcwnd rcborder rcwnd rcborder rcwnd rcborder rcwnd m_bcol1bold m_fontbold m_hobject cfont pfont getfont pfont pfont getlogfont lfweight fw_bold m_fontbold createfontindirect itextheight imaxcol1width imaxcol2width imaxsinglelinewidth csize siztext ipos ipos cstring strline getnextstring strtext _t ipos icolon strline _t icolon cfont poldfont m_bcol1bold selectobject m_fontbold csize gettextextent strline icolon poldfont selectobject poldfont imaxcol1width imaxcol1width itextheight siztext pszcol2 strline icolon _istspace pszcol2 pszcol2 pszcol2 _t gettextextent pszcol2 strline strline getlength pszcol2 imaxcol2width imaxcol2width strline isempty csize gettextextent strline imaxsinglelinewidth imaxsinglelinewidth siztext csize gettextextent _t siztext imaxcol1width m_iscreenwidth4 imaxcol1width imaxcol2width m_iscreenwidth4 imaxcol2width imiddlemargin imaxsinglelinewidth imaxsinglelinewidth imaxcol1width imiddlemargin imaxcol2width siztext imaxsinglelinewidth rcwnd rcwnd rcborder siztext rcborder rcwnd rcwnd rcborder siztext rcborder rcwnd m_rcscreen rcwnd m_rcscreen rcwnd m_rcscreen rcwnd offsetrect rcwnd m_rcscreen rcwnd m_rcscreen rcwnd m_rcscreen rcwnd m_rcscreen rcwnd offsetrect rcwnd m_rcscreen movewindow rcwnd screentoclient rcwnd fillsolidrect rcwnd m_crtooltipbkcolor cpoint pttext ipos ipos cstring strline getnextstring strtext _t ipos icolon strline _t icolon crect pttext pttext pttext imaxcol1width pttext itextheight icolon cfont poldfont m_bcol1bold selectobject m_fontbold drawtext strline icolon m_dwcol1drawtextflags poldfont selectobject poldfont pszcol2 strline icolon _istspace pszcol2 pszcol2 pszcol2 _t pttext imaxcol1width imiddlemargin imaxcol2width drawtext pszcol2 strline strline getlength pszcol2 m_dwcol2drawtextflags pttext itextheight csize tabbedtextout pttext pttext strline pttext presult cdrf_skipdefault presult cdrf_dodefault void c tool tip ctrlx onnm theme changed nmhdr pnmhdr lresult p result reset system metrics p result 0 ctooltipctrlx onnmthemechanged presult resetsystemmetrics presult void c tool tip ctrlx on sys color change reset system metrics c tool tip ctrl on sys color change ctooltipctrlx onsyscolorchange resetsystemmetrics ctooltipctrl onsyscolorchange void c tool tip ctrlx on setting change uint u flags lpctstr lpsz section reset system metrics c tool tip ctrl on setting change u flags lpsz section ctooltipctrlx onsettingchange uflags lpszsection resetsystemmetrics ctooltipctrl onsettingchange uflags lpszsection c list view walker property sheet c list ctrl item walk p list ctrl m plistctrl p list ctrl clistviewwalkerpropertysheet clistctrlitemwalk plistctrl m_plistctrl plistctrl c list view walker property sheet c list view walker property sheet uint nid caption c wnd p parent wnd uint i select page c resizable sheet nid caption p parent wnd i select page clistviewwalkerpropertysheet clistviewwalkerpropertysheet nidcaption cwnd pparentwnd iselectpage cresizablesheet nidcaption pparentwnd iselectpage c list view walker property sheet c list view walker property sheet lpctstr psz caption c wnd p parent wnd uint i select page c resizable sheet psz caption p parent wnd i select page clistviewwalkerpropertysheet clistviewwalkerpropertysheet pszcaption cwnd pparentwnd iselectpage cresizablesheet pszcaption pparentwnd iselectpage c list view walker property sheet c list view walker property sheet clistviewwalkerpropertysheet clistviewwalkerpropertysheet void c list view walker property sheet change data c object p obj m aitems remove all m aitems add p obj send message um data changed for int i page 0 i page get page count i page c property page p page get page i page if p page p page m hwnd p page send message um data changed p page set modified false get active page on set active clistviewwalkerpropertysheet changedata cobject pobj m_aitems removeall m_aitems pobj sendmessage um_data_changed ipage ipage getpagecount ipage cpropertypage ppage getpage ipage ppage ppage m_hwnd ppage sendmessage um_data_changed ppage setmodified getactivepage onsetactive bool c list view walker property sheet on init dialog bool b result c resizable sheet on init dialog add additional controls if m plistctrl null switching from multi selection to single selection is currently not supported disable up down controls dword dw ctrl style m aitems get size 1 ws disabled 0 const struct c button p ctl btn uint u ctl id lpctstr psz label lpctstr psz symbol dword dw style a ctrls m ctlprev idc prev t prev t 5 ws child ws visible ws group ws tabstop m ctlnext idc next t next t 6 ws child ws visible ws group ws tabstop int i left most button id idok int i max 32767 static const int aipropsheetbuttons idok idcancel id apply now idhelp for int i 0 i arrsize aipropsheetbuttons i c wnd p btn get dlg item aipropsheetbuttons i if p btn p btn is window visible c rect rc btn p btn get window rect rc btn screen to client rc btn if rc btn left i max i max rc btn left i left most button id aipropsheetbuttons i c wnd pctl ok get dlg item i left most button id c rect rc ok pctl ok get window rect rc ok screen to client rc ok c font p def ctrl font pctl ok get font for int i 0 i arrsize a ctrls i const int i navi btn width rc ok width 2 c rect rc rc left rc ok left 8 i navi btn width arrsize a ctrls i rc top rc ok top rc right rc left i navi btn width rc bottom rc top rc ok height verify a ctrls i p ctl btn create a ctrls i psz label dw ctrl style a ctrls i dw style rc this a ctrls i u ctl id if the app m fontsymbol m hobject a ctrls i p ctl btn set font the app m fontsymbol a ctrls i p ctl btn set window text a ctrls i psz symbol show down arrow else a ctrls i p ctl btn set font p def ctrl font add anchor a ctrls i p ctl btn bottom right return b result clistviewwalkerpropertysheet oninitdialog bresult cresizablesheet oninitdialog m_plistctrl dwctrlstyle m_aitems getsize ws_disabled cbutton pctlbtn uctlid pszlabel pszsymbol dwstyle actrls m_ctlprev idc_prev _t _t ws_child ws_visible ws_group ws_tabstop m_ctlnext idc_next _t _t ws_child ws_visible ws_group ws_tabstop ileftmostbuttonid imax _aipropsheetbuttons id_apply_now _aipropsheetbuttons cwnd pbtn getdlgitem _aipropsheetbuttons pbtn pbtn iswindowvisible crect rcbtn pbtn getwindowrect rcbtn screentoclient rcbtn rcbtn imax imax rcbtn ileftmostbuttonid _aipropsheetbuttons cwnd pctlok getdlgitem ileftmostbuttonid crect rcok pctlok getwindowrect rcok screentoclient rcok cfont pdefctrlfont pctlok getfont actrls inavibtnwidth rcok crect rcok inavibtnwidth actrls rcok inavibtnwidth rcok actrls pctlbtn actrls pszlabel dwctrlstyle actrls dwstyle actrls uctlid theapp m_fontsymbol m_hobject actrls pctlbtn setfont theapp m_fontsymbol actrls pctlbtn setwindowtext actrls pszsymbol actrls pctlbtn setfont pdefctrlfont addanchor actrls pctlbtn bottom_right bresult void c list view walker property sheet on next assert m plistctrl null if m plistctrl null return c object p obj m plistctrl get next selectable item if p obj change data p obj else message beep mb ok clistviewwalkerpropertysheet onnext m_plistctrl m_plistctrl cobject pobj m_plistctrl getnextselectableitem pobj changedata pobj messagebeep mb_ok void c list view walker property sheet on prev assert m plistctrl null if m plistctrl null return c object p obj m plistctrl get prev selectable item if p obj change data p obj else message beep mb ok clistviewwalkerpropertysheet onprev m_plistctrl m_plistctrl cobject pobj m_plistctrl getprevselectableitem pobj changedata pobj messagebeep mb_ok c resizable page c client detail page idd 0 m paclients null m bdatachanged false cresizablepage cclientdetailpage m_paclients m_bdatachanged c client detail page c client detail page cclientdetailpage cclientdetailpage void c client detail page localize get dlg item idc static30 set window text get res string ids cd general get dlg item idc static31 set window text get res string ids cd uname get dlg item idc static32 set window text get res string ids cd uhash get dlg item idc static33 set window text get res string ids cd csoft t get dlg item idc static35 set window text get res string ids cd sip get dlg item idc static38 set window text get res string ids cd sname get dlg item idc static40 set window text get res string ids cd trans get dlg item idc static41 set window text get res string ids cd cdown get dlg item idc static42 set window text get res string ids cd down get dlg item idc static43 set window text get res string ids cd adown get dlg item idc static44 set window text get res string ids cd tdown get dlg item idc static45 set window text get res string ids cd up get dlg item idc static46 set window text get res string ids cd aup get dlg item idc static47 set window text get res string ids cd tup get dlg item idc static48 set window text get res string ids cd uploadreq get dlg item idc static50 set window text get res string ids cd scores get dlg item idc static51 set window text get res string ids cd mod get dlg item idc static52 set window text get res string ids cd rating get dlg item idc static53 set window text get res string ids cd uscore get dlg item idc static133x set window text get res string ids cd ident get dlg item idc clientdetail kad set window text get res string ids kademlia t cclientdetailpage getdlgitem idc_static30 setwindowtext getresstring ids_cd_general getdlgitem idc_static31 setwindowtext getresstring ids_cd_uname getdlgitem idc_static32 setwindowtext getresstring ids_cd_uhash getdlgitem idc_static33 setwindowtext getresstring ids_cd_csoft _t getdlgitem idc_static35 setwindowtext getresstring ids_cd_sip getdlgitem idc_static38 setwindowtext getresstring ids_cd_sname getdlgitem idc_static40 setwindowtext getresstring ids_cd_trans getdlgitem idc_static41 setwindowtext getresstring ids_cd_cdown getdlgitem idc_static42 setwindowtext getresstring ids_cd_down getdlgitem idc_static43 setwindowtext getresstring ids_cd_adown getdlgitem idc_static44 setwindowtext getresstring ids_cd_tdown getdlgitem idc_static45 setwindowtext getresstring ids_cd_up getdlgitem idc_static46 setwindowtext getresstring ids_cd_aup getdlgitem idc_static47 setwindowtext getresstring ids_cd_tup getdlgitem idc_static48 setwindowtext getresstring ids_cd_uploadreq getdlgitem idc_static50 setwindowtext getresstring ids_cd_scores getdlgitem idc_static51 setwindowtext getresstring ids_cd_mod getdlgitem idc_static52 setwindowtext getresstring ids_cd_rating getdlgitem idc_static53 setwindowtext getresstring ids_cd_uscore getdlgitem idc_static133x setwindowtext getresstring ids_cd_ident getdlgitem idc_clientdetail_kad setwindowtext getresstring ids_kademlia _t bool c client detail page on init dialog c resizable page on init dialog init window styles this add anchor idc static30 top left top right add anchor idc static40 top left top right add anchor idc static50 top left top right add anchor idc ddownloading top left top right add anchor idc uploading top left top right localize return true cclientdetailpage oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_static30 top_left top_right addanchor idc_static40 top_left top_right addanchor idc_static50 top_left top_right addanchor idc_ddownloading top_left top_right addanchor idc_uploading top_left top_right void c client detail page do data exchange c data exchange pdx c resizable page do data exchange pdx cclientdetailpage dodataexchange cdataexchange cresizablepage dodataexchange bool c client detail page on set active if c resizable page on set active return false if m bdatachanged c up down client client static downcast c up down client m paclients 0 c string buffer if client get user name get dlg item idc dname set window text client get user name else get dlg item idc dname set window text t if client has valid hash get dlg item idc dhash set window text md4str client get user hash else get dlg item idc dhash set window text t get dlg item idc dsoft set window text client get client soft ver buffer format t s client has lowid get res string ids idlow get res string ids idhigh get dlg item idc did set window text buffer if client get serverip c string str serverip ipstr client get serverip get dlg item idc dsip set window text str serverip c server cserver the app serverlist get server by address str serverip client get server port if cserver get dlg item idc dsname set window text cserver get list name else get dlg item idc dsname set window text t else get dlg item idc dsip set window text t get dlg item idc dsname set window text t c known file file the app sharedfiles get file byid client get upload fileid if file get dlg item idc ddownloading set window text file get file name else get dlg item idc ddownloading set window text t if client get request file get dlg item idc uploading set window text client get request file get file name else get dlg item idc uploading set window text t get dlg item idc ddup set window text cast itox bytes client get transferred down false false get dlg item idc ddown set window text cast itox bytes client get transferred up false false buffer format t s cast itox bytes client get download datarate false true get dlg item idc davur set window text buffer buffer format t s cast itox bytes client get datarate false true get dlg item idc davdr set window text buffer if client credits get dlg item idc duptotal set window text cast itox bytes client credits get downloaded total false false get dlg item idc ddowntotal set window text cast itox bytes client credits get uploaded total false false buffer format t 1f float client credits get score ratio client getip get dlg item idc dratio set window text buffer if the app clientcredits crypto available switch client credits get current ident state client getip case is notavailable get dlg item idc cdident set window text get res string ids identnosupport break case is idfailed case is idneeded case is idbadguy get dlg item idc cdident set window text get res string ids identfailed break case is identified get dlg item idc cdident set window text get res string ids identok break else get dlg item idc cdident set window text get res string ids identnosupport else get dlg item idc ddowntotal set window text t get dlg item idc duptotal set window text t get dlg item idc dratio set window text t get dlg item idc cdident set window text t if client get user name client credits null buffer format t 1f float client get score false client is downloading true get dlg item idc drating set window text buffer else get dlg item idc drating set window text t if client get upload state us none client credits null if client get friend slot buffer format t u client get score false client is downloading false get dlg item idc dscore set window text buffer else get dlg item idc dscore set window text get res string ids frienddetail else get dlg item idc dscore set window text t if client get kad port buffer format t s get res string ids connected else buffer format t s get res string ids disconnected get dlg item idc clientdetail kadcon set window text buffer m bdatachanged false return true cclientdetailpage onsetactive cresizablepage onsetactive m_bdatachanged cupdownclient static_downcast cupdownclient m_paclients cstring getusername getdlgitem idc_dname setwindowtext getusername getdlgitem idc_dname setwindowtext _t hasvalidhash getdlgitem idc_dhash setwindowtext getuserhash getdlgitem idc_dhash setwindowtext _t getdlgitem idc_dsoft setwindowtext getclientsoftver _t haslowid getresstring ids_idlow getresstring ids_idhigh getdlgitem idc_did setwindowtext getserverip cstring strserverip getserverip getdlgitem idc_dsip setwindowtext strserverip cserver theapp getserverbyaddress strserverip getserverport getdlgitem idc_dsname setwindowtext getlistname getdlgitem idc_dsname setwindowtext _t getdlgitem idc_dsip setwindowtext _t getdlgitem idc_dsname setwindowtext _t cknownfile theapp getfilebyid getuploadfileid getdlgitem idc_ddownloading setwindowtext getfilename getdlgitem idc_ddownloading setwindowtext _t getrequestfile getdlgitem idc_uploading setwindowtext getrequestfile getfilename getdlgitem idc_uploading setwindowtext _t getdlgitem idc_ddup setwindowtext castitoxbytes gettransferreddown getdlgitem idc_ddown setwindowtext castitoxbytes gettransferredup _t castitoxbytes getdownloaddatarate getdlgitem idc_davur setwindowtext _t castitoxbytes getdatarate getdlgitem idc_davdr setwindowtext getdlgitem idc_duptotal setwindowtext castitoxbytes getdownloadedtotal getdlgitem idc_ddowntotal setwindowtext castitoxbytes getuploadedtotal _t getscoreratio getdlgitem idc_dratio setwindowtext theapp cryptoavailable getcurrentidentstate is_notavailable getdlgitem idc_cdident setwindowtext getresstring ids_identnosupport is_idfailed is_idneeded is_idbadguy getdlgitem idc_cdident setwindowtext getresstring ids_identfailed is_identified getdlgitem idc_cdident setwindowtext getresstring ids_identok getdlgitem idc_cdident setwindowtext getresstring ids_identnosupport getdlgitem idc_ddowntotal setwindowtext _t getdlgitem idc_duptotal setwindowtext _t getdlgitem idc_dratio setwindowtext _t getdlgitem idc_cdident setwindowtext _t getusername _t getscore isdownloading getdlgitem idc_drating setwindowtext getdlgitem idc_drating setwindowtext _t getuploadstate us_none getfriendslot _t getscore isdownloading getdlgitem idc_dscore setwindowtext getdlgitem idc_dscore setwindowtext getresstring ids_frienddetail getdlgitem idc_dscore setwindowtext _t getkadport _t getresstring ids_connected _t getresstring ids_disconnected getdlgitem idc_clientdetail_kadcon setwindowtext m_bdatachanged lresult c client detail page on data changed wparam lparam m bdatachanged true return 1 cclientdetailpage ondatachanged m_bdatachanged c list view walker property sheet p list ctrl m aitems add p client construct clistviewwalkerpropertysheet plistctrl m_aitems pclient c client detail dialog c client detail dialog cclientdetaildialog cclientdetaildialog void c client detail dialog construct m psh dw flags psh hashelp m psh dw flags psh noapplynow m wndclient m psp dw flags psp hashelp m wndclient m psp dw flags psp useiconid m wndclient m psp psz icon t clientdetails m wndclient set clients m aitems add page m wndclient cclientdetaildialog m_psh dwflags psh_hashelp m_psh dwflags psh_noapplynow m_wndclient m_psp dwflags psp_hashelp m_wndclient m_psp dwflags psp_useiconid m_wndclient m_psp pszicon _t m_wndclient setclients m_aitems addpage m_wndclient bool c client detail dialog on init dialog enable stacked tabs false bool b result c list view walker property sheet on init dialog high color tab update image list this init window styles this enable save restore t client detail dialog call this after on init dialog set window text get res string ids cd title return b result cclientdetaildialog oninitdialog enablestackedtabs bresult clistviewwalkerpropertysheet oninitdialog highcolortab updateimagelist initwindowstyles enablesaverestore _t clientdetaildialog oninitdialog setwindowtext getresstring ids_cd_title bresult void c client detail dialog on destroy c list view walker property sheet on destroy cclientdetaildialog ondestroy clistviewwalkerpropertysheet ondestroy c resizable dialog c chat wnd idd p parent icon friend null icon msg null cresizabledialog cchatwnd pparent icon_friend icon_msg c chat wnd c chat wnd if icon friend verify destroy icon icon friend if icon msg verify destroy icon icon msg cchatwnd cchatwnd icon_friend destroyicon icon_friend icon_msg destroyicon icon_msg void c chat wnd scroll history bool down c string buffer c chat item ci chatselector get current chat item if ci null return if ci history pos 0 down ci history pos ci history get count down return if down ci history pos else ci history pos buffer ci history pos ci history get count t ci history get at ci history pos inputtext set window text buffer inputtext set sel buffer get length buffer get length cchatwnd scrollhistory cstring cchatitem getcurrentchatitem history_pos history_pos getcount history_pos history_pos history_pos getcount _t getat history_pos setwindowtext setsel getlength getlength void c chat wnd start session c up down client client if client get user name return the app emuledlg set active dialog this chatselector start session client true cchatwnd startsession cupdownclient getusername theapp setactivedialog startsession void c chat wnd localize get dlg item idc friends lbl set window text get res string ids cw friends get dlg item idc messages lbl set window text get res string ids cw messages m cuserinfo set window text get res string ids info get dlg item idc friends downloaded set window text get res string ids chat downloaded get dlg item idc friends uploaded set window text get res string ids chat uploaded get dlg item idc friends ident set window text get res string ids chat ident get dlg item idc friends client set window text get res string ids cd csoft get dlg item idc friends name set window text get res string ids cd uname get dlg item idc friends userhash set window text get res string ids cd uhash chatselector localize m friendlistctrl localize cchatwnd getdlgitem idc_friends_lbl setwindowtext getresstring ids_cw_friends getdlgitem idc_messages_lbl setwindowtext getresstring ids_cw_messages m_cuserinfo setwindowtext getresstring ids_info getdlgitem idc_friends_downloaded setwindowtext getresstring ids_chat_downloaded getdlgitem idc_friends_uploaded setwindowtext getresstring ids_chat_uploaded getdlgitem idc_friends_ident setwindowtext getresstring ids_chat_ident getdlgitem idc_friends_client setwindowtext getresstring ids_cd_csoft getdlgitem idc_friends_name setwindowtext getresstring ids_cd_uname getdlgitem idc_friends_userhash setwindowtext getresstring ids_cd_uhash m_friendlistctrl void c chat wnd update friendlist count uint count c string temp temp format t i count temp get res string ids cw friends temp get dlg item idc friends lbl set window text temp cchatwnd updatefriendlistcount cstring _t getresstring ids_cw_friends getdlgitem idc_friends_lbl setwindowtext void c chat wnd show friend msg details c friend p friend if p friend c string buffer name if p friend get linked client get dlg item idc friends name edit set window text p friend get linked client get user name else if p friend m strname t get dlg item idc friends name edit set window text p friend m strname else get dlg item idc friends name edit set window text t hash if p friend get linked client get dlg item idc friends userhash edit set window text md4str p friend get linked client get user hash else if p friend m dwhashash get dlg item idc friends userhash edit set window text md4str p friend m abyuserhash else get dlg item idc friends userhash edit set window text t client if p friend get linked client get dlg item idc friends cliente edit set window text p friend get linked client get client soft ver else get dlg item idc friends cliente edit set window text t identification if p friend get linked client p friend get linked client credits if the app clientcredits crypto available switch p friend get linked client credits get current ident state p friend get linked client getip case is notavailable get dlg item idc friends identificacion edit set window text get res string ids identnosupport break case is idfailed case is idneeded case is idbadguy get dlg item idc friends identificacion edit set window text get res string ids identfailed break case is identified get dlg item idc friends identificacion edit set window text get res string ids identok break else get dlg item idc friends identificacion edit set window text get res string ids identnosupport else get dlg item idc friends identificacion edit set window text t upload and downloaded if p friend get linked client p friend get linked client credits get dlg item idc friends descargado edit set window text cast itox bytes p friend get linked client credits get downloaded total false false else get dlg item idc friends descargado edit set window text t if p friend get linked client p friend get linked client credits get dlg item idc friends subido edit set window text cast itox bytes p friend get linked client credits get uploaded total false false else get dlg item idc friends subido edit set window text t else get dlg item idc friends name edit set window text t get dlg item idc friends userhash edit set window text t get dlg item idc friends cliente edit set window text t get dlg item idc friends identificacion edit set window text t get dlg item idc friends descargado edit set window text t get dlg item idc friends subido edit set window text t cchatwnd showfriendmsgdetails cfriend pfriend pfriend cstring pfriend getlinkedclient getdlgitem idc_friends_name_edit setwindowtext pfriend getlinkedclient getusername pfriend m_strname _t getdlgitem idc_friends_name_edit setwindowtext pfriend m_strname getdlgitem idc_friends_name_edit setwindowtext _t pfriend getlinkedclient getdlgitem idc_friends_userhash_edit setwindowtext pfriend getlinkedclient getuserhash pfriend m_dwhashash getdlgitem idc_friends_userhash_edit setwindowtext pfriend m_abyuserhash getdlgitem idc_friends_userhash_edit setwindowtext _t pfriend getlinkedclient getdlgitem idc_friends_cliente_edit setwindowtext pfriend getlinkedclient getclientsoftver getdlgitem idc_friends_cliente_edit setwindowtext _t pfriend getlinkedclient pfriend getlinkedclient theapp cryptoavailable pfriend getlinkedclient getcurrentidentstate pfriend getlinkedclient is_notavailable getdlgitem idc_friends_identificacion_edit setwindowtext getresstring ids_identnosupport is_idfailed is_idneeded is_idbadguy getdlgitem idc_friends_identificacion_edit setwindowtext getresstring ids_identfailed is_identified getdlgitem idc_friends_identificacion_edit setwindowtext getresstring ids_identok getdlgitem idc_friends_identificacion_edit setwindowtext getresstring ids_identnosupport getdlgitem idc_friends_identificacion_edit setwindowtext _t pfriend getlinkedclient pfriend getlinkedclient getdlgitem idc_friends_descargado_edit setwindowtext castitoxbytes pfriend getlinkedclient getdownloadedtotal getdlgitem idc_friends_descargado_edit setwindowtext _t pfriend getlinkedclient pfriend getlinkedclient getdlgitem idc_friends_subido_edit setwindowtext castitoxbytes pfriend getlinkedclient getuploadedtotal getdlgitem idc_friends_subido_edit setwindowtext _t getdlgitem idc_friends_name_edit setwindowtext _t getdlgitem idc_friends_userhash_edit setwindowtext _t getdlgitem idc_friends_cliente_edit setwindowtext _t getdlgitem idc_friends_identificacion_edit setwindowtext _t getdlgitem idc_friends_descargado_edit setwindowtext _t getdlgitem idc_friends_subido_edit setwindowtext _t void c chat wnd set all icons init window styles this if icon friend verify destroy icon icon friend if icon msg verify destroy icon icon msg icon friend the app load icon t friend 16 16 icon msg the app load icon t message 16 16 c static get dlg item idc messageicon set icon icon msg c static get dlg item idc friendsicon set icon icon friend m cuserinfo set icon t info cchatwnd setallicons initwindowstyles icon_friend destroyicon icon_friend icon_msg destroyicon icon_msg icon_friend theapp loadicon _t icon_msg theapp loadicon _t cstatic getdlgitem idc_messageicon seticon icon_msg cstatic getdlgitem idc_friendsicon seticon icon_friend m_cuserinfo seticon _t void c chat wnd do resize int delta c splitter control change width get dlg item idc list2 delta c splitter control change width get dlg item idc friends msg delta c splitter control change width get dlg item idc friends name edit delta c splitter control change width get dlg item idc friends userhash edit delta c splitter control change width get dlg item idc friends cliente edit delta c splitter control change width get dlg item idc friends identificacion edit delta c splitter control change width get dlg item idc friends subido edit delta c splitter control change width get dlg item idc friends descargado edit delta c splitter control change width get dlg item idc chatsel delta cw rightalign c splitter control change pos get dlg item idc messages lbl delta 0 c splitter control change pos get dlg item idc messageicon delta 0 c rect rcw get window rect rcw screen to client rcw c rect rcspl get dlg item idc list2 get client rect rcspl the prefs set splitterbar position friend rcspl right remove anchor m wndsplitterchat add anchor m wndsplitterchat top left remove anchor idc list2 add anchor idc list2 top left bottom left remove anchor idc friends msg add anchor idc friends msg bottom left bottom left remove anchor idc chatsel add anchor idc chatsel top left bottom right remove anchor idc messages lbl add anchor idc messages lbl top left remove anchor idc messageicon add anchor idc messageicon top left remove anchor idc friends name edit remove anchor idc friends userhash edit remove anchor idc friends cliente edit remove anchor idc friends identificacion edit remove anchor idc friends subido edit remove anchor idc friends descargado edit add anchor idc friends name edit bottom left add anchor idc friends userhash edit bottom left add anchor idc friends cliente edit bottom left add anchor idc friends identificacion edit bottom left add anchor idc friends subido edit bottom left add anchor idc friends descargado edit bottom left m wndsplitterchat set range rcw left splitter range width rcw left splitter range height m friendlistctrl save settings m friendlistctrl delete column 0 m friendlistctrl init invalidate update window cchatwnd doresize csplittercontrol changewidth getdlgitem idc_list2 csplittercontrol changewidth getdlgitem idc_friends_msg csplittercontrol changewidth getdlgitem idc_friends_name_edit csplittercontrol changewidth getdlgitem idc_friends_userhash_edit csplittercontrol changewidth getdlgitem idc_friends_cliente_edit csplittercontrol changewidth getdlgitem idc_friends_identificacion_edit csplittercontrol changewidth getdlgitem idc_friends_subido_edit csplittercontrol changewidth getdlgitem idc_friends_descargado_edit csplittercontrol changewidth getdlgitem idc_chatsel cw_rightalign csplittercontrol changepos getdlgitem idc_messages_lbl csplittercontrol changepos getdlgitem idc_messageicon crect getwindowrect screentoclient crect getdlgitem idc_list2 getclientrect theprefs setsplitterbarpositionfriend removeanchor m_wndsplitterchat addanchor m_wndsplitterchat top_left removeanchor idc_list2 addanchor idc_list2 top_left bottom_left removeanchor idc_friends_msg addanchor idc_friends_msg bottom_left bottom_left removeanchor idc_chatsel addanchor idc_chatsel top_left bottom_right removeanchor idc_messages_lbl addanchor idc_messages_lbl top_left removeanchor idc_messageicon addanchor idc_messageicon top_left removeanchor idc_friends_name_edit removeanchor idc_friends_userhash_edit removeanchor idc_friends_cliente_edit removeanchor idc_friends_identificacion_edit removeanchor idc_friends_subido_edit removeanchor idc_friends_descargado_edit addanchor idc_friends_name_edit bottom_left addanchor idc_friends_userhash_edit bottom_left addanchor idc_friends_cliente_edit bottom_left addanchor idc_friends_identificacion_edit bottom_left addanchor idc_friends_subido_edit bottom_left addanchor idc_friends_descargado_edit bottom_left m_wndsplitterchat setrange splitter_range_width splitter_range_height m_friendlistctrl savesettings m_friendlistctrl deletecolumn m_friendlistctrl updatewindow void c chat wnd do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc chatsel chatselector ddx control pdx idc list2 m friendlistctrl ddx control pdx idc cmessage inputtext ddx control pdx idc friends msg m cuserinfo cchatwnd dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_chatsel ddx_control idc_list2 m_friendlistctrl ddx_control idc_cmessage ddx_control idc_friends_msg m_cuserinfo bool c chat wnd on init dialog c resizable dialog on init dialog inputtext set limit text max client msg len chatselector init m friendlistctrl init set all icons c rect rc spl get dlg item idc list2 get window rect rc spl screen to client rc spl c rect rc get window rect rc screen to client rc rc spl bottom rc bottom 5 rc spl left rc spl right splitter margin rc spl right rc spl left splitter width m wndsplitterchat create ws child ws visible rc spl this idc splitter friend int pos stat vinit rc spl left int pos stat vnew the prefs get splitterbar position friend uint max splitter range height uint min splitter range width if the prefs get splitterbar position friend max pos stat vnew max else if the prefs get splitterbar position friend min pos stat vnew min rc spl left pos stat vnew rc spl right pos stat vnew splitter width m wndsplitterchat move window rc spl do resize pos stat vnew pos stat vinit add anchor idc friendsicon top left add anchor idc friends lbl top left add anchor idc friends name bottom left add anchor idc friends userhash bottom left add anchor idc friends client bottom left add anchor idc friends ident bottom left add anchor idc friends uploaded bottom left add anchor idc friends downloaded bottom left localize the app friendlist show friends return true cchatwnd oninitdialog cresizabledialog oninitdialog setlimittext max_client_msg_len m_friendlistctrl setallicons crect rcspl getdlgitem idc_list2 getwindowrect rcspl screentoclient rcspl crect getwindowrect screentoclient rcspl rcspl rcspl splitter_margin rcspl rcspl splitter_width m_wndsplitterchat ws_child ws_visible rcspl idc_splitter_friend posstatvinit rcspl posstatvnew theprefs getsplitterbarpositionfriend splitter_range_height splitter_range_width theprefs getsplitterbarpositionfriend posstatvnew theprefs getsplitterbarpositionfriend posstatvnew rcspl posstatvnew rcspl posstatvnew splitter_width m_wndsplitterchat movewindow rcspl doresize posstatvnew posstatvinit addanchor idc_friendsicon top_left addanchor idc_friends_lbl top_left addanchor idc_friends_name bottom_left addanchor idc_friends_userhash bottom_left addanchor idc_friends_client bottom_left addanchor idc_friends_ident bottom_left addanchor idc_friends_uploaded bottom_left addanchor idc_friends_downloaded bottom_left theapp showfriends bool c chat wnd pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 return false else if p msg message wm keyup if p msg hwnd get dlg item idc list2 m hwnd on lvn item activate frlist 0 0 return c resizable dialog pre translate message p msg cchatwnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control pmsg wm_keyup pmsg getdlgitem idc_list2 m_hwnd onlvnitemactivatefrlist cresizabledialog pretranslatemessage pmsg lresult c chat wnd def window proc uint message wparam w param lparam l param switch message case wm paint if m wndsplitterchat c rect rcw get window rect rcw screen to client rcw if rcw width 0 c rect rctree get dlg item idc list2 get window rect rctree screen to client rctree c rect rc spl rc spl left rctree right splitter margin rc spl right rc spl left splitter width rc spl top rctree top rc spl bottom rcw bottom 5 m wndsplitterchat move window rc spl true m friendlistctrl delete column 0 m friendlistctrl init break case wm notify if w param idc splitter friend spc nmhdr p hdr spc nmhdr l param do resize p hdr delta break case wm windowposchanged c rect rcw get window rect rcw screen to client rcw if m wndsplitterchat rcw width 0 invalidate break case wm size if m wndsplitterchat c rect rc get window rect rc screen to client rc m wndsplitterchat set range rc left splitter range width rc left splitter range height break return c resizable dialog def window proc message w param l param cchatwnd defwindowproc wparam lparam wm_paint m_wndsplitterchat crect getwindowrect screentoclient crect getdlgitem idc_list2 getwindowrect screentoclient crect rcspl rcspl splitter_margin rcspl rcspl splitter_width rcspl rcspl m_wndsplitterchat movewindow rcspl m_friendlistctrl deletecolumn m_friendlistctrl wm_notify wparam idc_splitter_friend spc_nmhdr phdr spc_nmhdr lparam doresize phdr wm_windowposchanged crect getwindowrect screentoclient m_wndsplitterchat wm_size m_wndsplitterchat crect getwindowrect screentoclient m_wndsplitterchat setrange splitter_range_width splitter_range_height cresizabledialog defwindowproc wparam lparam void c chat wnd on show window bool b show uint n status if b show chatselector show chat cchatwnd onshowwindow bshow nstatus bshow showchat void c chat wnd on sys color change c resizable dialog on sys color change set all icons cchatwnd onsyscolorchange cresizabledialog onsyscolorchange setallicons lresult c chat wnd on close tab wparam w param lparam l param tcitem item 0 item mask tcif param if chatselector get item int w param item chatselector end session c chat item item l param client return true cchatwnd onclosetab wparam lparam tcif_param getitem wparam endsession cchatitem lparam bool c chat wnd on help info helpinfo p help info the app show help emule faq friends return true cchatwnd onhelpinfo phelpinfo theapp showhelp emule_faq_friends void c chat wnd on lvn item activate frlist nmhdr pnmhdr lresult p result int i sel m friendlistctrl get selection mark if i sel 1 c friend p friend c friend m friendlistctrl get item data i sel show friend msg details p friend else show friend msg details null cchatwnd onlvnitemactivatefrlist presult isel m_friendlistctrl getselectionmark isel cfriend pfriend cfriend m_friendlistctrl getitemdata isel showfriendmsgdetails pfriend showfriendmsgdetails void c chat wnd onnm click frlist nmhdr pnmhdr lresult p result on lvn item activate frlist pnmhdr p result p result 0 cchatwnd onnmclickfrlist presult onlvnitemactivatefrlist presult presult void c chat wnd on stn dblclick friendsicon the app emuledlg show preferences idd ppg files cchatwnd onstndblclickfriendsicon theapp showpreferences idd_ppg_files cdc assert pdc null some initialization m pdc pdc m oldbitmap null m bmemdc pdc is printing m bflushed false get the rectangle to draw if p rect null pdc get clip box m rect else m rect p rect if m bmemdc create a memory dc create compatibledc pdc pdc l ptodp m rect what is this needed for we can t use that for rtl d cs verify m bitmap create compatible bitmap pdc m rect width m rect height m oldbitmap select object m bitmap set map mode pdc get map mode set window ext pdc get window ext set viewport ext pdc get viewport ext pdc d ptolp m rect what is this needed for we can t use that for rtl d cs set window org m rect left m rect top else m bprinting pdc m bprinting m hdc pdc m hdc m hattribdc pdc m hattribdc fill background fill solid rect m rect pdc get bk color m_pdc m_oldbitmap m_bmemdc isprinting m_bflushed prect getclipbox m_rect m_rect prect m_bmemdc createcompatibledc lptodp m_rect dcs m_bitmap createcompatiblebitmap m_rect m_rect m_oldbitmap selectobject m_bitmap setmapmode getmapmode setwindowext getwindowext setviewportext getviewportext dptolp m_rect dcs setwindoworg m_rect m_rect m_bprinting m_bprinting m_hdc m_hdc m_hattribdc m_hattribdc fillsolidrect m_rect getbkcolor c memdc flush cmemdc temp void flush if m bflushed m bflushed true if m bmemdc copy the offscreen bitmap onto the screen m pdc bit blt m rect left m rect top m rect width m rect height this m rect left m rect top srccopy swap back the original bitmap select object m oldbitmap else m hdc m hattribdc null m_bflushed m_bflushed m_bmemdc m_pdc bitblt m_rect m_rect m_rect m_rect m_rect m_rect selectobject m_oldbitmap m_hdc m_hattribdc c memdc operator return this cmemdc operator c memdc return this cmemdc c sync helper m pobject null csynchelper m_pobject c sync helper if m pobject m pobject unlock csynchelper m_pobject m_pobject uint get found files uint32 searchid const uint return val 0 verify m foundfilescount lookup searchid return val return return val getfoundfiles returnval m_foundfilescount returnval returnval c search list c search list outputwnd null m mobilmulesearch false csearchlist csearchlist m_mobilmulesearch c search list c search list clear csearchlist csearchlist void c search list clear for position pos list get head position pos null delete list get next pos list remove all csearchlist getheadposition getnext removeall void c search list add result count uint32 n searchid const uchar hash uint n count do not count already available or downloading files for the search result limit if the app sharedfiles get file byid hash the app downloadqueue get file byid hash return uint temp value 0 verify m foundsourcescount lookup n searchid temp value m foundsourcescount set at n searchid temp value n count csearchlist addresultcount nsearchid ncount theapp getfilebyid theapp getfilebyid tempvalue m_foundsourcescount nsearchid tempvalue m_foundsourcescount setat nsearchid tempvalue ncount void c search list remove results uint32 n searchid this will not delete the item from the window make sure your code does it if you call this for position pos list get head position pos null position pos last pos c search file cur file list get next pos if cur file get searchid n searchid list remove at pos last delete cur file csearchlist removeresults nsearchid getheadposition poslast csearchfile cur_file getnext cur_file getsearchid nsearchid removeat poslast cur_file void c search list remove result c search file todel for position pos list get head position pos null position pos last pos c search file cur file list get next pos if cur file todel the app emuledlg searchwnd remove result todel list remove at pos last delete todel return csearchlist removeresult csearchfile getheadposition poslast csearchfile cur_file getnext cur_file theapp removeresult removeat poslast void c search list show results uint32 n searchid assert outputwnd outputwnd set redraw false for position pos list get head position pos null const c search file cur file list get next pos if cur file get list parent null cur file get searchid n searchid outputwnd add result cur file if cur file is list expanded cur file get list child count 0 outputwnd update sources cur file outputwnd set redraw true csearchlist showresults nsearchid setredraw getheadposition csearchfile cur_file getnext cur_file getlistparent cur_file getsearchid nsearchid addresult cur_file cur_file islistexpanded cur_file getlistchildcount updatesources cur_file setredraw void c search list get web list cq array search file struct search file struct search file array int i sort by const for position pos list get head position pos null const c search file p file list get next pos if p file null p file get list parent null p file get file size uint64 0 p file get file name is empty continue search file struct struct file struct file m strfilename p file get file name struct file m strfiletype p file get file type display str struct file m strfilehash md4str p file get file hash struct file m usourcecount p file get source count struct file m dwcompletesourcecount p file get complete source count struct file m ufilesize p file get file size switch i sort by case 0 struct file m strindex struct file m strfilename break case 1 struct file m strindex format t 10u struct file m ufilesize break case 2 struct file m strindex struct file m strfilehash break case 3 struct file m strindex format t 09u struct file m usourcecount break case 4 struct file m strindex struct file m strfiletype break default struct file m strindex empty search file array add struct file csearchlist getweblist cqarray searchfilestruct searchfilestruct searchfilearray isortby getheadposition csearchfile pfile getnext pfile pfile getlistparent pfile getfilesize pfile getfilename isempty searchfilestruct structfile structfile m_strfilename pfile getfilename structfile m_strfiletype pfile getfiletypedisplaystr structfile m_strfilehash pfile getfilehash structfile m_usourcecount pfile getsourcecount structfile m_dwcompletesourcecount pfile getcompletesourcecount structfile m_ufilesize pfile getfilesize isortby structfile m_strindex structfile m_strfilename structfile m_strindex _t structfile m_ufilesize structfile m_strindex structfile m_strfilehash structfile m_strindex _t structfile m_usourcecount structfile m_strindex structfile m_strfiletype structfile m_strindex searchfilearray structfile void c search list add file to download by hash const uchar hash int cat for position pos list get head position pos null c search file sf list get next pos if md4cmp hash sf get file hash the app downloadqueue add search to download sf 2 cat break csearchlist addfiletodownloadbyhash getheadposition csearchfile getnext getfilehash theapp addsearchtodownload bool c search list add to list c search file toadd bool b client response if b client response m strresultfiletype is empty tcscmp m strresultfiletype toadd get file type 0 delete toadd return false search for a parent with same filehash and search id as the new search result entry for position pos list get head position pos null c search file parent list get next pos if parent get list parent null parent get searchid toadd get searchid md4cmp parent get file hash toadd get file hash 0 if this parent does not yet have any child entries create one child entry which is equal to the current parent entry needed for gui when expanding the child list if parent get list child count 0 c search file child new c search file parent child set list parent parent int i sources parent get int tag value ft sources if i sources 0 i sources 1 child set list child count i sources list add tail child parent set list child count 1 get the availability of the new search result entry uint u avail if b client response if this is a response from a client view shared files we set the availability at least to 1 if toadd get int tag value ft sources u avail u avail 0 u avail 1 else u avail toadd get int tag value ft sources add the availability of the new search result entry to the total search result count for this search add result count parent get searchid parent get file hash u avail get complete sources of the new search result entry uint32 u complete sources uint32 1 bool b has complete sources toadd get int tag value ft complete sources u complete sources bool b found false if the prefs get debug search result detail level 1 for debugging do not merge search results else check if that parent already has a child with same filename as the new search result entry for position pos2 list get head position pos2 null b found c search file child list get next pos2 if child toadd not the same object child get list parent parent is a child of our result one filehash toadd get file name compare no case child get file name 0 same name b found true add properties of new search result entry to the already available child entry with same filename ed2k use the sum of all values kad use the max values if toadd is kademlia if u avail child get list child count child set list child count u avail else child add list child count u avail child add sources u avail if b has complete sources child add complete sources u complete sources break if b found the parent which we had found does not yet have a child with that new search result s entry name add the new entry as a new child toadd set list parent parent toadd set list child count u avail parent add list child count 1 list add head toadd copy possible available sources from new search result entry to parent if toadd get clientid toadd get client port if is valid search result clientip port toadd get clientid toadd get client port pre filter sources which would be dropped in c part file add sources if c part file can add source toadd get clientid toadd get client port toadd get client serverip toadd get client server port c search file s client client toadd get clientid toadd get client port toadd get client serverip toadd get client server port if parent get clients find client 1 parent add client client else if the prefs get debug server searches level 1 uint32 nip toadd get clientid debug t filtered source from search result s u n dbg get clientid nip toadd get client port copy possible available servers from new search result entry to parent will be used in future if toadd get client serverip toadd get client server port c search file s server server toadd get client serverip toadd get client server port int i found parent get servers find server if i found 1 server m uavail u avail parent add server server else parent get server at i found m uavail u avail uint u all childs source count 0 ed2k sum of all sources kad the max sources found uint u all childs complete source count 0 ed2k sum of all sources kad the max sources found const c search file best entry null for position pos2 list get head position pos2 null const c search file child list get next pos2 if child get list parent parent if parent is kademlia if child get list child count u all childs source count u all childs source count child get list child count if child get complete source count u all childs complete source count not yet supported u all childs complete source count child get complete source count else u all childs source count child get list child count u all childs complete source count child get complete source count if best entry null best entry child else if child get list child count best entry get list child count best entry child if best entry parent set file size best entry get file size parent set file name best entry get file name parent set file type best entry get file type parent clear tags parent copy tags best entry get tags parent set int tag value ft sources u all childs source count parent set int tag value ft complete sources u all childs complete source count update parent in gui if outputwnd m mobilmulesearch outputwnd update sources parent if b found delete toadd return true no bounded result found yet add as parent to list toadd set list parent null if list add tail toadd uint temp value 0 verify m foundfilescount lookup toadd get searchid temp value m foundfilescount set at toadd get searchid temp value 1 get the availability of this new search result entry uint u avail if b client response if this is a response from a client view shared files we set the availability at least to 1 if toadd get int tag value ft sources u avail u avail 0 u avail 1 toadd add sources u avail else u avail toadd get int tag value ft sources add the availability of this new search result entry to the total search result count for this search add result count toadd get searchid toadd get file hash u avail if the prefs get debug search result detail level 1 toadd set list expanded true add parent in gui if outputwnd m mobilmulesearch outputwnd add result toadd return true csearchlist addtolist csearchfile bclientresponse bclientresponse m_strresultfiletype isempty _tcscmp m_strresultfiletype getfiletype getheadposition csearchfile getnext getlistparent getsearchid getsearchid getfilehash getfilehash getlistchildcount csearchfile csearchfile setlistparent isources getinttagvalue ft_sources isources isources setlistchildcount isources addtail setlistchildcount uavail bclientresponse getinttagvalue ft_sources uavail uavail uavail uavail getinttagvalue ft_sources addresultcount getsearchid getfilehash uavail ucompletesources bhascompletesources getinttagvalue ft_complete_sources ucompletesources bfound theprefs getdebugsearchresultdetaillevel getheadposition bfound csearchfile getnext getlistparent getfilename comparenocase getfilename bfound iskademlia uavail getlistchildcount setlistchildcount uavail addlistchildcount uavail addsources uavail bhascompletesources addcompletesources ucompletesources bfound setlistparent setlistchildcount uavail addlistchildcount addhead getclientid getclientport isvalidsearchresultclientipport getclientid getclientport cpartfile addsources cpartfile canaddsource getclientid getclientport getclientserverip getclientserverport csearchfile sclient getclientid getclientport getclientserverip getclientserverport getclients addclient theprefs getdebugserversearcheslevel getclientid _t dbggetclientid getclientport getclientserverip getclientserverport csearchfile sserver getclientserverip getclientserverport ifound getservers ifound m_uavail uavail addserver getserverat ifound m_uavail uavail uallchildssourcecount uallchildscompletesourcecount csearchfile bestentry getheadposition csearchfile getnext getlistparent iskademlia getlistchildcount uallchildssourcecount uallchildssourcecount getlistchildcount getcompletesourcecount uallchildscompletesourcecount uallchildscompletesourcecount getcompletesourcecount uallchildssourcecount getlistchildcount uallchildscompletesourcecount getcompletesourcecount bestentry bestentry getlistchildcount bestentry getlistchildcount bestentry bestentry setfilesize bestentry getfilesize setfilename bestentry getfilename setfiletype bestentry getfiletype cleartags copytags bestentry gettags setinttagvalue ft_sources uallchildssourcecount setinttagvalue ft_complete_sources uallchildscompletesourcecount m_mobilmulesearch updatesources bfound setlistparent addtail tempvalue m_foundfilescount getsearchid tempvalue m_foundfilescount setat getsearchid tempvalue uavail bclientresponse getinttagvalue ft_sources uavail uavail uavail addsources uavail uavail getinttagvalue ft_sources addresultcount getsearchid getfilehash uavail theprefs getdebugsearchresultdetaillevel setlistexpanded m_mobilmulesearch addresult c search file c search list get search file by hash const uchar hash const for position pos list get head position pos 0 c search file sf list get next pos if md4cmp hash sf get file hash return sf return null csearchfile csearchlist getsearchfilebyhash getheadposition csearchfile getnext getfilehash lpctstr name uint64 size lpctstr type uint num properties va list args va start args num properties e utf8 str e str encode utf8str raw c safe mem file temp new c safe mem file 250 uchar fileid 16 fileid to byte array fileid temp write hash16 fileid temp writeu int32 0 client ip temp writeu int16 0 client port write tag list uint u file pos tag count uint temp get position uint32 tagcount 0 temp writeu int32 tagcount dummy tag count will be filled later standard tags c tag tag name ft filename name tag name write tag to file temp e str encode tagcount c tag tag size ft filesize size true tag size write tag to file temp e str encode tagcount if type null type 0 t 0 c tag tag type ft filetype type tag type write tag to file temp e str encode tagcount additional tags while num properties 0 uint u prop type va arg args uint lpcstr psz prop name va arg args lpcstr lpvoid pv prop value va arg args lpvoid if u prop type 2 tagtype string if lpctstr pv prop value null lpctstr pv prop value 0 t 0 if strlen psz prop name 1 c tag tag prop uint8 psz prop name lpctstr pv prop value tag prop write tag to file temp e str encode else c tag tag prop psz prop name lpctstr pv prop value tag prop write tag to file temp e str encode tagcount else if u prop type 3 tagtype uint32 if uint32 pv prop value 0 c tag tag prop psz prop name uint32 pv prop value tag prop write tag to file temp e str encode tagcount else assert 0 va end args temp seek u file pos tag count seek set temp writeu int32 tagcount temp seek to begin c search file temp file new c search file temp e str encode utf8str raw searchid 0 0 0 true add to list temp file delete temp numproperties va_list va_start numproperties eutf8str estrencode utf8strraw csafememfile csafememfile tobytearray writehash16 writeuint32 writeuint16 ufilepostagcount getposition writeuint32 ctag tagname ft_filename tagname writetagtofile estrencode ctag tagsize ft_filesize tagsize writetagtofile estrencode _t ctag tagtype ft_filetype tagtype writetagtofile estrencode numproperties uproptype va_arg pszpropname va_arg pvpropvalue va_arg uproptype tagtype_string pvpropvalue pvpropvalue _t pszpropname ctag tagprop pszpropname pvpropvalue tagprop writetagtofile estrencode ctag tagprop pszpropname pvpropvalue tagprop writetagtofile estrencode uproptype tagtype_uint32 pvpropvalue ctag tagprop pszpropname pvpropvalue tagprop writetagtofile estrencode va_end ufilepostagcount seek_set writeuint32 seektobegin csearchfile tempfile csearchfile estrencode utf8strraw addtolist tempfile bool c search list add notes kademlia c entry entry const uchar hash bool flag false for position pos list get head position pos 0 c search file sf list get next pos if md4cmp hash sf get file hash kademlia c entry entry clone entry copy if sf add note entry clone flag true else delete entry clone return flag csearchlist addnotes centry getheadposition csearchfile getnext getfilehash centry entryclone addnote entryclone entryclone c search file c search list detach next file uint32 n searchid the files are not deleted make sure you do this if you call this function find removes and returns the searchresult with most sources uint32 n high source 0 position resultpos 0 for position pos list get head position pos null position cur pos pos c search file cur file list get next pos if cur file get searchid n searchid if cur file get int tag value ft sources n high source n high source cur file get int tag value ft sources resultpos cur pos if resultpos 0 assert false return null c search file result list get at resultpos list remove at resultpos return result csearchfile csearchlist detachnextfile nsearchid nhighsource getheadposition cur_pos csearchfile cur_file getnext cur_file getsearchid nsearchid cur_file getinttagvalue ft_sources nhighsource nhighsource cur_file getinttagvalue ft_sources cur_pos csearchfile getat removeat uint get found files uint32 searchid const uint return val 0 verify m foundfilescount lookup searchid return val return return val getfoundfiles returnval m_foundfilescount returnval returnval cip filter cip filter m plasthit null m bmodified false load from default file false cipfilter cipfilter m_plasthit m_bmodified loadfromdefaultfile cip filter cip filter if m bmodified try save to default file catch c string remove allip filters cipfilter cipfilter m_bmodified savetodefaultfile cstring removeallipfilters c string cip filter get default file path const return the prefs get config dir dflt ipfilter filename cstring cipfilter getdefaultfilepath theprefs getconfigdir dflt_ipfilter_filename void cip filter remove allip filters for int i 0 i m iplist get count i delete m iplist i m iplist remove all m plasthit null cipfilter removeallipfilters m_iplist getcount m_iplist m_iplist removeall m_plasthit bool cip filter removeip filter const sip filter p filter for int i 0 i m iplist get count i if m iplist i p filter delete m iplist i m iplist remove at i return true return false cipfilter removeipfilter sipfilter pfilter m_iplist getcount m_iplist pfilter m_iplist m_iplist removeat int cip filter add from file lpctstr psz file path bool b show response dword dw start get tick count file read file tfsopen psz file path t r sh denywr if read file null enum eip filter file type unknown 0 filter dat 1 ipfilter dat ip prefix format peer guardian 2 peer guardian text format peer guardian2 3 peer guardian binary format e file type unknown setvbuf read file null iofbf 32768 tchar sz nam max fname tchar sz ext max ext tsplitpath psz file path null null sz nam sz ext if tcsicmp sz ext t p2p 0 tcsicmp sz nam t guarding p2p 0 tcsicmp sz ext t txt 0 e file type peer guardian else if tcsicmp sz ext t prefix 0 e file type filter dat else setmode fileno read file o binary static const byte aucp2bheader xff xff xff xffp2b byte auc header sizeof aucp2bheader 1 if fread auc header sizeof auc header 1 read file 1 if memcmp auc header aucp2bheader sizeof aucp2bheader 1 0 e file type peer guardian2 else fseek read file 0 seek set setmode fileno read file o text ugly int i found ranges 0 int i line 0 if e file type peer guardian2 version 1 strings are iso 8859 1 encoded version 2 strings are utf 8 encoded uint8 n version if fread n version sizeof n version 1 read file 1 n version 1 n version 2 while feof read file char sz name 256 int i len 0 for read until nul or eof int i char getc read file if i char eof break if i len sizeof sz name 1 sz name i len char i char if i char 0 break sz name i len 0 uint32 u start if fread u start sizeof u start 1 read file 1 break u start ntohl u start uint32 u end if fread u end sizeof u end 1 read file 1 break u end ntohl u end i line n version 2 opt utf8 to str sz name i len addip range u start u end dflt filter level c stringa sz name i len i found ranges else c stringa sbuffer char sz buffer 1024 while fgets sz buffer countof sz buffer read file null i line sbuffer sz buffer ignore comments too short lines if sbuffer get at 0 sbuffer get at 0 sbuffer get length 5 sbuffer trim t r n debug only sbuffer is empty trace ip filter ignored line u n i line 0 continue if e file type unknown looks like html if sbuffer find 1 sbuffer find 1 sbuffer delete 0 sbuffer reverse find 1 check for ip ip at start of line uint u1 u2 u3 u4 u5 u6 u7 u8 if sscanf sbuffer u u u u u u u u u1 u2 u3 u4 u5 u6 u7 u8 8 e file type filter dat else check for description ip ip int i colon sbuffer find if i colon 1 c stringa strip range sbuffer mid i colon 1 uint u1 u2 u3 u4 u5 u6 u7 u8 if sscanf strip range u u u u u u u u u1 u2 u3 u4 u5 u6 u7 u8 8 e file type peer guardian bool b valid false uint32 start 0 uint32 end 0 uint level 0 c stringa desc if e file type filter dat b valid parse filter line1 sbuffer start end level desc else if e file type peer guardian b valid parse filter line2 sbuffer start end level desc add a filter if b valid addip range start end level desc i found ranges else sbuffer trim t r n debug only sbuffer is empty trace ip filter ignored line u n i line 0 fclose read file sort the ip filter list by ip range start addresses qsort m iplist get data m iplist get count sizeof m iplist 0 cmpsip filter by start addr merge overlapping and adjacent filter ranges int i duplicate 0 int i merged 0 if m iplist get count 2 on large ip filter lists there is a noticeable performance problem when merging the list the cip filter array remove at call is way too expensive to get called during the merging thus we use temporary helper arrays to copy only the entries into the final list which are not get deleted reserve a byte array its used as a boolean array actually as large as the current ip filter list so we can set a to delete flag for each entry in the current ip filter list char pc to delete new char m iplist get count memset pc to delete 0 m iplist get count int i num to delete 0 sip filter p prv m iplist 0 int i 1 while i m iplist get count sip filter p cur m iplist i if p cur start p prv start p cur start p prv end overlapping p cur start p prv end 1 p cur level p prv level adjacent if p cur start p prv start p cur end p prv end don t merge identical entries todo not yet handled overlapping entries with different level if p cur end p prv end p prv end p cur end p prv desc t p cur desc this may create a very very long description string i merged else if we have identical entries use the lowest level if p cur level p prv level p prv level p cur level i duplicate delete p cur m iplist remove at i way too expensive read above pc to delete i 1 mark this entry as to delete i num to delete i continue p prv p cur i create new ip filter list which contains only the entries from the original ip filter list which are not to be deleted if i num to delete 0 cip filter array new list new list set size m iplist get count i num to delete int i new list index 0 for int i 0 i m iplist get count i if pc to delete i new list i new list index m iplist i assert i new list index new list get size replace current list with new list dump but still fast enough only 1 memcpy m iplist remove all m iplist append new list new list remove all m bmodified true delete pc to delete if the prefs get verbose dword dw end get tick count add debug log line false t loaded ip filters from s psz file path add debug log line false t parsed lines entries u found ip ranges u duplicate u merged u time s i line i found ranges i duplicate i merged cast seconds tohm dw end dw start 500 1000 add log line b show response get res string ids ipfilterloaded m iplist get count return m iplist get count cipfilter addfromfile pszfilepath bshowresponse dwstart gettickcount readfile _tfsopen pszfilepath _t _sh_denywr readfile eipfilterfiletype filterdat peerguardian peerguardian peerguardian2 peerguardian efiletype readfile _iofbf sznam _max_fname szext _max_ext _tsplitpath pszfilepath sznam szext _tcsicmp szext _t _tcsicmp sznam _t _tcsicmp szext _t efiletype peerguardian _tcsicmp szext _t efiletype filterdat _setmode readfile _o_binary _aucp2bheader aucheader _aucp2bheader aucheader aucheader readfile aucheader _aucp2bheader _aucp2bheader efiletype peerguardian2 readfile seek_set _setmode readfile _o_text ifoundranges iline efiletype peerguardian2 nversion nversion nversion readfile nversion nversion readfile szname ilen ichar readfile ichar ilen szname szname ilen ichar ichar szname ilen ustart ustart ustart readfile ustart ustart uend uend uend readfile uend uend iline nversion optutf8tostr szname ilen addiprange ustart uend dflt_filter_level cstringa szname ilen ifoundranges cstringa szbuffer szbuffer _countof szbuffer readfile iline szbuffer getat getat getlength debug_only isempty iline efiletype reversefind efiletype filterdat icolon icolon cstringa striprange icolon striprange efiletype peerguardian bvalid cstringa efiletype filterdat bvalid parsefilterline1 efiletype peerguardian bvalid parsefilterline2 bvalid addiprange ifoundranges debug_only isempty iline readfile m_iplist getdata m_iplist getcount m_iplist cmpsipfilterbystartaddr iduplicate imerged m_iplist getcount cipfilterarray removeat pctodelete m_iplist getcount pctodelete m_iplist getcount inumtodelete sipfilter pprv m_iplist m_iplist getcount sipfilter pcur m_iplist pcur pprv pcur pprv pcur pprv pcur pprv pcur pprv pcur pprv pcur pprv pprv pcur pprv _t pcur imerged pcur pprv pprv pcur iduplicate pcur m_iplist removeat pctodelete inumtodelete pprv pcur inumtodelete cipfilterarray newlist newlist setsize m_iplist getcount inumtodelete inewlistindex m_iplist getcount pctodelete newlist inewlistindex m_iplist inewlistindex newlist getsize m_iplist removeall m_iplist newlist newlist removeall m_bmodified pctodelete theprefs getverbose dwend gettickcount adddebuglogline _t pszfilepath adddebuglogline _t iline ifoundranges iduplicate imerged castsecondstohm dwend dwstart addlogline bshowresponse getresstring ids_ipfilterloaded m_iplist getcount m_iplist getcount int cip filter load from default file bool b show response remove allip filters return add from file get default file path b show response cipfilter loadfromdefaultfile bshowresponse removeallipfilters addfromfile getdefaultfilepath bshowresponse void cip filter save to default file c string str file path the prefs get config dir dflt ipfilter filename file fp tfsopen str file path t wt sh denywr if fp null for int i 0 i m iplist get count i const sip filter flt m iplist i char sz start 16 ipstra sz start countof sz start htonl flt start char sz end 16 ipstra sz end countof sz end htonl flt end if fprintf fp 15s 15s 3u s n sz start sz end flt level flt desc 0 ferror fp c string str error str error format t failed to save ip filter to file s hs str file path strerror errno throw str error fclose fp m bmodified false else c string str error str error format t failed to save ip filter to file s hs str file path strerror errno throw str error cipfilter savetodefaultfile cstring strfilepath theprefs getconfigdir dflt_ipfilter_filename _tfsopen strfilepath _t _sh_denywr m_iplist getcount sipfilter m_iplist szstart szstart _countof szstart szend szend _countof szend szstart szend cstring strerror strerror _t strfilepath strerror m_bmodified cstring strerror strerror _t strfilepath strerror bool cip filter is filtered uint32 ip const return is filtered ip the prefs getip filter level cipfilter isfiltered isfiltered theprefs getipfilterlevel bool cip filter is filtered uint32 ip uint level const if m iplist get count 0 ip 0 return false ip htonl ip to speed things up we use a binary search the ip filter list must be sorted by ip range start addresses the ip filter list is not allowed to contain overlapping ip ranges see also the ip range merging code when loading the list the filter level is ignored during the binary search and is evaluated only for the found element todo this can still be improved even more use a pre assembled list of ip ranges which contains only the ip ranges for the currently used filter level use a dumb plain array for storing the ip range structures this will give more cach hits when processing the list but this would require to also use a dumb sip filter structure don t use data items with ctors otherwise the creation of the array would be rather slow sip filter pp found sip filter bsearch ip m iplist get data m iplist get count sizeof m iplist 0 cmpsip filter by addr if pp found pp found level level pp found hits m plasthit pp found return true return false cipfilter isfiltered m_iplist getcount sipfilter sipfilter ppfound sipfilter m_iplist getdata m_iplist getcount m_iplist cmpsipfilterbyaddr ppfound ppfound ppfound m_plasthit ppfound c string cip filter get last hit const return m plasthit c string m plasthit desc t not available cstring cipfilter getlasthit m_plasthit cstring m_plasthit _t const cip filter array cip filter getip filter const return m iplist cipfilterarray cipfilter getipfilter m_iplist cudp socket cudp socket m hwndresolvemessage null m sendbuffer null m cur server null m dnstaskhandle null m bwouldblock false cudpsocket cudpsocket m_hwndresolvemessage m_sendbuffer m_cur_server m_dnstaskhandle m_bwouldblock cudp socket cudp socket the app upload bandwidth throttler remove from all queues this zz upload band with throttler udp delete m cur server delete m sendbuffer position pos controlpacket queue get head position while pos s serverudp packet p controlpacket queue get next pos delete p packet delete p m udpwnd destroy window cudpsocket cudpsocket theapp uploadbandwidththrottler removefromallqueues uploadbandwiththrottler m_cur_server m_sendbuffer controlpacket_queue getheadposition sserverudppacket controlpacket_queue getnext m_udpwnd destroywindow bool cudp socket create if the prefs get serverudp port verify m udpwnd create ex 0 afx register wnd class 0 t e mule async dns resolve socket wnd 1 ws overlapped 0 0 0 0 null null m hwndresolvemessage m udpwnd m hwnd m udpwnd m powner this if c async socket create the prefs get serverudp port 0xffff 0 the prefs get serverudp port sock dgram fd read fd write the prefs get bind addrw log error log statusbar t error server udp socket failed to create server udp socket s get error message get last error return false return true return false cudpsocket theprefs getserverudpport m_udpwnd createex afxregisterwndclass _t emule ws_overlapped m_hwndresolvemessage m_udpwnd m_hwnd m_udpwnd m_powner casyncsocket theprefs getserverudpport theprefs getserverudpport sock_dgram fd_read fd_write theprefs getbindaddrw logerror log_statusbar _t geterrormessage getlasterror socket sent bytes cudp socket send control data uint32 max number of bytes to send uint32 min frag size zz upload band with throttler udp zz upload band with throttler udp note this function is invoked from a different thread send locker lock uint32 sent bytes 0 zz upload band with throttler udp while controlpacket queue get head position 0 is busy sent bytes max number of bytes to send zz upload band with throttler udp s serverudp packet packet controlpacket queue get head int send success send to packet packet packet size packet dwip packet n port if send success 0 if send success 0 sent bytes packet size zz upload band with throttler udp controlpacket queue remove head delete packet packet delete packet zz upload band with throttler udp if is busy controlpacket queue is empty the app upload bandwidth throttler queue for sending control packet this send locker unlock socket sent bytes return val true 0 sent bytes return return val zz upload band with throttler udp socketsentbytes cudpsocket sendcontroldata maxnumberofbytestosend minfragsize uploadbandwiththrottler uploadbandwiththrottler sendlocker sentbytes uploadbandwiththrottler controlpacket_queue getheadposition isbusy sentbytes maxnumberofbytestosend uploadbandwiththrottler sserverudppacket controlpacket_queue gethead sendsuccess sendto nport sendsuccess sendsuccess sentbytes uploadbandwiththrottler controlpacket_queue removehead uploadbandwiththrottler isbusy controlpacket_queue isempty theapp uploadbandwidththrottler queueforsendingcontrolpacket sendlocker socketsentbytes returnval sentbytes returnval uploadbandwiththrottler void cudp socket send packet packet packet c server host uses conversion if the last dns query did not yet return we may still have a packet queued delete it if the prefs get verbose m cur server debug log warning t warning server udp socket timeout occured when trying to resolve address for server s s m cur server get list name m cur server get address delete m cur server m cur server null delete m sendbuffer m sendbuffer null m sendblen 0 m cur server new c server host m sendbuffer new uint8 packet size 2 memcpy m sendbuffer packet getudp header 2 memcpy m sendbuffer 2 packet p buffer packet size m sendblen packet size 2 async resolvedns t2ca m cur server get address m cur server get port 4 cudpsocket sendpacket cserver uses_conversion theprefs getverbose m_cur_server debuglogwarning _t m_cur_server getlistname m_cur_server getaddress m_cur_server m_cur_server m_sendbuffer m_sendbuffer m_sendblen m_cur_server cserver m_sendbuffer m_sendbuffer getudpheader m_sendbuffer pbuffer m_sendblen asyncresolvedns m_cur_server getaddress m_cur_server getport void cudp socket dns lookup done wparam wp lparam lp m dnstaskhandle null an asynchronous database routine completed if wsagetasyncerror lp 0 if the prefs get verbose debug log warning t error server udp socket failed to resolve address for server s s s m cur server m cur server get list name t m cur server m cur server get address t get error message wsagetasyncerror lp 1 delete m sendbuffer m sendbuffer null delete m cur server m cur server null return if m saveaddr sin addr s addr inaddr none get the structure length int i buf len wsagetasyncbuflen lp if i buf len sizeof hostent lphostent p host lphostent m dnshostbuffer if p host h length 4 p host h addr list p host h addr list 0 m saveaddr sin addr s addr lpin addr p host h addr list 0 s addr also reset the receive buffer memset m dnshostbuffer 0 sizeof m dnshostbuffer if m cur server if m saveaddr sin addr s addr inaddr none bool b remove server false if is goodip m saveaddr sin addr s addr if the prefs get log filteredi ps add debug log line false t resolved ip for server s is s invalid ip or lan address server deleted m cur server get list name ipstr m saveaddr sin addr s addr b remove server true if b remove server the app ipfilter is filtered m saveaddr sin addr s addr if the prefs get log filteredi ps add debug log line false t resolved ip for server s is s found in ip filter server deleted m cur server get list name ipstr m saveaddr sin addr s addr b remove server true if b remove server c server update the app serverlist get server by address m cur server get address m cur server get port if update update setip m saveaddr sin addr s un s addr send buffer else c server todel the app serverlist get server by address m cur server get address m cur server get port if todel the app emuledlg serverwnd serverlistctrl remove server todel delete m cur server m cur server null delete m sendbuffer m sendbuffer null m sendblen 0 else still no valid ip for this server delete packet if the prefs get verbose debug log warning t error server udp socket failed to resolve address for server s s m cur server get list name m cur server get address delete m cur server m cur server null delete m sendbuffer m sendbuffer null m sendblen 0 cudpsocket dnslookupdone m_dnstaskhandle theprefs getverbose debuglogwarning _t m_cur_server m_cur_server getlistname _t m_cur_server m_cur_server getaddress _t geterrormessage m_sendbuffer m_sendbuffer m_cur_server m_cur_server m_saveaddr sin_addr s_addr inaddr_none ibuflen ibuflen phost m_dnshostbuffer phost h_length phost h_addr_list phost h_addr_list m_saveaddr sin_addr s_addr lpin_addr phost h_addr_list s_addr m_dnshostbuffer m_dnshostbuffer m_cur_server m_saveaddr sin_addr s_addr inaddr_none bremoveserver isgoodip m_saveaddr sin_addr s_addr theprefs getlogfilteredips adddebuglogline _t m_cur_server getlistname m_saveaddr sin_addr s_addr bremoveserver bremoveserver theapp isfiltered m_saveaddr sin_addr s_addr theprefs getlogfilteredips adddebuglogline _t m_cur_server getlistname m_saveaddr sin_addr s_addr bremoveserver bremoveserver cserver theapp getserverbyaddress m_cur_server getaddress m_cur_server getport m_saveaddr sin_addr s_un s_addr sendbuffer cserver theapp getserverbyaddress m_cur_server getaddress m_cur_server getport theapp removeserver m_cur_server m_cur_server m_sendbuffer m_sendbuffer m_sendblen theprefs getverbose debuglogwarning _t m_cur_server getlistname m_cur_server getaddress m_cur_server m_cur_server m_sendbuffer m_sendbuffer m_sendblen void cudp socket async resolvedns lpcstr lpsz host addressa uint n host port if m dnstaskhandle wsa cancel async request m dnstaskhandle m dnstaskhandle null see if we have a ip already sockaddr in sock addr 0 sock addr sin family af inet sock addr sin addr s addr inet addr lpsz host addressa sock addr sin port htons u short n host port backup for send socket m saveaddr sock addr if sock addr sin addr s addr inaddr none resolve hostname hostname asynchronously memset m dnshostbuffer 0 sizeof m dnshostbuffer m dnstaskhandle wsa async get host by name m hwndresolvemessage wm dnslookupdone lpsz host addressa m dnshostbuffer maxgethoststruct if m dnstaskhandle null if the prefs get verbose debug log warning t error server udp socket failed to resolve address for hs s lpsz host addressa get error message get last error 1 delete m sendbuffer m sendbuffer null delete m cur server m cur server null else send buffer cudpsocket asyncresolvedns lpszhostaddressa nhostport m_dnstaskhandle wsacancelasyncrequest m_dnstaskhandle m_dnstaskhandle sockaddr_in sockaddr sockaddr sin_family af_inet sockaddr sin_addr s_addr inet_addr lpszhostaddressa sockaddr sin_port u_short nhostport m_saveaddr sockaddr sockaddr sin_addr s_addr inaddr_none m_dnshostbuffer m_dnshostbuffer m_dnstaskhandle wsaasyncgethostbyname m_hwndresolvemessage wm_dnslookupdone lpszhostaddressa m_dnshostbuffer m_dnstaskhandle theprefs getverbose debuglogwarning _t lpszhostaddressa geterrormessage getlasterror m_sendbuffer m_sendbuffer m_cur_server m_cur_server sendbuffer void cudp socket on send int n error code if n error code if the prefs get verbose debug log error t error server udp socket failed to send packet s get error message n error code 1 return m bwouldblock false zz upload band with throttler udp send locker lock if controlpacket queue is empty the app upload bandwidth throttler queue for sending control packet this send locker unlock zz upload band with throttler udp cudpsocket onsend nerrorcode nerrorcode theprefs getverbose debuglogerror _t geterrormessage nerrorcode m_bwouldblock uploadbandwiththrottler sendlocker controlpacket_queue isempty theapp uploadbandwidththrottler queueforsendingcontrolpacket sendlocker uploadbandwiththrottler void cudp socket on receive int n error code if n error code if the prefs get debug serverudp level 0 debug t error server udp socket receive failed s n get error message n error code 1 if the prefs get verbose debug log error t error server udp socket receive failed s get error message n error code 1 uint8 buffer 5000 sockaddr in sock addr 0 int i sock addr len sizeof sock addr int length receive from buffer sizeof buffer sockaddr sock addr i sock addr len if length socket error if buffer 0 op edonkeyprot process packet buffer 2 length 2 buffer 1 sock addr sin addr s un s addr ntohs sock addr sin port else if the prefs get debug serverudp level 0 debug t note serverudp message from s u unknown protocol 0x 02x n ipstr sock addr sin addr ntohs sock addr sin port 4 buffer 0 else dword dw error wsa get last error if the prefs get debug serverudp level 0 c string str server info if i sock addr len 0 sock addr sin addr s un s addr 0 sock addr sin addr s un s addr inaddr none str server info format t from s u ipstr sock addr sin addr ntohs sock addr sin port 4 debug t error server udp socket failed to receive data s s n str server info get error message dw error 1 if dw error wsaeconnreset depending on local and remote os and depending on used local remote router we may receive wsaeconnreset errors according some kb articels this is a special way of winsock to report that a sent udp packet was not received by the remote host because it was not listening on the specified port no server running there if we are not currently pinging this server increase the failure counter c server p server the app serverlist get server by address ipstr sock addr sin addr ntohs sock addr sin port 4 if p server get tick count p server get last pinged sec2ms 30 p server add failed count the app emuledlg serverwnd serverlistctrl refresh server p server else if the prefs get verbose c string str server info if i sock addr len 0 sock addr sin addr s un s addr 0 sock addr sin addr s un s addr inaddr none str server info format t from s u ipstr sock addr sin addr ntohs sock addr sin port 4 debug log error t error server udp socket failed to receive data s s str server info get error message dw error 1 cudpsocket onreceive nerrorcode nerrorcode theprefs getdebugserverudplevel _t geterrormessage nerrorcode theprefs getverbose debuglogerror _t geterrormessage nerrorcode sockaddr_in sockaddr isockaddrlen sockaddr receivefrom sockaddr isockaddrlen socket_error op_edonkeyprot processpacket sockaddr sin_addr s_un s_addr sockaddr sin_port theprefs getdebugserverudplevel _t serverudpmessage sockaddr sin_addr sockaddr sin_port dwerror wsagetlasterror theprefs getdebugserverudplevel cstring strserverinfo isockaddrlen sockaddr sin_addr s_un s_addr sockaddr sin_addr s_un s_addr inaddr_none strserverinfo _t sockaddr sin_addr sockaddr sin_port _t strserverinfo geterrormessage dwerror dwerror cserver pserver theapp getserverbyaddress sockaddr sin_addr sockaddr sin_port pserver gettickcount pserver getlastpinged pserver addfailedcount theapp refreshserver pserver theprefs getverbose cstring strserverinfo isockaddrlen sockaddr sin_addr s_un s_addr sockaddr sin_addr s_un s_addr inaddr_none strserverinfo _t sockaddr sin_addr sockaddr sin_port debuglogerror _t strserverinfo geterrormessage dwerror void cudp socket send buffer if m cur server m sendbuffer u short n port ntohs m saveaddr sin port zz upload band with throttler udp s serverudp packet newpending new s serverudp packet newpending dwip m saveaddr sin addr s addr newpending n port n port newpending packet m sendbuffer newpending size m sendblen send locker lock controlpacket queue add tail newpending send locker unlock the app upload bandwidth throttler queue for sending control packet this zz upload band with throttler udp m sendbuffer null m sendblen 0 delete m cur server m cur server null cudpsocket sendbuffer m_cur_server m_sendbuffer u_short nport m_saveaddr sin_port uploadbandwiththrottler sserverudppacket sserverudppacket m_saveaddr sin_addr s_addr nport nport m_sendbuffer m_sendblen sendlocker controlpacket_queue addtail sendlocker theapp uploadbandwidththrottler queueforsendingcontrolpacket uploadbandwiththrottler m_sendbuffer m_sendblen m_cur_server m_cur_server bool cudp socket process packet const byte packet uint size uint opcode uint32 nip uint16 nudp port try the stats add down data overhead server size c server update the app serverlist get server by address ipstr nip nudp port 4 if update update reset failed count the app emuledlg serverwnd serverlistctrl refresh server update switch opcode case op globsearchres c safe mem file data packet size process all search result packets int i left int i dbg packet 1 do if the prefs get debug serverudp level 0 if data get length data get position 16 4 2 const byte p dbg packet data get buffer data get position debug t serverudp message from 21s op globsearchresult u s n ipstr nip nudp port 4 i dbg packet dbg get file info p dbg packet dbg get clientid peeku int32 p dbg packet 16 peeku int16 p dbg packet 20 uint u result count the app searchlist processudp search answer data true update get unicode support nip nudp port 4 the app emuledlg searchwnd add global ed2k search results u result count check if there is another source packet i left int data get length data get position if i left 2 uint8 protocol data readu int8 i left if protocol op edonkeyprot data seek 1 seek cur i left 1 break uint8 opcode data readu int8 i left if opcode op globsearchres data seek 2 seek cur i left 2 break while i left 0 if i left 0 the prefs get debug serverudp level 0 debug t note op globsearchresult contains d additional bytes n i left if the prefs get debug serverudp level 1 debug hex dump data break case op globfoundsources c safe mem file data packet size process all source packets int i left int i dbg packet 1 do uchar fileid 16 data read hash16 fileid if the prefs get debug serverudp level 0 debug t serverudp message from 21s op globfoundsources u s n ipstr nip nudp port 4 i dbg packet dbg get file info fileid if c part file file the app downloadqueue get file byid fileid file add sources data nip nudp port 4 else skip sources for that file uint count data readu int8 data seek count 4 2 seek cur check if there is another source packet i left int data get length data get position if i left 2 uint8 protocol data readu int8 i left if protocol op edonkeyprot data seek 1 seek cur i left 1 break uint8 opcode data readu int8 i left if opcode op globfoundsources data seek 2 seek cur i left 2 break while i left 0 if i left 0 the prefs get debug serverudp level 0 debug t note op globfoundsources contains d additional bytes n i left if the prefs get debug serverudp level 1 debug hex dump data break case op globservstatres if the prefs get debug serverudp level 0 debug t serverudp message from 21s op globservstatres n ipstr nip nudp port 4 if size 12 update null return true uint32 challenge peeku int32 packet if challenge update get challenge if the prefs get debug serverudp level 0 debug t note received unexpected challenge 08x waiting on packet with challenge 08x n challenge update get challenge return true update set challenge 0 uint32 cur user peeku int32 packet 4 uint32 cur files peeku int32 packet 8 uint32 cur maxusers 0 uint32 cur softfiles 0 uint32 cur hardfiles 0 uint32 uudp flags 0 uint32 u lowid users 0 if size 16 cur maxusers peeku int32 packet 12 if size 24 cur softfiles peeku int32 packet 16 cur hardfiles peeku int32 packet 20 if size 28 uudp flags peeku int32 packet 24 if the prefs get debug serverudp level 0 c string str info const dword dw known bits srv udpflg ext getsources srv udpflg ext getfiles srv udpflg newtags srv udpflg unicode srv udpflg ext getsources2 srv udpflg largefiles if uudp flags dw known bits str info append format t unkudp flags 0x 08x uudp flags dw known bits if uudp flags srv udpflg ext getsources str info append format t ext get sources 1 if uudp flags srv udpflg ext getsources2 str info append format t ext get sources2 1 if uudp flags srv udpflg ext getfiles str info append format t ext get files 1 if uudp flags srv udpflg newtags str info append format t new tags 1 if uudp flags srv udpflg unicode str info append format t unicode 1 if uudp flags srv udpflg largefiles str info append format t large files 1 debug t s n str info if size 32 u lowid users peeku int32 packet 28 if the prefs get debug serverudp level 0 if size 32 debug t note op globservstatres contains d additional bytes n size 32 if the prefs get debug serverudp level 1 dbg get hex dump packet 32 size 32 if update update set ping get tick count update get last pinged update set user count cur user update set file count cur files update set max users cur maxusers update set soft files cur softfiles update set hard files cur hardfiles if the received udp flags do not match any already stored udp flags reset the server version string because the version which was determined by last connecting to that server is most likely not accurat any longer this may also give false results because we don t know the udp flags when connecting to a server with tcp if update getudp flags uudp flags update set version t update setudp flags uudp flags update set lowid users u lowid users the app emuledlg serverwnd serverlistctrl refresh server update break case op server desc res if the prefs get debug serverudp level 0 debug t serverudp message from 21s op serverdescres n ipstr nip nudp port 4 if update return true old packet name len 2 name name len desc len 2 desc en new packet challenge 4 taglist note to properly distinguish between the two packets which are both useing the same opcode the first two bytes of challenge in network byte order have to be an invalid name len at least c safe mem file srvinfo packet size if size 8 peeku int16 packet inv serv desc len if update get desc req challenge 0 peeku int32 packet update get desc req challenge update set desc req challenge 0 void srvinfo readu int32 skip challenge uint u tags srvinfo readu int32 for uint i 0 i u tags i c tag tag srvinfo true update get unicode support if tag get nameid st servername tag is str update set list name tag get str else if tag get nameid st description tag is str update set description tag get str else if tag get nameid st dynip tag is str update set dynip tag get str else if tag get nameid st version tag is str update set version tag get str else if tag get nameid st version tag is int c string str version str version format t u u tag get int 16 tag get int 0xffff update set version str version else if tag get nameid st auxportslist tag is str currently not implemented string port port else if the prefs get debug serverudp level 0 debug t note unknown tag in op serverdescres s n tag get full info else a server sent us a new server description packet including a challenge although we did not ask for it this may happen if there are multiple servers running on the same machine with multiple i ps if such a server is asked for a description the server will answer 2 times but with the same ip if the prefs get debug serverudp level 0 debug t note received unexpected new format op serverdescres from s with challenge 08x waiting on packet with challenge 08x n ipstr nip nudp port 4 peeku int32 packet update get desc req challenge ignore this packet else c string str name srvinfo read string true update get unicode support c string str desc srvinfo read string true update get unicode support update set description str desc update set list name str name if the prefs get debug serverudp level 0 int i add data int srvinfo get length srvinfo get position if i add data 0 debug t note op serverdescres contains d additional bytes n i add data if the prefs get debug serverudp level 1 debug hex dump srvinfo the app emuledlg serverwnd serverlistctrl refresh server update break default if the prefs get debug serverudp level 0 debug t note serverudp message from s unknown packet cudpsocket processpacket nudpport thestats adddowndataoverheadserver cserver theapp getserverbyaddress nudpport resetfailedcount theapp refreshserver op_globsearchres csafememfile ileft idbgpacket theprefs getdebugserverudplevel getlength getposition pdbgpacket getbuffer getposition _t serverudpmessage op_globsearchresult nudpport idbgpacket dbggetfileinfo pdbgpacket dbggetclientid peekuint32 pdbgpacket peekuint16 pdbgpacket uresultcount theapp processudpsearchanswer getunicodesupport nudpport theapp addglobaled2ksearchresults uresultcount ileft getlength getposition ileft readuint8 ileft op_edonkeyprot seek_cur ileft readuint8 ileft op_globsearchres seek_cur ileft ileft ileft theprefs getdebugserverudplevel _t op_globsearchresult ileft theprefs getdebugserverudplevel debughexdump op_globfoundsources csafememfile ileft idbgpacket readhash16 theprefs getdebugserverudplevel _t serverudpmessage op_globfoundsources nudpport idbgpacket dbggetfileinfo cpartfile theapp getfilebyid addsources nudpport readuint8 seek_cur ileft getlength getposition ileft readuint8 ileft op_edonkeyprot seek_cur ileft readuint8 ileft op_globfoundsources seek_cur ileft ileft ileft theprefs getdebugserverudplevel _t op_globfoundsources ileft theprefs getdebugserverudplevel debughexdump op_globservstatres theprefs getdebugserverudplevel _t serverudpmessage op_globservstatres nudpport peekuint32 getchallenge theprefs getdebugserverudplevel _t getchallenge setchallenge cur_user peekuint32 cur_files peekuint32 cur_maxusers cur_softfiles cur_hardfiles uudpflags ulowidusers cur_maxusers peekuint32 cur_softfiles peekuint32 cur_hardfiles peekuint32 uudpflags peekuint32 theprefs getdebugserverudplevel cstring strinfo dwknownbits srv_udpflg_ext_getsources srv_udpflg_ext_getfiles srv_udpflg_newtags srv_udpflg_unicode srv_udpflg_ext_getsources2 srv_udpflg_largefiles uudpflags dwknownbits strinfo appendformat _t unkudpflags uudpflags dwknownbits uudpflags srv_udpflg_ext_getsources strinfo appendformat _t extgetsources uudpflags srv_udpflg_ext_getsources2 strinfo appendformat _t extgetsources2 uudpflags srv_udpflg_ext_getfiles strinfo appendformat _t extgetfiles uudpflags srv_udpflg_newtags strinfo appendformat _t newtags uudpflags srv_udpflg_unicode strinfo appendformat _t uudpflags srv_udpflg_largefiles strinfo appendformat _t largefiles _t strinfo ulowidusers peekuint32 theprefs getdebugserverudplevel _t op_globservstatres theprefs getdebugserverudplevel dbggethexdump setping gettickcount getlastpinged setusercount cur_user setfilecount cur_files setmaxusers cur_maxusers setsoftfiles cur_softfiles sethardfiles cur_hardfiles getudpflags uudpflags setversion _t setudpflags uudpflags setlowidusers ulowidusers theapp refreshserver op_server_desc_res theprefs getdebugserverudplevel _t serverudpmessage op_serverdescres nudpport name_len name_len desc_len desc_en name_len csafememfile peekuint16 inv_serv_desc_len getdescreqchallenge peekuint32 getdescreqchallenge setdescreqchallenge readuint32 utags readuint32 utags ctag getunicodesupport getnameid st_servername isstr setlistname getstr getnameid st_description isstr setdescription getstr getnameid st_dynip isstr setdynip getstr getnameid st_version isstr setversion getstr getnameid st_version isint cstring strversion strversion _t getint getint setversion strversion getnameid st_auxportslist isstr theprefs getdebugserverudplevel _t op_serverdescres getfullinfo ips theprefs getdebugserverudplevel _t op_serverdescres nudpport peekuint32 getdescreqchallenge cstring strname readstring getunicodesupport cstring strdesc readstring getunicodesupport setdescription strdesc setlistname strname theprefs getdebugserverudplevel iadddata getlength getposition iadddata _t op_serverdescres iadddata theprefs getdebugserverudplevel debughexdump theapp refreshserver theprefs getdebugserverudplevel _t serverudpmessage void cudp socket process packet error uint size uint opcode uint32 nip uint16 ntcp port lpctstr psz error if the prefs get verbose c string str name c server p server the app serverlist get server by address ipstr nip ntcp port if p server str name t p server get list name t debug log warning false t error failed to process server udp packet from s u s opcode 0x 02x size u s ipstr nip ntcp port str name opcode size psz error cudpsocket processpacketerror ntcpport pszerror theprefs getverbose cstring strname cserver pserver theapp getserverbyaddress ntcpport pserver strname _t pserver getlistname _t debuglogwarning _t ntcpport strname pszerror int cudp socket send to uint8 lp buf int n buf len uint32 dwip uint16 n port note this function is invoked from a different thread int i result c async socket send to lp buf n buf len n port ipstr dwip if i result socket error dword dw error get last error if dw error wsaewouldblock m bwouldblock true return 1 blocked else if the prefs get verbose the app queue debug log line false t error server udp socket failed to send packet to s u s ipstr dwip n port get error message dw error 1 return 0 error return 1 success cudpsocket sendto lpbuf nbuflen nport iresult casyncsocket sendto lpbuf nbuflen nport iresult socket_error dwerror getlasterror dwerror m_bwouldblock theprefs getverbose theapp queuedebuglogline _t nport geterrormessage dwerror define wm dnslookupdone wm user 0x101 does not need to be placed in user msgs h cudp socket wnd cudp socket wnd wm_dnslookupdone wm_user usermsgs cudpsocketwnd cudpsocketwnd lresult cudp socket wnd ondns lookup done wparam w param lparam l param m powner dns lookup done w param l param return true cudpsocketwnd ondnslookupdone wparam lparam m_powner dnslookupdone wparam lparam uint32 n searchid uint32 n serverip uint16 n server port lpctstr psz directory bool b kademlia m bkademlia b kademlia m nsearchid n searchid in data read hash16 m abyfilehash m nclientid in data readu int32 m nclientport in data readu int16 if m nclientid m nclientport is valid search result clientip port m nclientid m nclientport if the prefs get debug server searches level 1 debug t filtered source from search result s u n dbg get clientid m nclientid m nclientport m nclientid 0 m nclientport 0 uint tagcount in data readu int32 nserver2 exe lugdunum v16 38 patched for win32 returns the clientip port of the client which offered that file even if that client has not filled the according fields in the op offerfiles packet with its ip port 16 38 p73 lugdunum propenprinz does not return clientip port if the op offerfiles packet does not also contain it if the op offerfiles packet does contain our highid and port the server returns that data at least when returning search results via tcp if the prefs get debug server searches level 1 debug t search result s client u u u u u tags u n md4str m abyfilehash uint8 m nclientid uint8 m nclientid 8 uint8 m nclientid 16 uint8 m nclientid 24 m nclientport tagcount copy convert ed2k server tags to local tags for uint i 0 i tagcount i c tag tag new c tag in data b optutf8 if the prefs get debug server searches level 1 debug t s n tag get full info dbg get file meta tag name converted2k tag tag if tag convert ed2k server file rating tag note feel free to do more with the received numbers here but please do not add that particular received tag to the local tag list with the received tag format packed rating either create a local tag with an e mule known rating value and drop the percentage which is currently done or add a second tag which holds the percentage in addition to the e mule known rating value be aware that adding that tag in packed rating format will create troubles in other code parts if tag get nameid ft filerating tag is int uint16 n packed rating uint16 tag get int percent of clients related to availability which rated on that file uint u percent client ratings hibyte n packed rating void u percent client ratings average rating used by clients uint u avg rating lobyte n packed rating m uuserrating u avg rating 255 5 rating excellent tag set int m uuserrating taglist add tag here we have two choices if the server client sent us a filetype we could use it though it could be wrong we always trust our filetype list and determine the filetype by the extension of the file if we received a filetype from server we use it if we did not receive a filetype we determine it by examining the file s extension but in no case we will use the receive file type when adding this search result to the download queue to avoid that we are using wrong file types in part files this has to be handled when creating the part files const c string rstr file type get str tag value ft filetype set file name get str tag value ft filename false rstr file type is empty uint64 ui64 file size get int64 tag value ft filesize uint64 ufilesize hi get int tag value ft filesize hi if ufilesize hi 0 if ui64 file size old max emule file size ui64 file size ufilesize hi 32 set int64 tag value ft filesize ui64 file size else assert false set int tag value ft filesize hi 0 set file size ui64 file size if rstr file type is empty if tcscmp rstr file type t ed2kftstr program 0 c string str detail file type get file type by name get file name if str detail file type is empty set file type str detail file type else set file type rstr file type else set file type rstr file type m nclientserverip n serverip m nclientserverport n server port if m nclientserverip m nclientserverport s server server m nclientserverip m nclientserverport server m uavail get int tag value ft sources add server server m pszdirectory psz directory tcsdup psz directory null m list bexpanded false m list parent null m list childcount 0 m bpreviewpossible false m eknown not determined nsearchid nserverip nserverport pszdirectory bkademlia m_bkademlia bkademlia m_nsearchid nsearchid in_data readhash16 m_abyfilehash m_nclientid in_data readuint32 m_nclientport in_data readuint16 m_nclientid m_nclientport isvalidsearchresultclientipport m_nclientid m_nclientport theprefs getdebugserversearcheslevel _t dbggetclientid m_nclientid m_nclientport m_nclientid m_nclientport in_data readuint32 op_offerfiles op_offerfiles op_offerfiles theprefs getdebugserversearcheslevel _t m_abyfilehash m_nclientid m_nclientid m_nclientid m_nclientid m_nclientport ctag ctag in_data boptutf8 theprefs getdebugserversearcheslevel _t getfullinfo dbggetfilemetatagname converted2ktag emule emule getnameid ft_filerating isint npackedrating getint upercentclientratings npackedrating upercentclientratings uavgrating npackedrating m_uuserrating uavgrating ratingexcellent setint m_uuserrating cstring rstrfiletype getstrtagvalue ft_filetype setfilename getstrtagvalue ft_filename rstrfiletype isempty ui64filesize getint64tagvalue ft_filesize ufilesize_hi getinttagvalue ft_filesize_hi ufilesize_hi ui64filesize old_max_emule_file_size ui64filesize ufilesize_hi setint64tagvalue ft_filesize ui64filesize setinttagvalue ft_filesize_hi setfilesize ui64filesize rstrfiletype isempty _tcscmp rstrfiletype _t ed2kftstr_program cstring strdetailfiletype getfiletypebyname getfilename strdetailfiletype isempty setfiletype strdetailfiletype setfiletype rstrfiletype setfiletype rstrfiletype m_nclientserverip nserverip m_nclientserverport nserverport m_nclientserverip m_nclientserverport sserver m_nclientserverip m_nclientserverport m_uavail getinttagvalue ft_sources addserver m_pszdirectory pszdirectory _tcsdup pszdirectory m_list_bexpanded m_list_parent m_list_childcount m_bpreviewpossible m_eknown notdetermined c abstract file copyfrom update file rating comment avail m nclientserverip copyfrom get client serverip m nclientserverport copyfrom get client server port m nclientid copyfrom get clientid m nclientport copyfrom get client port m pszdirectory copyfrom get directory tcsdup copyfrom get directory null m nsearchid copyfrom get searchid m bkademlia copyfrom is kademlia const c simple array s client clients copyfrom get clients for int i 0 i clients get size i add client clients i const c simple array s server servers copyfrom get servers for int i 0 i servers get size i add server servers i m list bexpanded false m list parent const cast c search file copyfrom m list childcount 0 m bpreviewpossible false m eknown copyfrom m eknown cabstractfile updatefileratingcommentavail m_nclientserverip getclientserverip m_nclientserverport getclientserverport m_nclientid getclientid m_nclientport getclientport m_pszdirectory getdirectory _tcsdup getdirectory m_nsearchid getsearchid m_bkademlia iskademlia csimplearray sclient getclients getsize addclient csimplearray sserver getservers getsize addserver m_list_bexpanded m_list_parent const_cast csearchfile m_list_childcount m_bpreviewpossible m_eknown m_eknown c search file c search file free m pszdirectory for int i 0 i m listimages get size i delete m listimages i csearchfile csearchfile m_pszdirectory m_listimages getsize m_listimages uint32 c search file add sources uint32 count for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid ft sources if m bkademlia if count p tag get int p tag set int count else p tag set int p tag get int count return p tag get int ft sources is not yet supported by clients we may have to create such a tag c tag p tag new c tag ft sources count taglist add p tag return count csearchfile addsources getsize ctag ptag ptag getnameid ft_sources m_bkademlia ptag getint ptag setint ptag setint ptag getint ptag getint ft_sources ctag ptag ctag ft_sources ptag uint32 c search file get source count const return get int tag value ft sources csearchfile getsourcecount getinttagvalue ft_sources uint32 c search file add complete sources uint32 count for int i 0 i taglist get size i c tag p tag taglist i if p tag get nameid ft complete sources if m bkademlia if count p tag get int p tag set int count else p tag set int p tag get int count return p tag get int ft complete sources is not yet supported by all servers we may have to create such a tag c tag p tag new c tag ft complete sources count taglist add p tag return count csearchfile addcompletesources getsize ctag ptag ptag getnameid ft_complete_sources m_bkademlia ptag getint ptag setint ptag setint ptag getint ptag getint ft_complete_sources ctag ptag ctag ft_complete_sources ptag uint32 c search file get complete source count const return get int tag value ft complete sources csearchfile getcompletesourcecount getinttagvalue ft_complete_sources int c search file is complete const return is complete get source count get int tag value ft complete sources csearchfile iscomplete iscomplete getsourcecount getinttagvalue ft_complete_sources int c search file is complete uint u sources uint u complete sources const if is kademlia return 1 unknown else if get directory null u sources 1 u complete sources 0 if this search result is from a remote client view shared files answer we don t yet have any complete information could though be implemented some day don t show the file as incomplete though treat it as unknown return 1 unknown else if u sources 0 u complete sources 0 return 1 complete else return 0 not complete csearchfile iscomplete usources ucompletesources iskademlia getdirectory usources ucompletesources usources ucompletesources time t c search file get last seen complete const return get int tag value ft lastseencomplete time_t csearchfile getlastseencomplete getinttagvalue ft_lastseencomplete void c search file update file rating comment avail bool b old has comment m bhascomment uint u old user ratings m uuserrating m bhascomment false uint u ratings 0 uint u user ratings 0 for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos if m bhascomment entry get str tag value tag description is empty m bhascomment true uint rating uint entry get int tag value tag filerating if rating 0 u ratings u user ratings rating if u ratings m uuserrating u user ratings u ratings else m uuserrating 0 if b old has comment m bhascomment u old user ratings m uuserrating the app emuledlg searchwnd update search this csearchfile updatefileratingcommentavail boldhascomment m_bhascomment uolduserratings m_uuserrating m_bhascomment uratings uuserratings m_kadnotes getheadposition centry m_kadnotes getnext m_bhascomment getstrtagvalue tag_description isempty m_bhascomment getinttagvalue tag_filerating uratings uuserratings uratings m_uuserrating uuserratings uratings m_uuserrating boldhascomment m_bhascomment uolduserratings m_uuserrating theapp updatesearch c prop page frame default c prop page frame default cproppageframedefault cproppageframedefault c prop page frame default c prop page frame default if m images get safe handle m images delete image list cproppageframedefault cproppageframedefault m_images getsafehandle m_images deleteimagelist bool c prop page frame default create dword dw window style const rect rect c wnd pwnd parent uint nid return c wnd create afx register wnd class cs hredraw cs vredraw afx get app load standard cursor idc arrow get sys color brush color 3dface t page frame dw window style rect pwnd parent nid cproppageframedefault dwwindowstyle cwnd pwndparent cwnd afxregisterwndclass cs_hredraw cs_vredraw afxgetapp loadstandardcursor idc_arrow getsyscolorbrush color_3dface _t dwwindowstyle pwndparent c wnd c prop page frame default get wnd return static cast c wnd this cwnd cproppageframedefault getwnd static_cast cwnd void c prop page frame default set caption lpctstr lpsz caption hicon h icon null c prop page frame set caption lpsz caption h icon build image list if m images get safe handle m images delete image list if h icon iconinfo ii if get icon info h icon ii return c bitmap bm mask bm mask attach ii hbm mask if ii hbm color delete object ii hbm color bitmap bm bm mask get bitmap bm if m images create bm bm width bm bm height the app m idfltimagelistcolorflags ilc mask 0 1 return if m images add h icon 1 m images delete image list cproppageframedefault setcaption lpszcaption hicon cproppageframe setcaption lpszcaption hicon m_images getsafehandle m_images deleteimagelist hicon geticoninfo hicon cbitmap bmmask bmmask hbmmask hbmcolor deleteobject hbmcolor bmmask getbitmap m_images bmwidth bmheight theapp m_idfltimagelistcolorflags ilc_mask m_images hicon m_images deleteimagelist c rect c prop page frame default calc msg area c rect rect get client rect rect if g xpstyle is theme active g xpstyle is app themed htheme h theme g xpstyle open theme data m hwnd l tab if h theme c rect rect content cdc p dc getdc g xpstyle get theme background content rect h theme p dc m hdc tabp pane 0 rect rect content releasedc p dc g xpstyle close theme data h theme if get show caption rect content top rect top get caption height 1 rect rect content else if get show caption rect top get caption height 1 return rect crect cproppageframedefault calcmsgarea crect getclientrect g_xpstyle isthemeactive g_xpstyle isappthemed htheme g_xpstyle openthemedata m_hwnd htheme crect rectcontent pdc g_xpstyle getthemebackgroundcontentrect htheme pdc m_hdc tabp_pane rectcontent pdc g_xpstyle closethemedata htheme getshowcaption rectcontent getcaptionheight rectcontent getshowcaption getcaptionheight c rect c prop page frame default calc caption area c rect rect get client rect rect if g xpstyle is theme active g xpstyle is app themed htheme h theme g xpstyle open theme data m hwnd l tab if h theme c rect rect content cdc p dc getdc g xpstyle get theme background content rect h theme p dc m hdc tabp pane 0 rect rect content releasedc p dc g xpstyle close theme data h theme if get show caption rect content bottom rect top get caption height else rect content bottom rect content top rect rect content else if get show caption rect bottom rect top get caption height else rect bottom rect top return rect crect cproppageframedefault calccaptionarea crect getclientrect g_xpstyle isthemeactive g_xpstyle isappthemed htheme g_xpstyle openthemedata m_hwnd htheme crect rectcontent pdc g_xpstyle getthemebackgroundcontentrect htheme pdc m_hdc tabp_pane rectcontent pdc g_xpstyle closethemedata htheme getshowcaption rectcontent getcaptionheight rectcontent rectcontent rectcontent getshowcaption getcaptionheight void c prop page frame default draw caption cdc p dc c rect rect lpctstr lpsz caption hicon h icon colorref clr left get sys color color activecaption colorref clr right if g blowcolordesktop if g xpstyle is theme active g xpstyle is app themed clr right p dc get pixel rect right 1 rect top not very smart but for xp styles we need the real background color else clr right get sys color color 3dface else clr right clr left fill gradient recth p dc rect clr left clr right draw icon if h icon m images get safe handle m images get image count 1 imageinfo ii m images get image info 0 ii c point pt 3 rect center point y ii rc image bottom ii rc image top 2 m images draw p dc 0 pt ild transparent rect left ii rc image right ii rc image left 3 draw text rect left 2 colorref clr prev p dc set text color get sys color color captiontext int n bk style p dc set bk mode transparent c font p font c font p dc select object the app m fontdefaultbold p dc draw text lpsz caption rect dt left dt vcenter dt singleline dt end ellipsis p dc set text color clr prev p dc set bk mode n bk style p dc select object p font cproppageframedefault drawcaption pdc crect lpszcaption hicon clrleft getsyscolor color_activecaption clrright g_blowcolordesktop g_xpstyle isthemeactive g_xpstyle isappthemed clrright pdc getpixel clrright getsyscolor color_3dface clrright clrleft fillgradientrecth pdc clrleft clrright hicon m_images getsafehandle m_images getimagecount m_images getimageinfo cpoint centerpoint rcimage rcimage m_images pdc ild_transparent rcimage rcimage clrprev pdc settextcolor getsyscolor color_captiontext nbkstyle pdc setbkmode cfont pfont cfont pdc selectobject theapp m_fontdefaultbold pdc drawtext lpszcaption dt_left dt_vcenter dt_singleline dt_end_ellipsis pdc settextcolor clrprev pdc setbkmode nbkstyle pdc selectobject pfont void c prop page frame default fill gradient recth cdc p dc const rect rect colorref clr left colorref clr right pre calculation int n steps rect right rect left int nr range getr value clr right getr value clr left int ng range getg value clr right getg value clr left int nb range getb value clr right getb value clr left double dr step double nr range double n steps double dg step double ng range double n steps double db step double nb range double n steps double dr double getr value clr left double dg double getg value clr left double db double getb value clr left c pen p prev pen null for int x rect left x rect right x c pen pen ps solid 1 rgb byte dr byte dg byte db p prev pen p dc select object pen p dc move to x rect top p dc line to x rect bottom p dc select object p prev pen dr dr step dg dg step db db step cproppageframedefault fillgradientrecth pdc clrleft clrright nsteps nrrange getrvalue clrright getrvalue clrleft ngrange getgvalue clrright getgvalue clrleft nbrange getbvalue clrright getbvalue clrleft drstep nrrange nsteps dgstep ngrange nsteps dbstep nbrange nsteps getrvalue clrleft getgvalue clrleft getbvalue clrleft cpen pprevpen cpen ps_solid pprevpen pdc selectobject pdc moveto pdc lineto pdc selectobject pprevpen drstep dgstep dbstep void c prop page frame default on paint c paintdc dc this draw dc cproppageframedefault onpaint cpaintdc bool c prop page frame default on erase bkgnd cdc pdc if g xpstyle is theme active g xpstyle is app themed htheme h theme g xpstyle open theme data m hwnd l tab if h theme c rect rect get client rect rect g xpstyle draw theme background h theme pdc m hdc tabp pane 0 rect null g xpstyle close theme data h theme return true else return c wnd on erase bkgnd pdc cproppageframedefault onerasebkgnd g_xpstyle isthemeactive g_xpstyle isappthemed htheme g_xpstyle openthemedata m_hwnd htheme crect getclientrect g_xpstyle drawthemebackground htheme m_hdc tabp_pane g_xpstyle closethemedata htheme cwnd onerasebkgnd c tray menu btn c tray menu btn m bbold false m bmouseover false m bnohover false m buseicon false m bparentcapture false m hicon null m nbtnid rand m sicon cx 0 m sicon cy 0 m strtext ctraymenubtn ctraymenubtn m_bbold m_bmouseover m_bnohover m_buseicon m_bparentcapture m_hicon m_nbtnid m_sicon m_sicon m_strtext c tray menu btn c tray menu btn if m hicon destroy icon m hicon ctraymenubtn ctraymenubtn m_hicon destroyicon m_hicon void c tray menu btn on mouse move uint n flags c point point c rect r client get client rect r client if point x r client left point x r client right point y r client top point y r client bottom set capture if m bnohover m bmouseover true invalidate else if m bparentcapture c wnd p parent get parent if p parent p parent set capture else release capture else release capture m bmouseover false invalidate c wnd on mouse move n flags point ctraymenubtn onmousemove nflags cpoint crect rclient getclientrect rclient rclient rclient rclient rclient setcapture m_bnohover m_bmouseover m_bparentcapture cwnd pparent getparent pparent pparent setcapture releasecapture releasecapture m_bmouseover cwnd onmousemove nflags void c tray menu btn onl button up uint n flags c point point c rect r client get client rect r client if point x r client left point x r client right point y r client top point y r client bottom c wnd p parent get parent if p parent p parent post message wm command makewparam m nbtnid bn clicked long m hwnd else release capture m bmouseover false invalidate c wnd onl button up n flags point ctraymenubtn onlbuttonup nflags cpoint crect rclient getclientrect rclient rclient rclient rclient rclient cwnd pparent getparent pparent pparent postmessage wm_command m_nbtnid bn_clicked m_hwnd releasecapture m_bmouseover cwnd onlbuttonup nflags void c tray menu btn on paint c paintdc dc this device context for painting c rect r client get client rect r client cdc memdc memdc create compatibledc dc c bitmap membmp p oldbmp membmp create compatible bitmap dc r client width r client height p oldbmp memdc select object membmp c font p oldfont null if m cffont get safe handle p oldfont memdc select object m cffont bool b enabled is window enabled if m bmouseover b enabled fill rect memdc m hdc r client get sys color brush color highlight memdc set text color get sys color color highlighttext else fill rect memdc m hdc r client get sys color brush color btnface memdc set text color get sys color color btntext int i left offset 0 if m buseicon memdc draw state c point 2 r client height 2 m sicon cy 2 c size 16 16 m hicon dst icon dss normal c brush null i left offset m sicon cx 4 memdc set bk mode transparent c rect r text 0 0 0 0 memdc draw text m strtext r text dt calcrect dt singleline dt left c point pt r client width 1 r text width 1 r client height 1 r text height 1 c point pt r client left 2 i left offset r client height 2 r text height 2 c point sz r text width r text height memdc draw state pt sz m strtext dst text b enabled dss normal dss disabled false m strtext get length c brush null dc bit blt 0 0 r client width r client height memdc 0 0 srccopy memdc select object p oldbmp if p oldfont memdc select object p oldfont ctraymenubtn onpaint cpaintdc crect rclient getclientrect rclient createcompatibledc cbitmap poldbmp createcompatiblebitmap rclient rclient poldbmp selectobject cfont poldfont m_cffont getsafehandle poldfont selectobject m_cffont benabled iswindowenabled m_bmouseover benabled fillrect m_hdc rclient getsyscolorbrush color_highlight settextcolor getsyscolor color_highlighttext fillrect m_hdc rclient getsyscolorbrush color_btnface settextcolor getsyscolor color_btntext ileftoffset m_buseicon drawstate cpoint rclient m_sicon csize m_hicon dst_icon dss_normal cbrush ileftoffset m_sicon setbkmode crect rtext drawtext m_strtext rtext dt_calcrect dt_singleline dt_left cpoint rclient rtext rclient rtext cpoint rclient ileftoffset rclient rtext cpoint rtext rtext drawstate m_strtext dst_text benabled dss_normal dss_disabled m_strtext getlength cbrush bitblt rclient rclient selectobject poldbmp poldfont selectobject poldfont c drop down button c drop down button m bsingledropdownbtn true cdropdownbutton cdropdownbutton m_bsingledropdownbtn c drop down button c drop down button cdropdownbutton cdropdownbutton bool c drop down button create dword dw style const rect rect c wnd p parent wnd uint nid bool b single drop down btn m bsingledropdownbtn b single drop down btn dw style ccs nomovey ccs noparentalign ccs noresize prevent adjusting of specified width height by create func ccs nodivider tbstyle list tbstyle flat tbstyle transparent 0 if c tool bar ctrlx create dw style rect p parent wnd nid return false return init b single drop down btn cdropdownbutton dwstyle cwnd pparentwnd bsingledropdownbtn m_bsingledropdownbtn bsingledropdownbtn dwstyle ccs_nomovey ccs_noparentalign ccs_noresize ccs_nodivider tbstyle_list tbstyle_flat tbstyle_transparent ctoolbarctrlx dwstyle pparentwnd bsingledropdownbtn bool c drop down button init bool b single drop down btn delete all buttons m bsingledropdownbtn b single drop down btn if a toolbar control was created indirectly via a dialog resource one can not add any buttons without setting an image list before so for this to work we have to attach an image list to the toolbar control the image list can be empty and it does not need to be used at all but it has to be attached c image list piml get image list if piml null piml m himagelist null c image list iml iml create 16 16 ilc color 0 0 set image list iml iml detach if m bsingledropdownbtn tbbutton atb 1 0 atb 0 i bitmap 1 atb 0 id command get window long m hwnd gwl id atb 0 fs state tbstate enabled atb 0 fs style m bsingledropdownbtn btns dropdown btns button atb 0 i string 1 verify add buttons 1 atb resize to max width set extended style tbstyle ex drawddarrows return true cdropdownbutton bsingledropdownbtn deleteallbuttons m_bsingledropdownbtn bsingledropdownbtn cimagelist getimagelist m_himagelist cimagelist ilc_color setimagelist m_bsingledropdownbtn ibitmap idcommand getwindowlong m_hwnd gwl_id fsstate tbstate_enabled fsstyle m_bsingledropdownbtn btns_dropdown btns_button istring addbuttons resizetomaxwidth setextendedstyle tbstyle_ex_drawddarrows void c drop down button set window text lpctstr psz string int cx 0 if m bsingledropdownbtn cx get btn width get window long m hwnd gwl id tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif text tbbi psz text const cast lptstr psz string set button info get window long m hwnd gwl id tbbi if cx set btn width get window long m hwnd gwl id cx cdropdownbutton setwindowtext pszstring m_bsingledropdownbtn getbtnwidth getwindowlong m_hwnd gwl_id cbsize dwmask tbif_text psztext const_cast pszstring setbuttoninfo getwindowlong m_hwnd gwl_id setbtnwidth getwindowlong m_hwnd gwl_id void c drop down button set icon lpctstr psz resourceid if m bsingledropdownbtn return c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 1 1 iml add c temp icon loader psz resourceid c image list p iml old set image list iml iml detach if p iml old p iml old delete image list tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif image tbbi i image 0 set button info get window long m hwnd gwl id tbbi cdropdownbutton seticon pszresourceid m_bsingledropdownbtn cimagelist theapp m_idfltimagelistcolorflags ilc_mask ctempiconloader pszresourceid cimagelist pimlold setimagelist pimlold pimlold deleteimagelist cbsize dwmask tbif_image iimage setbuttoninfo getwindowlong m_hwnd gwl_id void c drop down button resize to max width if m bsingledropdownbtn return c rect rc wnd get window rect rc wnd if rc wnd width 0 tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif size tbbi cx word rc wnd width set button info get window long m hwnd gwl id tbbi cdropdownbutton resizetomaxwidth m_bsingledropdownbtn crect rcwnd getwindowrect rcwnd rcwnd cbsize dwmask tbif_size rcwnd setbuttoninfo getwindowlong m_hwnd gwl_id void c drop down button recalc layout bool b force if toolbar has at least one button with the button style btns dropdown the entire toolbar is resized with too large height so remove the btns dropdown button style s and force the toolbar to resize and apply them again todo should be moved to c tool bar ctrlx bool b drop down btn get btn style get window long m hwnd gwl id btns dropdown 0 if b drop down btn remove btn style get window long m hwnd gwl id btns dropdown if b drop down btn b force c tool bar ctrlx recalc layout add btn style get window long m hwnd gwl id btns dropdown cdropdownbutton recalclayout bforce btns_dropdown btns_dropdown ctoolbarctrlx bdropdownbtn getbtnstyle getwindowlong m_hwnd gwl_id btns_dropdown bdropdownbtn removebtnstyle getwindowlong m_hwnd gwl_id btns_dropdown bdropdownbtn bforce ctoolbarctrlx recalclayout addbtnstyle getwindowlong m_hwnd gwl_id btns_dropdown void c drop down button on size uint n type int cx int cy c tool bar ctrlx on size n type cx cy if cx 0 cy 0 resize to max width cdropdownbutton onsize ntype ctoolbarctrlx onsize ntype resizetomaxwidth void c drop down button on setting change uint u flags lpctstr lpsz section c tool bar ctrlx on setting change u flags lpsz section the toolbar resizes itself when the system fonts were changed especially when large small system fonts were selected need to recalc the layout because we have a fixed control size recalc layout cdropdownbutton onsettingchange uflags lpszsection ctoolbarctrlx onsettingchange uflags lpszsection recalclayout c resizable dialog c shared files wnd idd p parent icon files null cresizabledialog csharedfileswnd pparent icon_files c shared files wnd c shared files wnd if icon files verify destroy icon icon files csharedfileswnd csharedfileswnd icon_files destroyicon icon_files void c shared files wnd localize sharedfilesctrl localize m ctlshareddirtree localize sharedfilesctrl set directory filter null true get dlg item idc traffic text set window text get res string ids sf files get dlg item idc reloadsharedfiles set window text get res string ids sf reload m ctrlstatisticsfrm set window text get res string ids sf statistics get dlg item idc cursession lbl set window text get res string ids sf current get dlg item idc total lbl set window text get res string ids sf total get dlg item idc fstatic6 set window text get res string ids sf trans get dlg item idc fstatic5 set window text get res string ids sf accepted get dlg item idc fstatic4 set window text get res string ids sf requests t get dlg item idc fstatic9 set window text get res string ids sf trans get dlg item idc fstatic8 set window text get res string ids sf accepted get dlg item idc fstatic7 set window text get res string ids sf requests t csharedfileswnd m_ctlshareddirtree setdirectoryfilter getdlgitem idc_traffic_text setwindowtext getresstring ids_sf_files getdlgitem idc_reloadsharedfiles setwindowtext getresstring ids_sf_reload m_ctrlstatisticsfrm setwindowtext getresstring ids_sf_statistics getdlgitem idc_cursession_lbl setwindowtext getresstring ids_sf_current getdlgitem idc_total_lbl setwindowtext getresstring ids_sf_total getdlgitem idc_fstatic6 setwindowtext getresstring ids_sf_trans getdlgitem idc_fstatic5 setwindowtext getresstring ids_sf_accepted getdlgitem idc_fstatic4 setwindowtext getresstring ids_sf_requests _t getdlgitem idc_fstatic9 setwindowtext getresstring ids_sf_trans getdlgitem idc_fstatic8 setwindowtext getresstring ids_sf_accepted getdlgitem idc_fstatic7 setwindowtext getresstring ids_sf_requests _t void c shared files wnd show selected files summary const c known file p the file null int i files 0 uint64 u transferred 0 uint u requests 0 uint u accepted 0 uint64 u all time transferred 0 uint u all time requests 0 uint u all time accepted 0 position pos sharedfilesctrl get first selected item position while pos int i item sharedfilesctrl get next selected item pos const c known file p file c known file sharedfilesctrl get item data i item i files if i files 1 p the file p file u transferred p file statistic get transferred u requests p file statistic get requests u accepted p file statistic get accepts u all time transferred p file statistic get all time transferred u all time requests p file statistic get all time requests u all time accepted p file statistic get all time accepts if i files 0 pop bartrans set range32 0 int the app knownfiles transferred 1024 pop bartrans set pos int u transferred 1024 pop bartrans set show percent set dlg item text idc stransferred cast itox bytes u transferred false false pop bar set range32 0 the app knownfiles requested pop bar set pos u requests pop bar set show percent set dlg item int idc srequested u requests false pop baraccept set range32 0 the app knownfiles accepted pop baraccept set pos u accepted pop baraccept set show percent set dlg item int idc saccepted u accepted false set dlg item text idc stransferred2 cast itox bytes u all time transferred false false set dlg item int idc srequested2 u all time requests false set dlg item int idc saccepted2 u all time accepted false c string str get res string ids sf statistics if i files 1 p the file null str t make string escaped p the file get file name t m ctrlstatisticsfrm set window text str else pop bartrans set range32 0 100 pop bartrans set pos 0 pop bartrans set text format t set dlg item text idc stransferred t pop bar set range32 0 100 pop bar set pos 0 pop bar set text format t set dlg item text idc srequested t pop baraccept set range32 0 100 pop baraccept set pos 0 pop baraccept set text format t set dlg item text idc saccepted t set dlg item text idc stransferred2 t set dlg item text idc srequested2 t set dlg item text idc saccepted2 t m ctrlstatisticsfrm set window text get res string ids sf statistics csharedfileswnd showselectedfilessummary cknownfile pthefile ifiles utransferred urequests uaccepted ualltimetransferred ualltimerequests ualltimeaccepted getfirstselecteditemposition iitem getnextselecteditem cknownfile pfile cknownfile getitemdata iitem ifiles ifiles pthefile pfile utransferred pfile gettransferred urequests pfile getrequests uaccepted pfile getaccepts ualltimetransferred pfile getalltimetransferred ualltimerequests pfile getalltimerequests ualltimeaccepted pfile getalltimeaccepts ifiles pop_bartrans setrange32 theapp pop_bartrans setpos utransferred pop_bartrans setshowpercent setdlgitemtext idc_stransferred castitoxbytes utransferred pop_bar setrange32 theapp pop_bar setpos urequests pop_bar setshowpercent setdlgitemint idc_srequested urequests pop_baraccept setrange32 theapp pop_baraccept setpos uaccepted pop_baraccept setshowpercent setdlgitemint idc_saccepted uaccepted setdlgitemtext idc_stransferred2 castitoxbytes ualltimetransferred setdlgitemint idc_srequested2 ualltimerequests setdlgitemint idc_saccepted2 ualltimeaccepted cstring getresstring ids_sf_statistics ifiles pthefile _t makestringescaped pthefile getfilename _t m_ctrlstatisticsfrm setwindowtext pop_bartrans setrange32 pop_bartrans setpos pop_bartrans settextformat _t setdlgitemtext idc_stransferred _t pop_bar setrange32 pop_bar setpos pop_bar settextformat _t setdlgitemtext idc_srequested _t pop_baraccept setrange32 pop_baraccept setpos pop_baraccept settextformat _t setdlgitemtext idc_saccepted _t setdlgitemtext idc_stransferred2 _t setdlgitemtext idc_srequested2 _t setdlgitemtext idc_saccepted2 _t m_ctrlstatisticsfrm setwindowtext getresstring ids_sf_statistics void c shared files wnd reload sharedfilesctrl set directory filter null false m ctlshareddirtree reload sharedfilesctrl set directory filter m ctlshareddirtree get selected filter false the app sharedfiles reload show selected files summary csharedfileswnd setdirectoryfilter m_ctlshareddirtree setdirectoryfilter m_ctlshareddirtree getselectedfilter theapp showselectedfilessummary void c shared files wnd set all icons if icon files verify destroy icon icon files icon files the app load icon t shared files list 16 16 c static get dlg item idc files ico set icon icon files csharedfileswnd setallicons icon_files destroyicon icon_files icon_files theapp loadicon _t sharedfileslist cstatic getdlgitem idc_files_ico seticon icon_files void c shared files wnd do resize int delta c splitter control change width get dlg item idc shareddirstree delta c splitter control change pos get dlg item idc cursession lbl delta 0 c splitter control change pos get dlg item idc fstatic4 delta 0 c splitter control change pos get dlg item idc srequested delta 0 c splitter control change pos get dlg item idc fstatic5 delta 0 c splitter control change pos get dlg item idc saccepted delta 0 c splitter control change pos get dlg item idc fstatic6 delta 0 c splitter control change pos get dlg item idc stransferred delta 0 c splitter control change pos get dlg item idc statistics delta 0 c splitter control change pos get dlg item idc sflist delta 0 c splitter control change width get dlg item idc statistics delta c splitter control change width get dlg item idc sflist delta c splitter control change pos get dlg item idc popbar delta 0 c splitter control change pos get dlg item idc popbar2 delta 0 c splitter control change pos get dlg item idc popbar3 delta 0 c splitter control change width get dlg item idc popbar delta c splitter control change width get dlg item idc popbar2 delta c splitter control change width get dlg item idc popbar3 delta c rect rcw get window rect rcw screen to client rcw c rect rcspl get dlg item idc shareddirstree get client rect rcspl the prefs set splitterbar position shared rcspl right splitter margin remove anchor m wndsplitter add anchor m wndsplitter top left remove anchor idc sflist remove anchor idc statistics remove anchor idc cursession lbl remove anchor idc fstatic4 remove anchor idc srequested remove anchor idc popbar remove anchor idc fstatic5 remove anchor idc saccepted remove anchor idc popbar2 remove anchor idc fstatic6 remove anchor idc stransferred remove anchor idc popbar3 remove anchor idc shareddirstree add anchor idc sflist top left bottom right add anchor idc statistics bottom left bottom right add anchor idc cursession lbl bottom left add anchor idc fstatic4 bottom left add anchor idc srequested bottom left add anchor idc fstatic5 bottom left add anchor idc saccepted bottom left add anchor idc fstatic6 bottom left add anchor idc stransferred bottom left add anchor idc shareddirstree top left bottom left add anchor idc popbar bottom left bottom right add anchor idc popbar2 bottom left bottom right add anchor idc popbar3 bottom left bottom right m wndsplitter set range rcw left splitter range min rcw left splitter range max invalidate update window csharedfileswnd doresize csplittercontrol changewidth getdlgitem idc_shareddirstree csplittercontrol changepos getdlgitem idc_cursession_lbl csplittercontrol changepos getdlgitem idc_fstatic4 csplittercontrol changepos getdlgitem idc_srequested csplittercontrol changepos getdlgitem idc_fstatic5 csplittercontrol changepos getdlgitem idc_saccepted csplittercontrol changepos getdlgitem idc_fstatic6 csplittercontrol changepos getdlgitem idc_stransferred csplittercontrol changepos getdlgitem idc_statistics csplittercontrol changepos getdlgitem idc_sflist csplittercontrol changewidth getdlgitem idc_statistics csplittercontrol changewidth getdlgitem idc_sflist csplittercontrol changepos getdlgitem idc_popbar csplittercontrol changepos getdlgitem idc_popbar2 csplittercontrol changepos getdlgitem idc_popbar3 csplittercontrol changewidth getdlgitem idc_popbar csplittercontrol changewidth getdlgitem idc_popbar2 csplittercontrol changewidth getdlgitem idc_popbar3 crect getwindowrect screentoclient crect getdlgitem idc_shareddirstree getclientrect theprefs setsplitterbarpositionshared splitter_margin removeanchor m_wndsplitter addanchor m_wndsplitter top_left removeanchor idc_sflist removeanchor idc_statistics removeanchor idc_cursession_lbl removeanchor idc_fstatic4 removeanchor idc_srequested removeanchor idc_popbar removeanchor idc_fstatic5 removeanchor idc_saccepted removeanchor idc_popbar2 removeanchor idc_fstatic6 removeanchor idc_stransferred removeanchor idc_popbar3 removeanchor idc_shareddirstree addanchor idc_sflist top_left bottom_right addanchor idc_statistics bottom_left bottom_right addanchor idc_cursession_lbl bottom_left addanchor idc_fstatic4 bottom_left addanchor idc_srequested bottom_left addanchor idc_fstatic5 bottom_left addanchor idc_saccepted bottom_left addanchor idc_fstatic6 bottom_left addanchor idc_stransferred bottom_left addanchor idc_shareddirstree top_left bottom_left addanchor idc_popbar bottom_left bottom_right addanchor idc_popbar2 bottom_left bottom_right addanchor idc_popbar3 bottom_left bottom_right m_wndsplitter setrange splitter_range_min splitter_range_max updatewindow void c shared files wnd do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc sflist sharedfilesctrl ddx control pdx idc popbar pop bar ddx control pdx idc popbar2 pop baraccept ddx control pdx idc popbar3 pop bartrans ddx control pdx idc statistics m ctrlstatisticsfrm ddx control pdx idc shareddirstree m ctlshareddirtree csharedfileswnd dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_sflist ddx_control idc_popbar pop_bar ddx_control idc_popbar2 pop_baraccept ddx_control idc_popbar3 pop_bartrans ddx_control idc_statistics m_ctrlstatisticsfrm ddx_control idc_shareddirstree m_ctlshareddirtree bool c shared files wnd on init dialog c resizable dialog on init dialog init window styles this set all icons sharedfilesctrl init m ctlshareddirtree initalize sharedfilesctrl pop bar set gradient colors rgb 255 255 240 rgb 255 255 0 pop bar set text color rgb 20 70 255 pop baraccept set gradient colors rgb 255 255 240 rgb 255 255 0 pop baraccept set text color rgb 20 70 255 pop bartrans set gradient colors rgb 255 255 240 rgb 255 255 0 pop bartrans set text color rgb 20 70 255 logfont lf get font get log font lf lf lf weight fw bold bold create font indirect lf m ctrlstatisticsfrm set icon t stats detail m ctrlstatisticsfrm set font bold should run set icon first before setting bold font m ctrlstatisticsfrm set window text get res string ids sf statistics c rect rc get dlg item idc shareddirstree get window rect rc screen to client rc c rect rc spl get dlg item idc shareddirstree get window rect rc spl screen to client rc spl rc spl left rc spl right splitter margin rc spl right rc spl left splitter width m wndsplitter create ws child ws visible rc spl this idc splitter sharedfiles int pos stat vinit rc spl left int pos stat vnew rc left the prefs get splitterbar position shared 2 if the prefs get splitterbar position shared splitter range max pos stat vnew splitter range max else if the prefs get splitterbar position shared splitter range min pos stat vnew splitter range min rc spl left pos stat vnew rc spl right pos stat vnew splitter width m wndsplitter move window rc spl do resize pos stat vnew pos stat vinit localize get dlg item idc cursession lbl set font bold get dlg item idc total lbl set font bold add anchor idc files ico top left add anchor idc reloadsharedfiles top right add anchor idc total lbl bottom right add anchor idc srequested2 bottom right add anchor idc fstatic7 bottom right add anchor idc fstatic8 bottom right add anchor idc fstatic9 bottom right add anchor idc stransferred2 bottom right add anchor idc saccepted2 bottom right add anchor idc traffic text top left return true csharedfileswnd oninitdialog cresizabledialog oninitdialog initwindowstyles setallicons m_ctlshareddirtree pop_bar setgradientcolors pop_bar settextcolor pop_baraccept setgradientcolors pop_baraccept settextcolor pop_bartrans setgradientcolors pop_bartrans settextcolor getfont getlogfont lfweight fw_bold createfontindirect m_ctrlstatisticsfrm seticon _t statsdetail m_ctrlstatisticsfrm setfont seticon m_ctrlstatisticsfrm setwindowtext getresstring ids_sf_statistics crect getdlgitem idc_shareddirstree getwindowrect screentoclient crect rcspl getdlgitem idc_shareddirstree getwindowrect rcspl screentoclient rcspl rcspl rcspl splitter_margin rcspl rcspl splitter_width m_wndsplitter ws_child ws_visible rcspl idc_splitter_sharedfiles posstatvinit rcspl posstatvnew theprefs getsplitterbarpositionshared theprefs getsplitterbarpositionshared splitter_range_max posstatvnew splitter_range_max theprefs getsplitterbarpositionshared splitter_range_min posstatvnew splitter_range_min rcspl posstatvnew rcspl posstatvnew splitter_width m_wndsplitter movewindow rcspl doresize posstatvnew posstatvinit getdlgitem idc_cursession_lbl setfont getdlgitem idc_total_lbl setfont addanchor idc_files_ico top_left addanchor idc_reloadsharedfiles top_right addanchor idc_total_lbl bottom_right addanchor idc_srequested2 bottom_right addanchor idc_fstatic7 bottom_right addanchor idc_fstatic8 bottom_right addanchor idc_fstatic9 bottom_right addanchor idc_stransferred2 bottom_right addanchor idc_saccepted2 bottom_right addanchor idc_traffic_text top_left bool c shared files wnd pre translate message msg p msg if p msg message wm keydown don t handle ctrl tab in this window it will be handled by main window if p msg w param vk tab get async key state vk control 0 return false else if p msg message wm keyup if p msg hwnd get dlg item idc sflist m hwnd on lvn item activate sflist 0 0 else if p msg message wm mbuttonup point point get cursor pos point c point p point sharedfilesctrl screen to client p int it sharedfilesctrl hit test p if it 1 return false sharedfilesctrl set item state 1 0 lvis selected sharedfilesctrl set item state it lvis selected lvis focused lvis selected lvis focused sharedfilesctrl set selection mark it display selection mark correctly sharedfilesctrl show comments c known file sharedfilesctrl get item data it return true return c resizable dialog pre translate message p msg csharedfileswnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab getasynckeystate vk_control pmsg wm_keyup pmsg getdlgitem idc_sflist m_hwnd onlvnitemactivatesflist pmsg wm_mbuttonup getcursorpos cpoint screentoclient hittest setitemstate lvis_selected setitemstate lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark showcomments cknownfile getitemdata cresizabledialog pretranslatemessage pmsg lresult c shared files wnd def window proc uint message wparam w param lparam l param switch message case wm paint if m wndsplitter c rect rcw get window rect rcw screen to client rcw if rcw width 0 c rect rctree get dlg item idc shareddirstree get window rect rctree screen to client rctree c rect rc spl rc spl left rctree right splitter margin rc spl right rc spl left splitter width rc spl top rctree top rc spl bottom rctree bottom m wndsplitter move window rc spl true break case wm notify if w param idc splitter sharedfiles spc nmhdr p hdr spc nmhdr l param do resize p hdr delta break case wm windowposchanged c rect rcw get window rect rcw screen to client rcw if m wndsplitter rcw width 0 invalidate break case wm size if m wndsplitter c rect rc get window rect rc screen to client rc m wndsplitter set range rc left splitter range min rc left splitter range max break return c resizable dialog def window proc message w param l param csharedfileswnd defwindowproc wparam lparam wm_paint m_wndsplitter crect getwindowrect screentoclient crect getdlgitem idc_shareddirstree getwindowrect screentoclient crect rcspl rcspl splitter_margin rcspl rcspl splitter_width rcspl rcspl m_wndsplitter movewindow rcspl wm_notify wparam idc_splitter_sharedfiles spc_nmhdr phdr spc_nmhdr lparam doresize phdr wm_windowposchanged crect getwindowrect screentoclient m_wndsplitter wm_size m_wndsplitter crect getwindowrect screentoclient m_wndsplitter setrange splitter_range_min splitter_range_max cresizabledialog defwindowproc wparam lparam void c shared files wnd on bn clicked reloadsharedfiles c wait cursor cur wait reload csharedfileswnd onbnclickedreloadsharedfiles cwaitcursor curwait void c shared files wnd on lvn item activate sflist nmhdr pnmhdr lresult p result show selected files summary csharedfileswnd onlvnitemactivatesflist presult showselectedfilessummary void c shared files wnd onnm click sflist nmhdr pnmhdr lresult p result on lvn item activate sflist pnmhdr p result p result 0 csharedfileswnd onnmclicksflist presult onlvnitemactivatesflist presult presult void c shared files wnd on sys color change c resizable dialog on sys color change set all icons csharedfileswnd onsyscolorchange cresizabledialog onsyscolorchange setallicons void c shared files wnd on stn dblclick files ico the app emuledlg show preferences idd ppg directories csharedfileswnd onstndblclickfilesico theapp showpreferences idd_ppg_directories void c shared files wnd on tvn selchanged shareddirstree nmhdr pnmhdr lresult p result sharedfilesctrl set directory filter m ctlshareddirtree get selected filter m ctlshareddirtree is creating tree p result 0 csharedfileswnd ontvnselchangedshareddirstree presult setdirectoryfilter m_ctlshareddirtree getselectedfilter m_ctlshareddirtree iscreatingtree presult void c shared files wnd on size uint n type int cx int cy c resizable dialog on size n type cx cy csharedfileswnd onsize ntype cresizabledialog onsize ntype c dialog input box idd p parent m cancel true m bfilenamemode false m icmain null cdialog inputbox pparent m_cancel m_bfilenamemode m_icmain input box input box if m icmain verify destroy icon m icmain inputbox inputbox m_icmain destroyicon m_icmain void input box set labels c string title c string label c string default str m label label m title title m default default str inputbox setlabels cstring cstring cstring defaultstr m_label m_title m_default defaultstr void input box do data exchange c data exchange pdx c dialog do data exchange pdx inputbox dodataexchange cdataexchange cdialog dodataexchange bool input box on init dialog c dialog on init dialog init window styles this set icon m icmain the app load icon t rename false get dlg item idc iblabel set window text m label get dlg item idc text set window text m default set window text m title get dlg item idcancel set window text get res string ids cancel set dlg item text idc cleanfilename get res string ids cleanup get dlg item idc cleanfilename show window m bfilenamemode sw normal sw hide return true inputbox oninitdialog cdialog oninitdialog initwindowstyles seticon m_icmain theapp loadicon _t getdlgitem idc_iblabel setwindowtext m_label getdlgitem idc_text setwindowtext m_default setwindowtext m_title getdlgitem setwindowtext getresstring ids_cancel setdlgitemtext idc_cleanfilename getresstring ids_cleanup getdlgitem idc_cleanfilename showwindow m_bfilenamemode sw_normal sw_hide void input box onok m cancel false get dlg item text idc text m return m return trim c dialog onok inputbox m_cancel getdlgitemtext idc_text m_return m_return cdialog void input box on clean filename c string filename get dlg item idc text get window text filename get dlg item idc text set window text cleanup filename filename inputbox oncleanfilename cstring getdlgitem idc_text getwindowtext getdlgitem idc_text setwindowtext cleanupfilename c list ctrl item walk this memset sortstat 0 sizeof sortstat naich hashing 0 m pdirectoryfilter null set general purpose find true false clistctrlitemwalk naichhashing m_pdirectoryfilter setgeneralpurposefind c shared files ctrl c shared files ctrl csharedfilesctrl csharedfilesctrl void c shared files ctrl init set name t shared files ctrl c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 set image list il dummy image list lvsil small assert get style lvs shareimagelists 0 il dummy image list detach set extended style lvs ex fullrowselect modify style lvs singlesel 0 insert column 0 get res string ids dl filename lvcfmt left 250 0 insert column 1 get res string ids dl size lvcfmt left 100 1 insert column 2 get res string ids type lvcfmt left 50 2 insert column 3 get res string ids priority lvcfmt left 70 3 insert column 4 get res string ids fileid lvcfmt left 220 4 insert column 5 get res string ids sf requests lvcfmt left 100 5 insert column 6 get res string ids sf accepts lvcfmt left 100 6 insert column 7 get res string ids sf transferred lvcfmt left 120 7 insert column 8 get res string ids upstatus lvcfmt left 100 8 insert column 9 get res string ids folder lvcfmt left 200 9 insert column 10 get res string ids complsources lvcfmt left 100 10 insert column 11 get res string ids sharedtitle lvcfmt left 200 11 set all icons create menues load settings barry use preferred sort order from preferences set sort arrow sort items sort proc get sort item get sort ascending 0 20 csharedfilesctrl setname _t sharedfilesctrl cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask setimagelist ildummyimagelist lvsil_small getstyle lvs_shareimagelists ildummyimagelist setextendedstyle lvs_ex_fullrowselect modifystyle lvs_singlesel insertcolumn getresstring ids_dl_filename lvcfmt_left insertcolumn getresstring ids_dl_size lvcfmt_left insertcolumn getresstring ids_type lvcfmt_left insertcolumn getresstring ids_priority lvcfmt_left insertcolumn getresstring ids_fileid lvcfmt_left insertcolumn getresstring ids_sf_requests lvcfmt_left insertcolumn getresstring ids_sf_accepts lvcfmt_left insertcolumn getresstring ids_sf_transferred lvcfmt_left insertcolumn getresstring ids_upstatus lvcfmt_left insertcolumn getresstring ids_folder lvcfmt_left insertcolumn getresstring ids_complsources lvcfmt_left insertcolumn getresstring ids_sharedtitle lvcfmt_left setallicons createmenues loadsettings setsortarrow sortitems sortproc getsortitem getsortascending void c shared files ctrl create menues if m priomenu verify m priomenu destroy menu if m collectionsmenu verify m collectionsmenu destroy menu if m sharedfilesmenu verify m sharedfilesmenu destroy menu m priomenu create menu m priomenu append menu mf string mp prioverylow get res string ids prioverylow m priomenu append menu mf string mp priolow get res string ids priolow m priomenu append menu mf string mp prionormal get res string ids prionormal m priomenu append menu mf string mp priohigh get res string ids priohigh m priomenu append menu mf string mp prioveryhigh get res string ids priorelease m priomenu append menu mf string mp prioauto get res string ids prioauto uap m collectionsmenu create menu m collectionsmenu add menu title null true m collectionsmenu append menu mf string mp createcollection get res string ids createcollection t collection add m collectionsmenu append menu mf string mp modifycollection get res string ids modifycollection t collection edit m collectionsmenu append menu mf string mp viewcollection get res string ids viewcollection t collection view m collectionsmenu append menu mf string mp searchauthor get res string ids searchauthorcollection t collection search m sharedfilesmenu create popup menu m sharedfilesmenu add menu title get res string ids sharedfiles true m sharedfilesmenu append menu mf string mp open get res string ids openfile t openfile m sharedfilesmenu append menu mf string mp openfolder get res string ids openfolder t openfolder m sharedfilesmenu append menu mf string mp rename get res string ids rename t t filerename m sharedfilesmenu append menu mf string mp remove get res string ids delete t delete if the prefs is ext controls enabled m sharedfilesmenu append menu mf string irc setsendlink get res string ids irc addlinktoirc t ircclipboard m sharedfilesmenu append menu mf string mf separator m sharedfilesmenu append menu mf string mf popup uint ptr m priomenu m hmenu get res string ids priority t get res string ids pw con uplbl t t filepriority m sharedfilesmenu append menu mf string mf separator m sharedfilesmenu append menu mf string mf popup uint ptr m collectionsmenu m hmenu get res string ids meta collection t collection m sharedfilesmenu append menu mf string mf separator m sharedfilesmenu append menu mf string mp detail get res string ids showdetails t fileinfo m sharedfilesmenu append menu mf string mp cmt get res string ids cmt add t filecomments if the prefs get show copy ed2k link cmd m sharedfilesmenu append menu mf string mp geted2klink get res string ids dl link1 t ed2klink else m sharedfilesmenu append menu mf string mp showed2klink get res string ids dl showed2klink t ed2klink m sharedfilesmenu append menu mf string mp find get res string ids find t search m sharedfilesmenu append menu mf string mf separator if defined debug if the prefs is ext controls enabled johntodo not for release as we need kad lowid users in the network to see how well this work work also we do not support these links yet m sharedfilesmenu append menu mf string mp getkadsourcelink t copy ed2k links to clipboard kad m sharedfilesmenu append menu mf string mf separator endif csharedfilesctrl createmenues m_priomenu m_priomenu destroymenu m_collectionsmenu m_collectionsmenu destroymenu m_sharedfilesmenu m_sharedfilesmenu destroymenu m_priomenu createmenu m_priomenu appendmenu mf_string mp_prioverylow getresstring ids_prioverylow m_priomenu appendmenu mf_string mp_priolow getresstring ids_priolow m_priomenu appendmenu mf_string mp_prionormal getresstring ids_prionormal m_priomenu appendmenu mf_string mp_priohigh getresstring ids_priohigh m_priomenu appendmenu mf_string mp_prioveryhigh getresstring ids_priorelease m_priomenu appendmenu mf_string mp_prioauto getresstring ids_prioauto m_collectionsmenu createmenu m_collectionsmenu addmenutitle m_collectionsmenu appendmenu mf_string mp_createcollection getresstring ids_createcollection _t collection_add m_collectionsmenu appendmenu mf_string mp_modifycollection getresstring ids_modifycollection _t collection_edit m_collectionsmenu appendmenu mf_string mp_viewcollection getresstring ids_viewcollection _t collection_view m_collectionsmenu appendmenu mf_string mp_searchauthor getresstring ids_searchauthorcollection _t collection_search m_sharedfilesmenu createpopupmenu m_sharedfilesmenu addmenutitle getresstring ids_sharedfiles m_sharedfilesmenu appendmenu mf_string mp_open getresstring ids_openfile _t m_sharedfilesmenu appendmenu mf_string mp_openfolder getresstring ids_openfolder _t m_sharedfilesmenu appendmenu mf_string mp_rename getresstring ids_rename _t _t m_sharedfilesmenu appendmenu mf_string mp_remove getresstring ids_delete _t theprefs isextcontrolsenabled m_sharedfilesmenu appendmenu mf_string irc_setsendlink getresstring ids_irc_addlinktoirc _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedfilesmenu appendmenu mf_string mf_popup uint_ptr m_priomenu m_hmenu getresstring ids_priority _t getresstring ids_pw_con_uplbl _t _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedfilesmenu appendmenu mf_string mf_popup uint_ptr m_collectionsmenu m_hmenu getresstring ids_meta_collection _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedfilesmenu appendmenu mf_string mp_detail getresstring ids_showdetails _t m_sharedfilesmenu appendmenu mf_string mp_cmt getresstring ids_cmt_add _t theprefs getshowcopyed2klinkcmd m_sharedfilesmenu appendmenu mf_string mp_geted2klink getresstring ids_dl_link1 _t m_sharedfilesmenu appendmenu mf_string mp_showed2klink getresstring ids_dl_showed2klink _t m_sharedfilesmenu appendmenu mf_string mp_find getresstring ids_find _t m_sharedfilesmenu appendmenu mf_string mf_separator _debug theprefs isextcontrolsenabled m_sharedfilesmenu appendmenu mf_string mp_getkadsourcelink _t m_sharedfilesmenu appendmenu mf_string mf_separator void c shared files ctrl reload file list delete all items the app emuledlg sharedfileswnd show selected files summary cc key buf key c known file cur file for position pos the app sharedfiles m files map get start position pos 0 the app sharedfiles m files map get next assoc pos buf key cur file add file cur file show files count csharedfilesctrl reloadfilelist deleteallitems theapp showselectedfilessummary cckey bufkey cknownfile cur_file theapp m_files_map getstartposition theapp m_files_map getnextassoc bufkey cur_file addfile cur_file showfilescount void c shared files ctrl add file const c known file file if the app emuledlg is running return check filter conditions if we should show this file right now if m pdirectoryfilter null c string str file path file get path if str file path right 1 str file path str file path left str file path get length 1 switch m pdirectoryfilter m eitemtype case sdi all no filter break case sdi filesystemparent return no files break case sdi no some shared directory case sdi catincoming categories with special incoming dirs case sdi unshareddirectory items from the whole filesystem tree if str file path compare no case m pdirectoryfilter m strfullpath 0 return break case sdi temp only tempfiles if file is part file return else if m pdirectoryfilter m ncatfilter 1 uint m pdirectoryfilter m ncatfilter c part file file get category return break case sdi directory any userselected shared dir but not incoming or temp if file is part file return if str file path compare no case the prefs get incoming dir 0 return break case sdi incoming main incoming directory if str file path compare no case the prefs get incoming dir 0 return hmm should we show all incoming files dirs or only those from the main incoming dir here hard choice will only show the main for now break if find file file 1 return int i item insert item lvif text lvif param get item count lpstr textcallback 0 0 0 lparam file if i item 0 update i item csharedfilesctrl addfile cknownfile theapp isrunning m_pdirectoryfilter cstring strfilepath getpath strfilepath strfilepath strfilepath strfilepath getlength m_pdirectoryfilter m_eitemtype sdi_all sdi_filesystemparent sdi_no sdi_catincoming sdi_unshareddirectory strfilepath comparenocase m_pdirectoryfilter m_strfullpath sdi_temp ispartfile m_pdirectoryfilter m_ncatfilter m_pdirectoryfilter m_ncatfilter cpartfile getcategory sdi_directory ispartfile strfilepath comparenocase theprefs getincomingdir sdi_incoming strfilepath comparenocase theprefs getincomingdir findfile iitem insertitem lvif_text lvif_param getitemcount lpstr_textcallback iitem iitem void c shared files ctrl remove file const c known file file int i item find file file if i item 1 delete item i item show files count csharedfilesctrl removefile cknownfile iitem findfile iitem deleteitem iitem showfilescount void c shared files ctrl update file const c known file file if file the app emuledlg is running return int i item find file file if i item 1 update i item if get item state i item lvis selected the app emuledlg sharedfileswnd show selected files summary csharedfilesctrl updatefile cknownfile theapp isrunning iitem findfile iitem iitem getitemstate iitem lvis_selected theapp showselectedfilessummary void c shared files ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res str res get res string ids dl filename hdi psz text const cast lptstr lpctstr str res p header ctrl set item 0 hdi str res get res string ids dl size hdi psz text const cast lptstr lpctstr str res p header ctrl set item 1 hdi str res get res string ids type hdi psz text const cast lptstr lpctstr str res p header ctrl set item 2 hdi str res get res string ids priority hdi psz text const cast lptstr lpctstr str res p header ctrl set item 3 hdi str res get res string ids fileid hdi psz text const cast lptstr lpctstr str res p header ctrl set item 4 hdi str res get res string ids sf requests hdi psz text const cast lptstr lpctstr str res p header ctrl set item 5 hdi str res get res string ids sf accepts hdi psz text const cast lptstr lpctstr str res p header ctrl set item 6 hdi str res get res string ids sf transferred hdi psz text const cast lptstr lpctstr str res p header ctrl set item 7 hdi str res get res string ids shared status hdi psz text const cast lptstr lpctstr str res p header ctrl set item 8 hdi str res get res string ids folder hdi psz text const cast lptstr lpctstr str res p header ctrl set item 9 hdi str res get res string ids complsources hdi psz text const cast lptstr lpctstr str res p header ctrl set item 10 hdi str res get res string ids sharedtitle hdi psz text const cast lptstr lpctstr str res p header ctrl set item 11 hdi create menues int i items get item count for int i 0 i i items i update i csharedfilesctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres strres getresstring ids_dl_filename psztext const_cast strres pheaderctrl setitem strres getresstring ids_dl_size psztext const_cast strres pheaderctrl setitem strres getresstring ids_type psztext const_cast strres pheaderctrl setitem strres getresstring ids_priority psztext const_cast strres pheaderctrl setitem strres getresstring ids_fileid psztext const_cast strres pheaderctrl setitem strres getresstring ids_sf_requests psztext const_cast strres pheaderctrl setitem strres getresstring ids_sf_accepts psztext const_cast strres pheaderctrl setitem strres getresstring ids_sf_transferred psztext const_cast strres pheaderctrl setitem strres getresstring ids_shared_status psztext const_cast strres pheaderctrl setitem strres getresstring ids_folder psztext const_cast strres pheaderctrl setitem strres getresstring ids_complsources psztext const_cast strres pheaderctrl setitem strres getresstring ids_sharedtitle psztext const_cast strres pheaderctrl setitem createmenues iitems getitemcount iitems void c shared files ctrl show files count c string str if the app sharedfiles get hashing count naich hashing str format t i s i the app sharedfiles get count get res string ids hashing the app sharedfiles get hashing count naich hashing else str format t i the app sharedfiles get count the app emuledlg sharedfileswnd get dlg item idc traffic text set window text get res string ids sf files str csharedfilesctrl showfilescount cstring theapp gethashingcount naichhashing _t theapp getcount getresstring ids_hashing theapp gethashingcount naichhashing _t theapp getcount theapp getdlgitem idc_traffic_text setwindowtext getresstring ids_sf_files void c shared files ctrl show comments c known file file if file c typed ptr list c ptr list c known file a files a files add head file show file dialog a files idd comment csharedfilesctrl showcomments cknownfile ctypedptrlist cptrlist cknownfile afiles afiles addhead showfiledialog afiles idd_comment void c shared files ctrl set directory filter c directory item p new filter bool b refresh if m pdirectoryfilter p new filter return m pdirectoryfilter p new filter if b refresh reload file list csharedfilesctrl setdirectoryfilter cdirectoryitem pnewfilter brefresh m_pdirectoryfilter pnewfilter m_pdirectoryfilter pnewfilter brefresh reloadfilelist int c shared files ctrl sort proc lparam l param1 lparam l param2 lparam l param sort const c known file item1 c known file l param1 const c known file item2 c known file l param2 int i result 0 switch l param sort case 0 filename asc i result compare locale string no case item1 get file name item2 get file name break case 20 filename desc i result compare locale string no case item2 get file name item1 get file name break case 1 filesize asc i result item1 get file size item2 get file size 0 item1 get file size item2 get file size 1 1 break case 21 filesize desc i result item1 get file size item2 get file size 0 item2 get file size item1 get file size 1 1 break case 2 filetype asc i result item1 get file type display str compare item2 get file type display str break case 22 filetype desc i result item2 get file type display str compare item1 get file type display str break case 3 prio asc uint8 p1 item1 get up priority 1 if p1 5 p1 0 uint8 p2 item2 get up priority 1 if p2 5 p2 0 i result p1 p2 break case 23 prio desc uint8 p1 item1 get up priority 1 if p1 5 p1 0 uint8 p2 item2 get up priority 1 if p2 5 p2 0 i result p2 p1 break case 4 fileid asc i result memcmp item1 get file hash item2 get file hash 16 break case 24 fileid desc i result memcmp item2 get file hash item1 get file hash 16 break case 5 requests asc i result item1 statistic get requests item2 statistic get requests break case 25 requests desc i result item2 statistic get requests item1 statistic get requests break case 6 acc requests asc i result item1 statistic get accepts item2 statistic get accepts break case 26 acc requests desc i result item2 statistic get accepts item1 statistic get accepts break case 7 all transferred asc i result item1 statistic get transferred item2 statistic get transferred 0 item1 statistic get transferred item2 statistic get transferred 1 1 break case 27 all transferred desc i result item1 statistic get transferred item2 statistic get transferred 0 item2 statistic get transferred item1 statistic get transferred 1 1 break case 9 folder asc i result compare locale string no case item1 get path item2 get path break case 29 folder desc i result compare locale string no case item2 get path item1 get path break case 10 complete sources asc i result compare unsigned item1 m ncompletesourcescount item2 m ncompletesourcescount break case 30 complete sources desc i result compare unsigned item2 m ncompletesourcescount item1 m ncompletesourcescount break case 11 ed2k shared asc i result item1 get publisheded2k item2 get publisheded2k break case 31 ed2k shared desc i result item2 get publisheded2k item1 get publisheded2k break case 105 all requests asc i result compare unsigned item1 statistic get all time requests item2 statistic get all time requests break case 125 all requests desc i result compare unsigned item2 statistic get all time requests item1 statistic get all time requests break case 106 all acc requests asc i result compare unsigned item1 statistic get all time accepts item2 statistic get all time accepts break case 126 all acc requests desc i result compare unsigned item2 statistic get all time accepts item1 statistic get all time accepts break case 107 all transferred asc i result item1 statistic get all time transferred item2 statistic get all time transferred 0 item1 statistic get all time transferred item2 statistic get all time transferred 1 1 break case 127 all transferred desc i result item1 statistic get all time transferred item2 statistic get all time transferred 0 item2 statistic get all time transferred item1 statistic get all time transferred 1 1 break case 111 kad shared asc uint32 t now time null int i1 t now item1 get last publish time kad src 1 0 int i2 t now item2 get last publish time kad src 1 0 i result i1 i2 break case 131 kad shared desc uint32 t now time null int i1 t now item1 get last publish time kad src 1 0 int i2 t now item2 get last publish time kad src 1 0 i result i2 i1 break default i result 0 break int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if i result 0 dw next sort the app emuledlg sharedfileswnd sharedfilesctrl get next sort order l param sort 1 i result sort proc l param1 l param2 dw next sort return i result csharedfilesctrl sortproc lparam1 lparam2 lparamsort cknownfile cknownfile lparam1 cknownfile cknownfile lparam2 iresult lparamsort iresult comparelocalestringnocase getfilename getfilename iresult comparelocalestringnocase getfilename getfilename iresult getfilesize getfilesize getfilesize getfilesize iresult getfilesize getfilesize getfilesize getfilesize iresult getfiletypedisplaystr getfiletypedisplaystr iresult getfiletypedisplaystr getfiletypedisplaystr getuppriority getuppriority iresult getuppriority getuppriority iresult iresult getfilehash getfilehash iresult getfilehash getfilehash iresult getrequests getrequests iresult getrequests getrequests iresult getaccepts getaccepts iresult getaccepts getaccepts iresult gettransferred gettransferred gettransferred gettransferred iresult gettransferred gettransferred gettransferred gettransferred iresult comparelocalestringnocase getpath getpath iresult comparelocalestringnocase getpath getpath iresult compareunsigned m_ncompletesourcescount m_ncompletesourcescount iresult compareunsigned m_ncompletesourcescount m_ncompletesourcescount iresult getpublisheded2k getpublisheded2k iresult getpublisheded2k getpublisheded2k iresult compareunsigned getalltimerequests getalltimerequests iresult compareunsigned getalltimerequests getalltimerequests iresult compareunsigned getalltimeaccepts getalltimeaccepts iresult compareunsigned getalltimeaccepts getalltimeaccepts iresult getalltimetransferred getalltimetransferred getalltimetransferred getalltimetransferred iresult getalltimetransferred getalltimetransferred getalltimetransferred getalltimetransferred tnow tnow getlastpublishtimekadsrc tnow getlastpublishtimekadsrc iresult tnow tnow getlastpublishtimekadsrc tnow getlastpublishtimekadsrc iresult iresult dwnextsort iresult dwnextsort theapp getnextsortorder lparamsort iresult sortproc lparam1 lparam2 dwnextsort iresult void c shared files ctrl open file const c known file file if file m pcollection c collection view dialog dialog dialog set collection file m pcollection dialog do modal else shell open file file get file path null csharedfilesctrl openfile cknownfile m_pcollection ccollectionviewdialog setcollection m_pcollection domodal shellopenfile getfilepath void c shared files ctrl show file dialog c typed ptr list c ptr list c known file a files uint u psh invoke page if a files get size 0 c shared file details sheet dialog a files u psh invoke page this dialog do modal csharedfilesctrl showfiledialog ctypedptrlist cptrlist cknownfile afiles upshinvokepage afiles getsize csharedfiledetailssheet afiles upshinvokepage domodal void c shared files ctrl set all icons m imagelist delete image list m imagelist create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 m imagelist set bk color clr none m imagelist add c temp icon loader t empty m imagelist add c temp icon loader t file shared server 16 16 m imagelist add c temp icon loader t file shared kad 16 16 m imagelist add c temp icon loader t rating notrated m imagelist add c temp icon loader t rating fake m imagelist add c temp icon loader t rating poor m imagelist add c temp icon loader t rating fair m imagelist add c temp icon loader t rating good m imagelist add c temp icon loader t rating excellent m imagelist set overlay image m imagelist add c temp icon loader t file comments ovl 1 csharedfilesctrl setallicons m_imagelist deleteimagelist m_imagelist theapp m_idfltimagelistcolorflags ilc_mask m_imagelist setbkcolor clr_none m_imagelist ctempiconloader _t m_imagelist ctempiconloader _t filesharedserver m_imagelist ctempiconloader _t filesharedkad m_imagelist ctempiconloader _t rating_notrated m_imagelist ctempiconloader _t rating_fake m_imagelist ctempiconloader _t rating_poor m_imagelist ctempiconloader _t rating_fair m_imagelist ctempiconloader _t rating_good m_imagelist ctempiconloader _t rating_excellent m_imagelist setoverlayimage m_imagelist ctempiconloader _t filecommentsovl int c shared files ctrl find file const c known file p file lvfindinfo find find flags lvfi param find l param lparam p file return find item find csharedfilesctrl findfile cknownfile pfile lvfi_param lparam pfile finditem bool c shared files ctrl on command wparam w param lparam l param w param loword w param c typed ptr list c ptr list c known file selected list position pos get first selected item position while pos null int index get next selected item pos if index 0 selected list add tail c known file get item data index if w param mp createcollection w param mp find selected list get count 0 c known file file null if selected list get count 1 file selected list get head switch w param case irc setsendlink if file the app emuledlg ircwnd set send file string createed2k link file break case mp geted2klink c string str position pos selected list get head position while pos null file selected list get next pos if str is empty str t r n str createed2k link file the app copy text to clipboard str break if defined debug johntodo not for release as we need kad lowid users in the network to see how well this work work also we do not support these links yet case mp getkadsourcelink c string str position pos selected list get head position while pos null file selected list get next pos if str is empty str t r n str the app create kad source link file the app copy text to clipboard str break endif file operations case mp open case ida enter if file file is part file open file file break case mp install skin if file file is part file install skin file get file path break case mp openfolder if file file is part file shell execute null t open file get path null null sw show break case mp rename case mpg f2 if file file is part file input box inputbox c string title get res string ids rename title remove t inputbox set labels title get res string ids dl filename file get file name inputbox set edit filename mode inputbox do modal c string newname inputbox get input if inputbox was cancelled newname get length 0 at least prevent users from specifying something like dir file static const tchar szinvfilenamechars t if newname find one of szinvfilenamechars 1 afx message box get error message error bad pathname break c string newpath path combine newpath get buffer max path file get path newname newpath release buffer if trename file get file path newpath 0 c string str error str error format get res string ids err renamesf file get file path newpath strerror errno afx message box str error break if file is kind of runtime class c part file file set file name newname else the app sharedfiles remove keywords file file set file name newname the app sharedfiles add keywords file file set file path newpath update file file else message beep mb ok break case mp remove case mpg delete if idno afx message box get res string ids confirm filedelete mb iconwarning mb iconquestion mb defbutton2 mb yesno return true set redraw false bool b removed items false while selected list is empty c known file myfile selected list remove head if myfile myfile is part file continue bool delsucc false if path file exists myfile get file path delsucc true else delete if the prefs get remove to bin delsucc delete file myfile get file path else delete to recycle bin tchar todel max path 1 memset todel 0 sizeof todel tcsncpy todel myfile get file path arrsize todel 2 shfileopstruct fp 0 fp w func fo delete fp hwnd the app emuledlg m hwnd fp p from todel fp f flags fof allowundo fof noconfirmation fof silent fof noerrorui delsucc sh file operation fp 0 if delsucc the app sharedfiles remove file myfile b removed items true if myfile is kind of runtime class c part file the app emuledlg transferwnd downloadlistctrl clear completed static cast c part file myfile else c string str error str error format get res string ids err delfile t r n r n s myfile get file path get error message get last error afx message box str error set redraw true if b removed items auto select item break case mp cmt show file dialog selected list idd comment break case mpg altenter case mp detail show file dialog selected list break case mp find on find start break case mp createcollection c collection p collection new c collection position pos selected list get head position while pos null p collection add file to collection selected list get next pos true c collection create dialog dialog dialog set collection p collection true dialog do modal we delete this collection object because when the newly created collection file is added to the sharedfile list it is read and verified and which creates the colleciton object that is attached to that file delete p collection break case mp searchauthor if selected list get count 1 file m pcollection s search params p params new s search params p params str expression file m pcollection get collection author key string p params e type search type kademlia p params str file type ed2kftstr emulecollection p params str special title file m pcollection m scollectionauthorname if p params str special title get length 50 p params str special title p params str special title left 50 t the app emuledlg searchwnd m pwndresults start search p params break case mp viewcollection if selected list get count 1 file m pcollection c collection view dialog dialog dialog set collection file m pcollection dialog do modal break case mp modifycollection if selected list get count 1 file m pcollection c collection create dialog dialog c collection p collection new c collection file m pcollection dialog set collection p collection false dialog do modal delete p collection break case mp showed2klink show file dialog selected list idd ed2klink break case mp prioverylow case mp priolow case mp prionormal case mp priohigh case mp prioveryhigh case mp prioauto position pos selected list get head position while pos null c known file file selected list get next pos switch w param case mp prioverylow file set auto up priority false file set up priority pr verylow update file file break case mp priolow file set auto up priority false file set up priority pr low update file file break case mp prionormal file set auto up priority false file set up priority pr normal update file file break case mp priohigh file set auto up priority false file set up priority pr high update file file break case mp prioveryhigh file set auto up priority false file set up priority pr veryhigh update file file break case mp prioauto file set auto up priority true file update auto up priority update file file break break default if w param mp weburl w param mp weburl 256 the web services runurl file w param break return true csharedfilesctrl oncommand wparam lparam wparam wparam ctypedptrlist cptrlist cknownfile selectedlist getfirstselecteditemposition getnextselecteditem selectedlist addtail cknownfile getitemdata wparam mp_createcollection wparam mp_find selectedlist getcount cknownfile selectedlist getcount selectedlist gethead wparam irc_setsendlink theapp setsendfilestring createed2klink mp_geted2klink cstring selectedlist getheadposition selectedlist getnext isempty _t createed2klink theapp copytexttoclipboard _debug mp_getkadsourcelink cstring selectedlist getheadposition selectedlist getnext isempty _t theapp createkadsourcelink theapp copytexttoclipboard mp_open ida_enter ispartfile openfile mp_install_skin ispartfile installskin getfilepath mp_openfolder ispartfile shellexecute _t getpath sw_show mp_rename mpg_f2 ispartfile inputbox cstring getresstring ids_rename _t setlabels getresstring ids_dl_filename getfilename seteditfilenamemode domodal cstring getinput wascancelled getlength _szinvfilenamechars _t findoneof _szinvfilenamechars afxmessagebox geterrormessage error_bad_pathname cstring pathcombine getbuffer max_path getpath releasebuffer _trename getfilepath cstring strerror strerror getresstring ids_err_renamesf getfilepath afxmessagebox strerror iskindof runtime_class cpartfile setfilename theapp removekeywords setfilename theapp addkeywords setfilepath updatefile messagebeep mb_ok mp_remove mpg_delete afxmessagebox getresstring ids_confirm_filedelete mb_iconwarning mb_iconquestion mb_defbutton2 mb_yesno setredraw bremoveditems selectedlist isempty cknownfile selectedlist removehead ispartfile pathfileexists getfilepath theprefs getremovetobin deletefile getfilepath max_path _tcsncpy getfilepath wfunc fo_delete theapp m_hwnd pfrom fflags fof_allowundo fof_noconfirmation fof_silent fof_noerrorui shfileoperation theapp removefile bremoveditems iskindof runtime_class cpartfile theapp clearcompleted static_cast cpartfile cstring strerror strerror getresstring ids_err_delfile _t getfilepath geterrormessage getlasterror afxmessagebox strerror setredraw bremoveditems autoselectitem mp_cmt showfiledialog selectedlist idd_comment mpg_altenter mp_detail showfiledialog selectedlist mp_find onfindstart mp_createcollection ccollection pcollection ccollection selectedlist getheadposition pcollection addfiletocollection selectedlist getnext ccollectioncreatedialog setcollection pcollection domodal pcollection mp_searchauthor selectedlist getcount m_pcollection ssearchparams pparams ssearchparams pparams strexpression m_pcollection getcollectionauthorkeystring pparams etype searchtypekademlia pparams strfiletype ed2kftstr_emulecollection pparams strspecialtitle m_pcollection m_scollectionauthorname pparams strspecialtitle getlength pparams strspecialtitle pparams strspecialtitle _t theapp m_pwndresults startsearch pparams mp_viewcollection selectedlist getcount m_pcollection ccollectionviewdialog setcollection m_pcollection domodal mp_modifycollection selectedlist getcount m_pcollection ccollectioncreatedialog ccollection pcollection ccollection m_pcollection setcollection pcollection domodal pcollection mp_showed2klink showfiledialog selectedlist idd_ed2klink mp_prioverylow mp_priolow mp_prionormal mp_priohigh mp_prioveryhigh mp_prioauto selectedlist getheadposition cknownfile selectedlist getnext wparam mp_prioverylow setautouppriority setuppriority pr_verylow updatefile mp_priolow setautouppriority setuppriority pr_low updatefile mp_prionormal setautouppriority setuppriority pr_normal updatefile mp_priohigh setautouppriority setuppriority pr_high updatefile mp_prioveryhigh setautouppriority setuppriority pr_veryhigh updatefile mp_prioauto setautouppriority updateautouppriority updatefile wparam mp_weburl wparam mp_weburl thewebservices wparam void c shared files ctrl draw item lpdrawitemstruct lp draw item struct if the app emuledlg is running return if lp draw item struct item data return cdc odc cdc from handle lp draw item struct hdc bool b ctrl focused get focus this get style lvs showselalways if lp draw item struct item state ods selected if b ctrl focused odc set bk color m crhighlight else odc set bk color m crnohighlight else odc set bk color get bk color const c known file file c known file lp draw item struct item data c memdc dc odc lp draw item struct rc item c font p old font dc select object get font c rect cur rec lp draw item struct rc item colorref cr old text color dc set text color lp draw item struct item state ods selected m crhighlighttext m crwindowtext int i old bk mode if m crwindowtextbk clr none def window proc wm erasebkgnd wparam hdc dc 0 i old bk mode dc set bk mode transparent else i old bk mode opaque c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count const int i marginx 4 cur rec right cur rec left i marginx 2 cur rec left i marginx c string buffer int i icon draw width the app get small sytem icon size cx 3 for int i current 0 i current i count i current int i column p header ctrl order to index i current if is column hidden i column uint udt flags dlc dt text cur rec right get column width i column switch i column case 0 int i image the app get file type system image idx file get file name if the app get system image list null imagelist draw the app get system image list i image dc get safe hdc cur rec left cur rec top ild normal ild transparent if file get file comment is empty file get file rating m imagelist draw dc 0 c point cur rec left cur rec top ild normal ild transparent indextooverlaymask 1 cur rec left i icon draw width 3 if the prefs show rating indicator file has comment file has rating m imagelist draw dc file user rating 3 c point cur rec left cur rec top ild normal cur rec left 16 i icon draw width 16 cur rec left 3 buffer file get file name break case 1 buffer cast itox bytes file get file size false false udt flags dt right break case 2 buffer file get file type display str break case 3 switch file get up priority case pr verylow buffer get res string ids prioverylow break case pr low if file is auto up priority buffer get res string ids prioautolow else buffer get res string ids priolow break case pr normal if file is auto up priority buffer get res string ids prioautonormal else buffer get res string ids prionormal break case pr high if file is auto up priority buffer get res string ids prioautohigh else buffer get res string ids priohigh break case pr veryhigh buffer get res string ids priorelease break default buffer empty break case 4 buffer md4str file get file hash break case 5 buffer format t u u file statistic get requests file statistic get all time requests break case 6 buffer format t u u file statistic get accepts file statistic get all time accepts break case 7 buffer format t s s cast itox bytes file statistic get transferred false false cast itox bytes file statistic get all time transferred false false break case 8 if file get part count cur rec bottom cur rec top file draw share status bar dc cur rec false the prefs use flat bar cur rec bottom cur rec top break case 9 buffer file get path path remove backslash buffer get buffer buffer release buffer break case 10 if file m ncompletesourcescountlo file m ncompletesourcescounthi buffer format t u file m ncompletesourcescountlo else if file m ncompletesourcescountlo 0 buffer format t u file m ncompletesourcescounthi else buffer format t u u file m ncompletesourcescountlo file m ncompletesourcescounthi break case 11 c point pt cur rec left cur rec top m imagelist draw dc file get publisheded2k 1 0 pt ild normal ild transparent pt x 16 bool b shared in kad if uint32 time null file get last publish time kad src if the app is firewalled the app is connected if the app clientlist get buddy file get last publish buddy the app clientlist get buddy getip b shared in kad true else b shared in kad false else b shared in kad true else b shared in kad false m imagelist draw dc b shared in kad 2 0 pt ild normal ild transparent buffer empty break if i column 8 dc draw text buffer buffer get length cur rec udt flags if i column 0 cur rec left i icon draw width cur rec left get column width i column show files count if lp draw item struct item state ods selected rect outline rec lp draw item struct rc item outline rec top outline rec bottom dc frame rect outline rec c brush m crwindow outline rec top outline rec bottom outline rec left outline rec right if lp draw item struct itemid 0 get item state lp draw item struct itemid 1 lvis selected outline rec top if lp draw item struct itemid 1 uint get item count get item state lp draw item struct itemid 1 lvis selected outline rec bottom if b ctrl focused dc frame rect outline rec c brush m crfocusline else dc frame rect outline rec c brush m crnofocusline if m crwindowtextbk clr none dc set bk mode i old bk mode dc select object p old font dc set text color cr old text color csharedfilesctrl drawitem lpdrawitemstruct theapp isrunning lpdrawitemstruct itemdata fromhandle lpdrawitemstruct bctrlfocused getfocus getstyle lvs_showselalways lpdrawitemstruct itemstate ods_selected bctrlfocused setbkcolor m_crhighlight setbkcolor m_crnohighlight setbkcolor getbkcolor cknownfile cknownfile lpdrawitemstruct itemdata cmemdc lpdrawitemstruct rcitem cfont poldfont selectobject getfont crect cur_rec lpdrawitemstruct rcitem croldtextcolor settextcolor lpdrawitemstruct itemstate ods_selected m_crhighlighttext m_crwindowtext ioldbkmode m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd ioldbkmode setbkmode ioldbkmode cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount imarginx cur_rec cur_rec imarginx cur_rec imarginx cstring iicondrawwidth theapp getsmallsytemiconsize icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent iscolumnhidden icolumn udtflags dlc_dt_text cur_rec getcolumnwidth icolumn icolumn iimage theapp getfiletypesystemimageidx getfilename theapp getsystemimagelist imagelist_draw theapp getsystemimagelist iimage getsafehdc cur_rec cur_rec ild_normal ild_transparent getfilecomment isempty getfilerating m_imagelist cpoint cur_rec cur_rec ild_normal ild_transparent cur_rec iicondrawwidth theprefs showratingindicator hascomment hasrating m_imagelist userrating cpoint cur_rec cur_rec ild_normal cur_rec iicondrawwidth cur_rec getfilename castitoxbytes getfilesize udtflags dt_right getfiletypedisplaystr getuppriority pr_verylow getresstring ids_prioverylow pr_low isautouppriority getresstring ids_prioautolow getresstring ids_priolow pr_normal isautouppriority getresstring ids_prioautonormal getresstring ids_prionormal pr_high isautouppriority getresstring ids_prioautohigh getresstring ids_priohigh pr_veryhigh getresstring ids_priorelease getfilehash _t getrequests getalltimerequests _t getaccepts getalltimeaccepts _t castitoxbytes gettransferred castitoxbytes getalltimetransferred getpartcount cur_rec cur_rec drawsharestatusbar cur_rec theprefs useflatbar cur_rec cur_rec getpath pathremovebackslash getbuffer releasebuffer m_ncompletesourcescountlo m_ncompletesourcescounthi _t m_ncompletesourcescountlo m_ncompletesourcescountlo _t m_ncompletesourcescounthi _t m_ncompletesourcescountlo m_ncompletesourcescounthi cpoint cur_rec cur_rec m_imagelist getpublisheded2k ild_normal ild_transparent bsharedinkad getlastpublishtimekadsrc theapp isfirewalled theapp isconnected theapp getbuddy getlastpublishbuddy theapp getbuddy bsharedinkad bsharedinkad bsharedinkad bsharedinkad m_imagelist bsharedinkad ild_normal ild_transparent icolumn drawtext getlength cur_rec udtflags icolumn cur_rec iicondrawwidth cur_rec getcolumnwidth icolumn showfilescount lpdrawitemstruct itemstate ods_selected outline_rec lpdrawitemstruct rcitem outline_rec outline_rec framerect outline_rec cbrush m_crwindow outline_rec outline_rec outline_rec outline_rec lpdrawitemstruct getitemstate lpdrawitemstruct lvis_selected outline_rec lpdrawitemstruct getitemcount getitemstate lpdrawitemstruct lvis_selected outline_rec bctrlfocused framerect outline_rec cbrush m_crfocusline framerect outline_rec cbrush m_crnofocusline m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor void c shared files ctrl on sys color change c mule list ctrl on sys color change set all icons create menues csharedfilesctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons createmenues void c shared files ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr barry store sort order in preferences determine ascending based on whether already sorted on this column bool sort ascending get sort item pnm list view i sub item true get sort ascending ornis 4 way sorting int adder 0 if pnm list view i sub item 5 pnm list view i sub item 7 assert pnm list view i sub item 5 arrsize sortstat if sort ascending sortstat pnm list view i sub item 5 sortstat pnm list view i sub item 5 adder sortstat pnm list view i sub item 5 0 100 else if pnm list view i sub item 11 assert 3 arrsize sortstat if sort ascending sortstat 3 sortstat 3 adder sortstat 3 0 100 sort table if adder 0 set sort arrow pnm list view i sub item sort ascending else set sort arrow pnm list view i sub item sort ascending arrow double up arrow double down update sort history pnm list view i sub item adder sort ascending 0 20 20 sort items sort proc pnm list view i sub item adder sort ascending 0 20 p result 0 csharedfilesctrl oncolumnclick presult nm_listview pnmlistview nm_listview sortascending getsortitem pnmlistview isubitem getsortascending pnmlistview isubitem pnmlistview isubitem pnmlistview isubitem sortascending pnmlistview isubitem pnmlistview isubitem pnmlistview isubitem pnmlistview isubitem sortascending setsortarrow pnmlistview isubitem sortascending setsortarrow pnmlistview isubitem sortascending arrowdoubleup arrowdoubledown updatesorthistory pnmlistview isubitem sortascending sortitems sortproc pnmlistview isubitem sortascending presult void c shared files ctrl on context menu c wnd p wnd c point point get merged settings bool b first item true int i selected items get selected count int i complete file selected 1 uint u prio menu item 0 const c known file p single sel file null position pos get first selected item position while pos const c known file p file c known file get item data get next selected item pos if b first item p single sel file p file else p single sel file null int i cur complete file p file is part file 0 1 if b first item i complete file selected i cur complete file else if i complete file selected i cur complete file i complete file selected 1 uint u cur prio menu item 0 if p file is auto up priority u cur prio menu item mp prioauto else if p file get up priority pr verylow u cur prio menu item mp prioverylow else if p file get up priority pr low u cur prio menu item mp priolow else if p file get up priority pr normal u cur prio menu item mp prionormal else if p file get up priority pr high u cur prio menu item mp priohigh else if p file get up priority pr veryhigh u cur prio menu item mp prioveryhigh else assert 0 if b first item u prio menu item u cur prio menu item else if u prio menu item u cur prio menu item u prio menu item 0 b first item false m sharedfilesmenu enable menu item uint ptr m priomenu m hmenu i selected items 0 mf enabled mf grayed m priomenu check menu radio item mp prioverylow mp prioauto u prio menu item 0 bool b single complete file selected i selected items 1 i complete file selected 1 m sharedfilesmenu enable menu item mp open b single complete file selected mf enabled mf grayed uint u inserted menu item 0 static const tchar szskinpkgsuffix1 t emulskin baseext t zip static const tchar szskinpkgsuffix2 t emulskin baseext t rar if b single complete file selected p single sel file p single sel file get file path right arrsize szskinpkgsuffix1 1 compare no case szskinpkgsuffix1 0 p single sel file get file path right arrsize szskinpkgsuffix2 1 compare no case szskinpkgsuffix2 0 menuiteminfo mii 0 mii cb size sizeof mii mii f mask miim type miim state miim id mii f type mft string mii f state mfs enabled mii wid mp install skin c string str buff get res string ids install skin mii dw type data const cast lptstr lpctstr str buff if insert menu item m sharedfilesmenu mp openfolder false mii u inserted menu item mii wid m sharedfilesmenu enable menu item mp openfolder b single complete file selected mf enabled mf grayed m sharedfilesmenu enable menu item mp rename b single complete file selected mf enabled mf grayed m sharedfilesmenu enable menu item mp remove i complete file selected 0 mf enabled mf grayed m sharedfilesmenu set default item b single complete file selected mp open 1 m sharedfilesmenu enable menu item mp cmt i selected items 0 mf enabled mf grayed m sharedfilesmenu enable menu item mp detail i selected items 0 mf enabled mf grayed m sharedfilesmenu enable menu item the prefs get show copy ed2k link cmd mp geted2klink mp showed2klink i selected items 0 mf enabled mf grayed m sharedfilesmenu enable menu item mp find get item count 0 mf enabled mf grayed m collectionsmenu enable menu item mp modifycollection p single sel file null p single sel file m pcollection null mf enabled mf grayed m collectionsmenu enable menu item mp viewcollection p single sel file null p single sel file m pcollection null mf enabled mf grayed m collectionsmenu enable menu item mp searchauthor p single sel file null p single sel file m pcollection null p single sel file m pcollection get author key hash string is empty mf enabled mf grayed if defined debug if the prefs is ext controls enabled johntodo not for release as we need kad lowid users in the network to see how well this work work also we do not support these links yet if i selected items 0 the app is connected the app is firewalled the app clientlist get buddy m sharedfilesmenu enable menu item mp getkadsourcelink mf enabled else m sharedfilesmenu enable menu item mp getkadsourcelink mf grayed endif m sharedfilesmenu enable menu item irc setsendlink i selected items 1 the app emuledlg ircwnd is connected mf enabled mf grayed c title menu web menu web menu create menu web menu add menu title null true int i web menu entries the web services get file menu entries web menu uint flag2 i web menu entries 0 i selected items 1 mf grayed mf string m sharedfilesmenu append menu flag2 mf popup uint ptr web menu m hmenu get res string ids webservices t web get popup menu pos this point m sharedfilesmenu track popup menu tpm leftalign tpm rightbutton point x point y this m sharedfilesmenu remove menu m sharedfilesmenu get menu item count 1 mf byposition verify web menu destroy menu if u inserted menu item verify m sharedfilesmenu remove menu u inserted menu item mf bycommand csharedfilesctrl oncontextmenu cwnd pwnd cpoint bfirstitem iselecteditems getselectedcount icompletefileselected upriomenuitem cknownfile psingleselfile getfirstselecteditemposition cknownfile pfile cknownfile getitemdata getnextselecteditem bfirstitem psingleselfile pfile psingleselfile icurcompletefile pfile ispartfile bfirstitem icompletefileselected icurcompletefile icompletefileselected icurcompletefile icompletefileselected ucurpriomenuitem pfile isautouppriority ucurpriomenuitem mp_prioauto pfile getuppriority pr_verylow ucurpriomenuitem mp_prioverylow pfile getuppriority pr_low ucurpriomenuitem mp_priolow pfile getuppriority pr_normal ucurpriomenuitem mp_prionormal pfile getuppriority pr_high ucurpriomenuitem mp_priohigh pfile getuppriority pr_veryhigh ucurpriomenuitem mp_prioveryhigh bfirstitem upriomenuitem ucurpriomenuitem upriomenuitem ucurpriomenuitem upriomenuitem bfirstitem m_sharedfilesmenu enablemenuitem uint_ptr m_priomenu m_hmenu iselecteditems mf_enabled mf_grayed m_priomenu checkmenuradioitem mp_prioverylow mp_prioauto upriomenuitem bsinglecompletefileselected iselecteditems icompletefileselected m_sharedfilesmenu enablemenuitem mp_open bsinglecompletefileselected mf_enabled mf_grayed uinsertedmenuitem _szskinpkgsuffix1 _t emulskin_baseext _t _szskinpkgsuffix2 _t emulskin_baseext _t bsinglecompletefileselected psingleselfile psingleselfile getfilepath _szskinpkgsuffix1 comparenocase _szskinpkgsuffix1 psingleselfile getfilepath _szskinpkgsuffix2 comparenocase _szskinpkgsuffix2 cbsize fmask miim_type miim_state miim_id ftype mft_string fstate mfs_enabled mp_install_skin cstring strbuff getresstring ids_install_skin dwtypedata const_cast strbuff insertmenuitem m_sharedfilesmenu mp_openfolder uinsertedmenuitem m_sharedfilesmenu enablemenuitem mp_openfolder bsinglecompletefileselected mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_rename bsinglecompletefileselected mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_remove icompletefileselected mf_enabled mf_grayed m_sharedfilesmenu setdefaultitem bsinglecompletefileselected mp_open m_sharedfilesmenu enablemenuitem mp_cmt iselecteditems mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_detail iselecteditems mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem theprefs getshowcopyed2klinkcmd mp_geted2klink mp_showed2klink iselecteditems mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_find getitemcount mf_enabled mf_grayed m_collectionsmenu enablemenuitem mp_modifycollection psingleselfile psingleselfile m_pcollection mf_enabled mf_grayed m_collectionsmenu enablemenuitem mp_viewcollection psingleselfile psingleselfile m_pcollection mf_enabled mf_grayed m_collectionsmenu enablemenuitem mp_searchauthor psingleselfile psingleselfile m_pcollection psingleselfile m_pcollection getauthorkeyhashstring isempty mf_enabled mf_grayed _debug theprefs isextcontrolsenabled iselecteditems theapp isconnected theapp isfirewalled theapp getbuddy m_sharedfilesmenu enablemenuitem mp_getkadsourcelink mf_enabled m_sharedfilesmenu enablemenuitem mp_getkadsourcelink mf_grayed m_sharedfilesmenu enablemenuitem irc_setsendlink iselecteditems theapp isconnected mf_enabled mf_grayed ctitlemenu webmenu webmenu createmenu webmenu addmenutitle iwebmenuentries thewebservices getfilemenuentries webmenu iwebmenuentries iselecteditems mf_grayed mf_string m_sharedfilesmenu appendmenu mf_popup uint_ptr webmenu m_hmenu getresstring ids_webservices _t getpopupmenupos m_sharedfilesmenu trackpopupmenu tpm_leftalign tpm_rightbutton m_sharedfilesmenu removemenu m_sharedfilesmenu getmenuitemcount mf_byposition webmenu destroymenu uinsertedmenuitem m_sharedfilesmenu removemenu uinsertedmenuitem mf_bycommand void c shared files ctrl onnm dblclk nmhdr pnmhdr lresult p result int i sel get next item 1 lvis selected lvis focused if i sel 1 c known file file c known file get item data i sel if file if get key state vk menu 0x8000 c typed ptr list c ptr list c known file a files a files add head file show file dialog a files else if file is part file open file file p result 0 csharedfilesctrl onnmdblclk presult isel getnextitem lvis_selected lvis_focused isel cknownfile cknownfile getitemdata isel getkeystate vk_menu ctypedptrlist cptrlist cknownfile afiles afiles addhead showfiledialog afiles ispartfile openfile presult void c shared files ctrl on get disp info nmhdr pnmhdr lresult p result nmlvdispinfo p disp info reinterpret cast nmlvdispinfo pnmhdr if the app emuledlg is running although we have an owner drawn listview control we store the text for the primary item in the listview to be capable of quick searching those items via the keyboard because our listview items may change their contents we do this via a text callback function the listview control will send us the lvn dispinfo notification if it needs to know the contents of the primary item but the listview control sends this notification all the time even if we do not search for an item at least this notification is only sent for the visible items and not for all items in the list though because this function is invoked very often no not put any time consuming code here in if p disp info item mask lvif text const c known file p file reinterpret cast c known file p disp info item l param if p file null switch p disp info item i sub item case 0 if p disp info item cch text max 0 tcsncpy p disp info item psz text p file get file name p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break default shouldn t happen p disp info item psz text 0 t 0 break p result 0 csharedfilesctrl ongetdispinfo presult pdispinfo reinterpret_cast theapp isrunning lvn_dispinfo pdispinfo lvif_text cknownfile pfile reinterpret_cast cknownfile pdispinfo lparam pfile pdispinfo isubitem pdispinfo cchtextmax _tcsncpy pdispinfo psztext pfile getfilename pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t pdispinfo psztext _t presult void c shared files ctrl on key down uint n char uint n rep cnt uint n flags if n char c get key state vk control 0x8000 ctrl c copy listview items to clipboard send message wm command mp geted2klink return else if n char vk f5 reload file list c mule list ctrl on key down n char n rep cnt n flags csharedfilesctrl onkeydown nchar nrepcnt nflags nchar getkeystate vk_control sendmessage wm_command mp_geted2klink nchar vk_f5 reloadfilelist cmulelistctrl onkeydown nchar nrepcnt nflags c tool bar ctrlx c tool bar ctrlx ctoolbarctrlx ctoolbarctrlx c tool bar ctrlx c tool bar ctrlx ctoolbarctrlx ctoolbarctrlx void c tool bar ctrlx adjust font int i max point size c size siz button the toolbar control uses the font which is specified in the current system metrics it does not use the font which is used by the parent so if user switched to large font mode in windows system applet we have to do some adjustements because our toolbar is of fixed size and designed for 8 pt ms shell dlg this function is only needed when the toolbar control is dynamically created if it s created via a dialog resource the font property is handled as expected even when the font is changed in system applet during runtime avoid to use this function it most likely creates glitches on some systems toolbar control is very sensitive to font changes adjust the font only if really needed c font p font get font if p font logfont lf 0 if p font get log font lf 0 hdc hdc getdc null int i point size mul div lf lf height 72 get device caps hdc logpixelsy releasedc null hdc if i point size i max point size c wnd pwnd parent get parent assert pwnd parent null if pwnd parent c font p font dlg pwnd parent get font assert p font dlg null if p font dlg set font p font dlg toolbar control likes to resize buttons and stuff when tbstyle ex drawddarrows is applied if get extended style tbstyle ex drawddarrows 0 set padding c size 0 0 set button size siz button ctoolbarctrlx adjustfont imaxpointsize csize sizbutton cfont pfont getfont pfont pfont getlogfont ipointsize muldiv lfheight getdevicecaps ipointsize imaxpointsize cwnd pwndparent getparent pwndparent pwndparent cfont pfontdlg pwndparent getfont pfontdlg pfontdlg setfont pfontdlg tbstyle_ex_drawddarrows getextendedstyle tbstyle_ex_drawddarrows setpadding csize setbuttonsize sizbutton void c tool bar ctrlx recalc layout force a recalc of the toolbar s layout to work around a comctl bug int i text rows get max text rows set redraw false set max text rows i text rows 1 set max text rows i text rows set redraw true ctoolbarctrlx recalclayout itextrows getmaxtextrows setredraw setmaxtextrows itextrows setmaxtextrows itextrows setredraw void c tool bar ctrlx delete all buttons int i buttons get button count for int i 0 i i buttons i delete button 0 ctoolbarctrlx deleteallbuttons ibuttons getbuttoncount ibuttons deletebutton c string c tool bar ctrlx get btn text int nid tchar sz string 512 tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif text tbbi psz text sz string tbbi cch text countof sz string get button info nid tbbi return sz string cstring ctoolbarctrlx getbtntext szstring cbsize dwmask tbif_text psztext szstring cchtext _countof szstring getbuttoninfo szstring void c tool bar ctrlx set btn text int nid lpctstr psz string tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif text tbbi psz text const cast lptstr psz string set button info nid tbbi ctoolbarctrlx setbtntext pszstring cbsize dwmask tbif_text psztext const_cast pszstring setbuttoninfo int c tool bar ctrlx get btn width int nid tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif size void get button info nid tbbi return tbbi cx ctoolbarctrlx getbtnwidth cbsize dwmask tbif_size getbuttoninfo void c tool bar ctrlx set btn width int nid int i width tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif size tbbi cx word i width set button info nid tbbi ctoolbarctrlx setbtnwidth iwidth cbsize dwmask tbif_size iwidth setbuttoninfo c size c tool bar ctrlx get padding dword dw padding send message tb getpadding return c size loword dw padding hiword dw padding csize ctoolbarctrlx getpadding dwpadding sendmessage tb_getpadding csize dwpadding dwpadding void c tool bar ctrlx set padding c size siz padding send message tb setpadding 0 makelparam siz padding cx siz padding cy ctoolbarctrlx setpadding csize sizpadding sendmessage tb_setpadding sizpadding sizpadding dword c tool bar ctrlx get btn style int id tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif style void get button info id tbbi return tbbi fs style ctoolbarctrlx getbtnstyle cbsize dwmask tbif_style getbuttoninfo fsstyle dword c tool bar ctrlx add btn style int id dword dw style tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif style void get button info id tbbi dword dw old style tbbi fs style tbbi fs style dw style set button info id tbbi return dw old style ctoolbarctrlx addbtnstyle dwstyle cbsize dwmask tbif_style getbuttoninfo dwoldstyle fsstyle fsstyle dwstyle setbuttoninfo dwoldstyle dword c tool bar ctrlx remove btn style int id dword dw style tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif style void get button info id tbbi dword dw old style tbbi fs style tbbi fs style dw style set button info id tbbi return dw old style ctoolbarctrlx removebtnstyle dwstyle cbsize dwmask tbif_style getbuttoninfo dwoldstyle fsstyle fsstyle dwstyle setbuttoninfo dwoldstyle c directory item c directory item c string str full path htreeitem ht item e special directory items e item type int n cat filter m htitem ht item m strfullpath str full path m eitemtype e item type m ncatfilter n cat filter cdirectoryitem cdirectoryitem cstring strfullpath htitem especialdirectoryitems eitemtype ncatfilter m_htitem htitem m_strfullpath strfullpath m_eitemtype eitemtype m_ncatfilter ncatfilter c directory item c directory item while li sub directories get head position null delete li sub directories remove head cdirectoryitem cdirectoryitem lisubdirectories getheadposition lisubdirectories removehead htreeitem c directory item find item c directory item p content to find const if p content to find null assert false return null if p content to find m eitemtype m eitemtype p content to find m strfullpath m strfullpath p content to find m ncatfilter m ncatfilter return m htitem position pos li sub directories get head position while pos null c directory item p current li sub directories get next pos htreeitem ht result if ht result p current find item p content to find null return ht result return null cdirectoryitem finditem cdirectoryitem pcontenttofind pcontenttofind pcontenttofind m_eitemtype m_eitemtype pcontenttofind m_strfullpath m_strfullpath pcontenttofind m_ncatfilter m_ncatfilter m_htitem lisubdirectories getheadposition cdirectoryitem pcurrent lisubdirectories getnext htresult htresult pcurrent finditem pcontenttofind htresult c shared dirs tree ctrl c shared dirs tree ctrl m prootdirectoryitem null m bcreatingtree false m psharedfilesctrl null m prootunshareddirectries null m pdraggingitem null cshareddirstreectrl cshareddirstreectrl m_prootdirectoryitem m_bcreatingtree m_psharedfilesctrl m_prootunshareddirectries m_pdraggingitem c shared dirs tree ctrl c shared dirs tree ctrl delete m prootdirectoryitem delete m prootunshareddirectries cshareddirstreectrl cshareddirstreectrl m_prootdirectoryitem m_prootunshareddirectries void c shared dirs tree ctrl initalize c shared files ctrl p shared files ctrl m psharedfilesctrl p shared files ctrl send message ccm setunicodeformat true word w win ver the prefs get windows version m buseicons true w win ver winver 2k w win ver winver xp w win ver winver me set all icons colorref cr bk get sys color color window colorref cr fg get sys color color windowtext the app load skin color alt t shared dirs tv bk t def lv bk cr bk the app load skin color alt t shared dirs tv fg t def lv fg cr fg set bk color cr bk set text color cr fg initalize standard items filter tree reload tree create menues cshareddirstreectrl csharedfilesctrl psharedfilesctrl m_psharedfilesctrl psharedfilesctrl sendmessage ccm_setunicodeformat wwinver theprefs getwindowsversion m_buseicons wwinver _winver_2k_ wwinver _winver_xp_ wwinver _winver_me_ setallicons crbk getsyscolor color_window crfg getsyscolor color_windowtext theapp loadskincoloralt _t shareddirstvbk _t deflvbk crbk theapp loadskincoloralt _t shareddirstvfg _t deflvfg crfg setbkcolor crbk settextcolor crfg initalizestandarditems filtertreereloadtree createmenues void c shared dirs tree ctrl set all icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml add c temp icon loader t allfiles all directory iml add c temp icon loader t incomplete temp directory iml add c temp icon loader t openfolder incoming directory iml add c temp icon loader t category cats iml add c temp icon loader t harddisk all dirs c string str temp dir the prefs get incoming dir if str temp dir right 1 str temp dir int n image the app get file type system image idx str temp dir system folder icon if the app get system image list null iml add imagelist geticon the app get system image list n image 0 else iml add c temp icon loader t openfolder iml set overlay image iml add c temp icon loader t client secure ovl 1 set image list iml tvsil normal m imltree delete image list m imltree attach iml detach cshareddirstreectrl setallicons cimagelist theapp m_idfltimagelistcolorflags ilc_mask ctempiconloader _t ctempiconloader _t ctempiconloader _t ctempiconloader _t ctempiconloader _t cstring strtempdir theprefs getincomingdir strtempdir strtempdir nimage theapp getfiletypesystemimageidx strtempdir theapp getsystemimagelist imagelist_geticon theapp getsystemimagelist nimage ctempiconloader _t setoverlayimage ctempiconloader _t clientsecureovl setimagelist tvsil_normal m_imltree deleteimagelist m_imltree c directory item c shared dirs tree ctrl get selected filter const if get selected item null return c directory item get item data get selected item else return null cdirectoryitem cshareddirstreectrl getselectedfilter getselecteditem cdirectoryitem getitemdata getselecteditem void c shared dirs tree ctrl localize initalize standard items filter tree reload tree create menues cshareddirstreectrl initalizestandarditems filtertreereloadtree createmenues void c shared dirs tree ctrl edit shared directories c directory item p dir bool b add bool b sub directories assert p dir m eitemtype sdi unshareddirectory c wait cursor cur wait if b add add shared directory p dir m strfullpath b sub directories else remove shared directory p dir m strfullpath b sub directories file system tree set share state p dir b add b sub directories file system tree update bold state filter tree reload tree sync with the preferences list the prefs shareddir list remove all position pos m strlishareddirs get head position copy list while pos c string str path m strlishareddirs get next pos if str path right 1 str path t the prefs shareddir list add tail str path update the sharedfiles list the app emuledlg sharedfileswnd reload the prefs save cshareddirstreectrl editshareddirectories cdirectoryitem pdir badd bsubdirectories pdir m_eitemtype sdi_unshareddirectory cwaitcursor curwait badd addshareddirectory pdir m_strfullpath bsubdirectories removeshareddirectory pdir m_strfullpath bsubdirectories filesystemtreesetsharestate pdir badd bsubdirectories filesystemtreeupdateboldstate filtertreereloadtree theprefs shareddir_list removeall m_strlishareddirs getheadposition cstring strpath m_strlishareddirs getnext strpath strpath _t theprefs shareddir_list addtail strpath theapp theprefs void c shared dirs tree ctrl reload bool b force bool b changed false if b force check for changes in shared dirs if the prefs shareddir list get count m strlishareddirs get count position pos m strlishareddirs get head position position pos2 the prefs shareddir list get head position while pos null pos2 null c string str1 m strlishareddirs get next pos c string str2 the prefs shareddir list get next pos2 if str1 right 1 str1 str1 left str1 get length 1 if str2 right 1 str2 str2 left str2 get length 1 if str1 compare no case str2 0 b changed true break else b changed true check for changes in categories incoming dirs c string str main inc dir the prefs get incoming dir if str main inc dir right 1 t str main inc dir str main inc dir left str main inc dir get length 1 c string list strli found for int i 0 i the prefs get cat count i category struct p cat struct the prefs get category i if p cat struct null c string str cat incoming path p cat struct incomingpath if str cat incoming path right 1 t str cat incoming path str cat incoming path left str cat incoming path get length 1 if str cat incoming path is empty str cat incoming path compare no case str main inc dir 0 strli found find str cat incoming path null position pos m strlicatincomingdirs find str cat incoming path if pos null strli found add tail str cat incoming path else b changed true break if strli found get count m strlicatincomingdirs get count b changed true if b changed b force fetch shared dirs list filter tree reload tree expand m prootunshareddirectries m htitem tve collapse collapsing is enough to sync for the filtetree as all items are recreated on every expanding cshareddirstreectrl bforce bchanged bforce theprefs shareddir_list getcount m_strlishareddirs getcount m_strlishareddirs getheadposition theprefs shareddir_list getheadposition cstring m_strlishareddirs getnext cstring theprefs shareddir_list getnext getlength getlength comparenocase bchanged bchanged cstring strmainincdir theprefs getincomingdir strmainincdir _t strmainincdir strmainincdir strmainincdir getlength cstringlist strlifound theprefs getcatcount category_struct pcatstruct theprefs getcategory pcatstruct cstring strcatincomingpath pcatstruct strcatincomingpath _t strcatincomingpath strcatincomingpath strcatincomingpath getlength strcatincomingpath isempty strcatincomingpath comparenocase strmainincdir strlifound strcatincomingpath m_strlicatincomingdirs strcatincomingpath strlifound addtail strcatincomingpath bchanged strlifound getcount m_strlicatincomingdirs getcount bchanged bchanged bforce fetchshareddirslist filtertreereloadtree m_prootunshareddirectries m_htitem tve_collapse bool c shared dirs tree ctrl on command wparam w param lparam l param c typed ptr list c ptr list c known file selected list int i selected items m psharedfilesctrl get item count for int i 0 i i selected items i selected list add tail c known file m psharedfilesctrl get item data i c directory item p selected dir get selected filter folder based if p selected dir null switch w param case mp openfolder if p selected dir p selected dir m eitemtype sdi no shell execute null t open p selected dir m strfullpath null null sw show break case mp sharedir edit shared directories p selected dir true false break case mp sharedirsub edit shared directories p selected dir true true break case mp unsharedir edit shared directories p selected dir false false break case mp unsharedirsub edit shared directories p selected dir false true break file based if selected list get count 0 p selected dir null c known file file null if selected list get count 1 file selected list get head switch w param case mp geted2klink c string str position pos selected list get head position while pos null file selected list get next pos if str is empty str t r n str createed2k link file the app copy text to clipboard str break file operations case mp remove case mpg delete if idno afx message box get res string ids confirm filedelete mb iconwarning mb iconquestion mb defbutton2 mb yesno return true m psharedfilesctrl set redraw false bool b removed items false while selected list is empty c known file myfile selected list remove head if myfile myfile is part file continue bool delsucc false if path file exists myfile get file path delsucc true else delete if the prefs get remove to bin delsucc delete file myfile get file path else delete to recycle bin tchar todel max path 1 memset todel 0 sizeof todel tcsncpy todel myfile get file path arrsize todel 2 shfileopstruct fp 0 fp w func fo delete fp hwnd the app emuledlg m hwnd fp p from todel fp f flags fof allowundo fof noconfirmation fof silent fof noerrorui delsucc sh file operation fp 0 if delsucc the app sharedfiles remove file myfile b removed items true if myfile is kind of runtime class c part file the app emuledlg transferwnd downloadlistctrl clear completed static cast c part file myfile else c string str error str error format get res string ids err delfile t r n r n s myfile get file path get error message get last error afx message box str error m psharedfilesctrl set redraw true if b removed items m psharedfilesctrl auto select item break case mp cmt show file dialog selected list idd comment break case mp detail case mpg altenter show file dialog selected list break case mp showed2klink show file dialog selected list idd ed2klink break case mp prioverylow case mp priolow case mp prionormal case mp priohigh case mp prioveryhigh case mp prioauto position pos selected list get head position while pos null c known file file selected list get next pos switch w param case mp prioverylow file set auto up priority false file set up priority pr verylow m psharedfilesctrl update file file break case mp priolow file set auto up priority false file set up priority pr low m psharedfilesctrl update file file break case mp prionormal file set auto up priority false file set up priority pr normal m psharedfilesctrl update file file break case mp priohigh file set auto up priority false file set up priority pr high m psharedfilesctrl update file file break case mp prioveryhigh file set auto up priority false file set up priority pr veryhigh m psharedfilesctrl update file file break case mp prioauto file set auto up priority true file update auto up priority m psharedfilesctrl update file file break break default if w param mp weburl w param mp weburl 256 the web services runurl file w param break return true cshareddirstreectrl oncommand wparam lparam ctypedptrlist cptrlist cknownfile selectedlist iselecteditems m_psharedfilesctrl getitemcount iselecteditems selectedlist addtail cknownfile m_psharedfilesctrl getitemdata cdirectoryitem pselecteddir getselectedfilter pselecteddir wparam mp_openfolder pselecteddir pselecteddir m_eitemtype sdi_no shellexecute _t pselecteddir m_strfullpath sw_show mp_sharedir editshareddirectories pselecteddir mp_sharedirsub editshareddirectories pselecteddir mp_unsharedir editshareddirectories pselecteddir mp_unsharedirsub editshareddirectories pselecteddir selectedlist getcount pselecteddir cknownfile selectedlist getcount selectedlist gethead wparam mp_geted2klink cstring selectedlist getheadposition selectedlist getnext isempty _t createed2klink theapp copytexttoclipboard mp_remove mpg_delete afxmessagebox getresstring ids_confirm_filedelete mb_iconwarning mb_iconquestion mb_defbutton2 mb_yesno m_psharedfilesctrl setredraw bremoveditems selectedlist isempty cknownfile selectedlist removehead ispartfile pathfileexists getfilepath theprefs getremovetobin deletefile getfilepath max_path _tcsncpy getfilepath wfunc fo_delete theapp m_hwnd pfrom fflags fof_allowundo fof_noconfirmation fof_silent fof_noerrorui shfileoperation theapp removefile bremoveditems iskindof runtime_class cpartfile theapp clearcompleted static_cast cpartfile cstring strerror strerror getresstring ids_err_delfile _t getfilepath geterrormessage getlasterror afxmessagebox strerror m_psharedfilesctrl setredraw bremoveditems m_psharedfilesctrl autoselectitem mp_cmt showfiledialog selectedlist idd_comment mp_detail mpg_altenter showfiledialog selectedlist mp_showed2klink showfiledialog selectedlist idd_ed2klink mp_prioverylow mp_priolow mp_prionormal mp_priohigh mp_prioveryhigh mp_prioauto selectedlist getheadposition cknownfile selectedlist getnext wparam mp_prioverylow setautouppriority setuppriority pr_verylow m_psharedfilesctrl updatefile mp_priolow setautouppriority setuppriority pr_low m_psharedfilesctrl updatefile mp_prionormal setautouppriority setuppriority pr_normal m_psharedfilesctrl updatefile mp_priohigh setautouppriority setuppriority pr_high m_psharedfilesctrl updatefile mp_prioveryhigh setautouppriority setuppriority pr_veryhigh m_psharedfilesctrl updatefile mp_prioauto setautouppriority updateautouppriority m_psharedfilesctrl updatefile wparam mp_weburl wparam mp_weburl thewebservices wparam void c shared dirs tree ctrl create menues if m priomenu verify m priomenu destroy menu if m sharedfilesmenu verify m sharedfilesmenu destroy menu if m sharedirsmenu verify m sharedirsmenu destroy menu m priomenu create menu m priomenu append menu mf string mp prioverylow get res string ids prioverylow m priomenu append menu mf string mp priolow get res string ids priolow m priomenu append menu mf string mp prionormal get res string ids prionormal m priomenu append menu mf string mp priohigh get res string ids priohigh m priomenu append menu mf string mp prioveryhigh get res string ids priorelease m priomenu append menu mf string mp prioauto get res string ids prioauto uap m sharedfilesmenu create popup menu m sharedfilesmenu add menu title get res string ids sharedfiles true m sharedfilesmenu append menu mf string mp openfolder get res string ids openfolder t openfolder m sharedfilesmenu append menu mf string mp remove get res string ids delete t delete m sharedfilesmenu append menu mf string mf separator m sharedfilesmenu append menu mf string mf popup uint ptr m priomenu m hmenu get res string ids priority t get res string ids pw con uplbl t t filepriority m sharedfilesmenu append menu mf string mf separator m sharedfilesmenu append menu mf string mp detail get res string ids showdetails t fileinfo m sharedfilesmenu append menu mf string mp cmt get res string ids cmt add t filecomments if the prefs get show copy ed2k link cmd m sharedfilesmenu append menu mf string mp geted2klink get res string ids dl link1 t ed2klink else m sharedfilesmenu append menu mf string mp showed2klink get res string ids dl showed2klink t ed2klink m sharedfilesmenu append menu mf string mf separator m sharedirsmenu create popup menu m sharedirsmenu add menu title get res string ids sharedfiles false m sharedirsmenu append menu mf string mp sharedir get res string ids sharedir m sharedirsmenu append menu mf string mp sharedirsub get res string ids sharedirsub m sharedirsmenu append menu mf string mf separator m sharedirsmenu append menu mf string mp unsharedir get res string ids unsharedir m sharedirsmenu append menu mf string mp unsharedirsub get res string ids unsharedirsub cshareddirstreectrl createmenues m_priomenu m_priomenu destroymenu m_sharedfilesmenu m_sharedfilesmenu destroymenu m_sharedirsmenu m_sharedirsmenu destroymenu m_priomenu createmenu m_priomenu appendmenu mf_string mp_prioverylow getresstring ids_prioverylow m_priomenu appendmenu mf_string mp_priolow getresstring ids_priolow m_priomenu appendmenu mf_string mp_prionormal getresstring ids_prionormal m_priomenu appendmenu mf_string mp_priohigh getresstring ids_priohigh m_priomenu appendmenu mf_string mp_prioveryhigh getresstring ids_priorelease m_priomenu appendmenu mf_string mp_prioauto getresstring ids_prioauto m_sharedfilesmenu createpopupmenu m_sharedfilesmenu addmenutitle getresstring ids_sharedfiles m_sharedfilesmenu appendmenu mf_string mp_openfolder getresstring ids_openfolder _t m_sharedfilesmenu appendmenu mf_string mp_remove getresstring ids_delete _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedfilesmenu appendmenu mf_string mf_popup uint_ptr m_priomenu m_hmenu getresstring ids_priority _t getresstring ids_pw_con_uplbl _t _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedfilesmenu appendmenu mf_string mp_detail getresstring ids_showdetails _t m_sharedfilesmenu appendmenu mf_string mp_cmt getresstring ids_cmt_add _t theprefs getshowcopyed2klinkcmd m_sharedfilesmenu appendmenu mf_string mp_geted2klink getresstring ids_dl_link1 _t m_sharedfilesmenu appendmenu mf_string mp_showed2klink getresstring ids_dl_showed2klink _t m_sharedfilesmenu appendmenu mf_string mf_separator m_sharedirsmenu createpopupmenu m_sharedirsmenu addmenutitle getresstring ids_sharedfiles m_sharedirsmenu appendmenu mf_string mp_sharedir getresstring ids_sharedir m_sharedirsmenu appendmenu mf_string mp_sharedirsub getresstring ids_sharedirsub m_sharedirsmenu appendmenu mf_string mf_separator m_sharedirsmenu appendmenu mf_string mp_unsharedir getresstring ids_unsharedir m_sharedirsmenu appendmenu mf_string mp_unsharedirsub getresstring ids_unsharedirsub void c shared dirs tree ctrl show file dialog c typed ptr list c ptr list c known file a files uint u psh invoke page m psharedfilesctrl show file dialog a files u psh invoke page cshareddirstreectrl showfiledialog ctypedptrlist cptrlist cknownfile afiles upshinvokepage m_psharedfilesctrl showfiledialog afiles upshinvokepage void c shared dirs tree ctrl delete child items c directory item p parent while p parent li sub directories is empty c directory item p to delete p parent li sub directories remove head delete item p to delete m htitem delete child items p to delete delete p to delete cshareddirstreectrl deletechilditems cdirectoryitem pparent pparent lisubdirectories isempty cdirectoryitem ptodelete pparent lisubdirectories removehead deleteitem ptodelete m_htitem deletechilditems ptodelete ptodelete void c shared dirs tree ctrl add shared directory c string str dir bool b sub directories if file system tree is shared str dir m strlishareddirs add tail str dir if b sub directories if str dir right 1 t str dir t c file find finder bool b working finder find file str dir t while b working b working finder find next file if finder is dots finder is system finder is directory continue add shared directory str dir finder get file name true finder close cshareddirstreectrl addshareddirectory cstring strdir bsubdirectories filesystemtreeisshared strdir m_strlishareddirs addtail strdir bsubdirectories strdir _t strdir _t cfilefind bworking findfile strdir _t bworking bworking findnextfile isdots issystem isdirectory addshareddirectory strdir getfilename void c shared dirs tree ctrl remove shared directory c string str dir bool b sub directories if str dir right 1 str dir str dir left str dir get length 1 str dir make lower position pos1 pos2 for pos1 m strlishareddirs get head position pos2 pos1 null m strlishareddirs get next pos1 c string str m strlishareddirs get at pos2 str make lower if str compare no case str dir 0 m strlishareddirs remove at pos2 else if b sub directories str find str dir 0 m strlishareddirs remove at pos2 cshareddirstreectrl removeshareddirectory cstring strdir bsubdirectories strdir strdir strdir strdir getlength strdir makelower m_strlishareddirs getheadposition m_strlishareddirs getnext cstring m_strlishareddirs getat makelower comparenocase strdir m_strlishareddirs removeat bsubdirectories strdir m_strlishareddirs removeat int c shared dirs tree ctrl add system icon hicon h icon int n system list pos int n pos 0 if m mapsystemicons lookup n system list pos n pos n pos get image list tvsil normal add h icon m mapsystemicons set at n system list pos n pos return n pos cshareddirstreectrl addsystemicon hicon nsystemlistpos npos m_mapsystemicons nsystemlistpos npos npos getimagelist tvsil_normal hicon m_mapsystemicons setat nsystemlistpos npos npos void c shared dirs tree ctrl fetch shared dirs list m strlishareddirs remove all position pos the prefs shareddir list get head position copy list while pos c string str path the prefs shareddir list get next pos if str path right 1 str path str path left str path get length 1 m strlishareddirs add tail str path cshareddirstreectrl fetchshareddirslist m_strlishareddirs removeall theprefs shareddir_list getheadposition cstring strpath theprefs shareddir_list getnext strpath strpath strpath strpath getlength m_strlishareddirs addtail strpath void c shared dirs tree ctrl on sys color change c tree ctrl on sys color change set all icons create menues cshareddirstreectrl onsyscolorchange ctreectrl onsyscolorchange setallicons createmenues c directory item p selected dir get selected filter if p selected dir null p selected dir m eitemtype sdi unshareddirectory p selected dir m eitemtype sdi filesystemparent int i selected items m psharedfilesctrl get item count int i complete file selected 1 uint u prio menu item 0 bool b first item true for int i 0 i i selected items i const c known file p file c known file m psharedfilesctrl get item data i int i cur complete file p file is part file 0 1 if b first item i complete file selected i cur complete file else if i complete file selected i cur complete file i complete file selected 1 uint u cur prio menu item 0 if p file is auto up priority u cur prio menu item mp prioauto else if p file get up priority pr verylow u cur prio menu item mp prioverylow else if p file get up priority pr low u cur prio menu item mp priolow else if p file get up priority pr normal u cur prio menu item mp prionormal else if p file get up priority pr high u cur prio menu item mp priohigh else if p file get up priority pr veryhigh u cur prio menu item mp prioveryhigh else assert 0 if b first item u prio menu item u cur prio menu item else if u prio menu item u cur prio menu item u prio menu item 0 b first item false bool b wide range selection true if p selected dir m ncatfilter 1 p selected dir m eitemtype sdi no just avoid that users get bad ideas by showing the comment delete option for the all selections as the same comment for all files all incimplete files etc is probably not too usefull even if it can be done in other ways if the user really wants to do it b wide range selection false m sharedfilesmenu enable menu item uint ptr m priomenu m hmenu i selected items 0 mf enabled mf grayed m priomenu check menu radio item mp prioverylow mp prioauto u prio menu item 0 m sharedfilesmenu enable menu item mp openfolder p selected dir null p selected dir m eitemtype sdi no mf enabled mf grayed m sharedfilesmenu enable menu item mp remove i complete file selected 0 b wide range selection mf enabled mf grayed m sharedfilesmenu enable menu item mp cmt i selected items 0 b wide range selection mf enabled mf grayed m sharedfilesmenu enable menu item mp detail i selected items 0 mf enabled mf grayed m sharedfilesmenu enable menu item the prefs get show copy ed2k link cmd mp geted2klink mp showed2klink i selected items 0 mf enabled mf grayed c title menu web menu web menu create menu web menu add menu title null true int i web menu entries the web services get file menu entries web menu uint flag2 i web menu entries 0 i selected items 1 mf grayed mf string m sharedfilesmenu append menu flag2 mf popup uint ptr web menu m hmenu get res string ids webservices t web get popup menu pos this point m sharedfilesmenu track popup menu tpm leftalign tpm rightbutton point x point y this m sharedfilesmenu remove menu m sharedfilesmenu get menu item count 1 mf byposition verify web menu destroy menu cdirectoryitem pselecteddir getselectedfilter pselecteddir pselecteddir m_eitemtype sdi_unshareddirectory pselecteddir m_eitemtype sdi_filesystemparent iselecteditems m_psharedfilesctrl getitemcount icompletefileselected upriomenuitem bfirstitem iselecteditems cknownfile pfile cknownfile m_psharedfilesctrl getitemdata icurcompletefile pfile ispartfile bfirstitem icompletefileselected icurcompletefile icompletefileselected icurcompletefile icompletefileselected ucurpriomenuitem pfile isautouppriority ucurpriomenuitem mp_prioauto pfile getuppriority pr_verylow ucurpriomenuitem mp_prioverylow pfile getuppriority pr_low ucurpriomenuitem mp_priolow pfile getuppriority pr_normal ucurpriomenuitem mp_prionormal pfile getuppriority pr_high ucurpriomenuitem mp_priohigh pfile getuppriority pr_veryhigh ucurpriomenuitem mp_prioveryhigh bfirstitem upriomenuitem ucurpriomenuitem upriomenuitem ucurpriomenuitem upriomenuitem bfirstitem bwiderangeselection pselecteddir m_ncatfilter pselecteddir m_eitemtype sdi_no bwiderangeselection m_sharedfilesmenu enablemenuitem uint_ptr m_priomenu m_hmenu iselecteditems mf_enabled mf_grayed m_priomenu checkmenuradioitem mp_prioverylow mp_prioauto upriomenuitem m_sharedfilesmenu enablemenuitem mp_openfolder pselecteddir pselecteddir m_eitemtype sdi_no mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_remove icompletefileselected bwiderangeselection mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_cmt iselecteditems bwiderangeselection mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem mp_detail iselecteditems mf_enabled mf_grayed m_sharedfilesmenu enablemenuitem theprefs getshowcopyed2klinkcmd mp_geted2klink mp_showed2klink iselecteditems mf_enabled mf_grayed ctitlemenu webmenu webmenu createmenu webmenu addmenutitle iwebmenuentries thewebservices getfilemenuentries webmenu iwebmenuentries iselecteditems mf_grayed mf_string m_sharedfilesmenu appendmenu mf_popup uint_ptr webmenu m_hmenu getresstring ids_webservices _t getpopupmenupos m_sharedfilesmenu trackpopupmenu tpm_leftalign tpm_rightbutton m_sharedfilesmenu removemenu m_sharedfilesmenu getmenuitemcount mf_byposition webmenu destroymenu void c shared dirs tree ctrl onr button down uint n flags c point point uint u hit flags htreeitem h item hit test point u hit flags if h item null u hit flags tvht onitem select h item tvgn caret set item state h item tvis selected tvis selected return cshareddirstreectrl onrbuttondown nflags cpoint uhitflags hitem hittest uhitflags hitem uhitflags tvht_onitem hitem tvgn_caret setitemstate hitem tvis_selected tvis_selected void c shared dirs tree ctrl onl button up uint n flags c point point if m pdraggingitem null c point pt pt point client to screen pt tvhittestinfo tvhti tvhti pt pt screen to client tvhti pt htreeitem h item sel hit test tvhti c directory item p drag target if h item sel null p drag target c directory item get item data h item sel null only allow dragging to shared folders if p drag target m eitemtype sdi directory p drag target m eitemtype sdi no c directory item p real drag item htreeitem ht real m prootunshareddirectries find item m pdraggingitem get the original drag src if ht real null p real drag item c directory item get item data ht real null edit shared directories p real drag item true false else item was deleted no problem as when we dont need to update the visible part we can just as well use the contentcopy edit shared directories m pdraggingitem true false c image list drag leave null c image list end drag release capture show cursor true select drop target null delete m pdraggingitem m pdraggingitem null redraw window c tree ctrl onl button up n flags point cshareddirstreectrl onlbuttonup nflags cpoint m_pdraggingitem cpoint clienttoscreen screentoclient hitemsel hittest cdirectoryitem pdragtarget hitemsel pdragtarget cdirectoryitem getitemdata hitemsel pdragtarget m_eitemtype sdi_directory pdragtarget m_eitemtype sdi_no cdirectoryitem prealdragitem htreal m_prootunshareddirectries finditem m_pdraggingitem htreal prealdragitem cdirectoryitem getitemdata htreal editshareddirectories prealdragitem editshareddirectories m_pdraggingitem cimagelist dragleave cimagelist enddrag releasecapture showcursor selectdroptarget m_pdraggingitem m_pdraggingitem redrawwindow ctreectrl onlbuttonup nflags void c shared dirs tree ctrl on tvn itemexpanding nmhdr pnmhdr lresult p result c wait cursor cur wait set redraw false lpnmtreeview pnm tree view reinterpret cast lpnmtreeview pnmhdr c directory item p expanded c directory item pnm tree view item new l param if p expanded null if p expanded m eitemtype sdi unshareddirectory p expanded m strfullpath is empty remove all subitems delete child items p expanded fetch all subdirectories and add them to the node file system tree add subdirectories p expanded else if p expanded m eitemtype sdi filesystemparent delete child items p expanded file system tree create tree else assert false set redraw true invalidate p result 0 cshareddirstreectrl ontvnitemexpanding presult cwaitcursor curwait setredraw pnmtreeview reinterpret_cast cdirectoryitem pexpanded cdirectoryitem pnmtreeview itemnew lparam pexpanded pexpanded m_eitemtype sdi_unshareddirectory pexpanded m_strfullpath isempty deletechilditems pexpanded filesystemtreeaddsubdirectories pexpanded pexpanded m_eitemtype sdi_filesystemparent deletechilditems pexpanded filesystemtreecreatetree setredraw presult void c shared dirs tree ctrl on tvn getdispinfo nmhdr pnmhdr lresult p result lpnmtvdispinfo ptv disp info reinterpret cast lpnmtvdispinfo pnmhdr ptv disp info item c children 1 p result 0 cshareddirstreectrl ontvngetdispinfo presult ptvdispinfo reinterpret_cast ptvdispinfo cchildren presult void c shared dirs tree ctrl on lvn begindrag nmhdr pnmhdr lresult p result lpnmtreeview lpnmtv lpnmtreeview pnmhdr p result 0 c directory item p to drag c directory item lpnmtv item new l param if p to drag null p to drag m eitemtype sdi unshareddirectory file system tree is shared p to drag m strfullpath return assert m pdraggingitem null delete m pdraggingitem m pdraggingitem p to drag clone content to be safe we store a copy as items can be deleted when collapsing the tree etc c image list piml null point pt offset rect rc item if piml create drag image lpnmtv item new h item null return get the bounding rectangle of the item being dragged rel to top left of control if get item rect lpnmtv item new h item rc item true c point pt drag begin int nx ny get offset into image that the mouse is at item rect doesn t include the image pt drag begin lpnmtv pt drag imagelist geticonsize piml get safe handle nx ny pt offset x pt drag begin x rc item left nx rc item right rc item left pt offset y pt drag begin y rc item top ny rc item bottom rc item top convert the item rect to screen co ords for use later map window points null rc item else get window rect rc item pt offset x pt offset y 8 if piml begin drag 0 pt offset c point pt drag enter lpnmtv pt drag client to screen pt drag enter piml drag enter null pt drag enter delete piml set the focus here so we get a wm cancelmode if needed set focus redraw item being dragged otherwise it remains looking selected invalidate rect rc item true update window hide the mouse cursor and direct mouse input to this window set capture cshareddirstreectrl onlvnbegindrag presult presult cdirectoryitem ptodrag cdirectoryitem itemnew lparam ptodrag ptodrag m_eitemtype sdi_unshareddirectory filesystemtreeisshared ptodrag m_strfullpath m_pdraggingitem m_pdraggingitem m_pdraggingitem ptodrag clonecontent cimagelist ptoffset rcitem createdragimage itemnew hitem getitemrect itemnew hitem rcitem cpoint ptdragbegin ptdragbegin ptdrag imagelist_geticonsize getsafehandle ptoffset ptdragbegin rcitem rcitem rcitem ptoffset ptdragbegin rcitem rcitem rcitem mapwindowpoints rcitem getwindowrect rcitem ptoffset ptoffset begindrag ptoffset cpoint ptdragenter ptdrag clienttoscreen ptdragenter dragenter ptdragenter wm_cancelmode setfocus invalidaterect rcitem updatewindow setcapture void c shared dirs tree ctrl on mouse move uint n flags c point point if m pdraggingitem null c point pt drag the item to the current position pt point client to screen pt c image list drag move pt c image list drag show nolock false if c wnd window from point pt this set cursor afx get app load standard cursor idc no else tvhittestinfo tvhti tvhti pt pt screen to client tvhti pt htreeitem h item sel hit test tvhti c directory item p drag target if h item sel null p drag target c directory item get item data h item sel null only allow dragging to shared folders if p drag target m eitemtype sdi directory p drag target m eitemtype sdi no set cursor afx get app load standard cursor idc arrow select drop target p drag target m htitem else set cursor afx get app load standard cursor idc no else set cursor afx get app load standard cursor idc no c image list drag show nolock true c tree ctrl on mouse move n flags point cshareddirstreectrl onmousemove nflags cpoint m_pdraggingitem cpoint clienttoscreen cimagelist dragmove cimagelist dragshownolock cwnd windowfrompoint setcursor afxgetapp loadstandardcursor idc_no screentoclient hitemsel hittest cdirectoryitem pdragtarget hitemsel pdragtarget cdirectoryitem getitemdata hitemsel pdragtarget m_eitemtype sdi_directory pdragtarget m_eitemtype sdi_no setcursor afxgetapp loadstandardcursor idc_arrow selectdroptarget pdragtarget m_htitem setcursor afxgetapp loadstandardcursor idc_no setcursor afxgetapp loadstandardcursor idc_no cimagelist dragshownolock ctreectrl onmousemove nflags void c shared dirs tree ctrl on cancel mode if m pdraggingitem null c image list drag leave null c image list end drag release capture show cursor true select drop target null delete m pdraggingitem m pdraggingitem null redraw window c tree ctrl on cancel mode cshareddirstreectrl oncancelmode m_pdraggingitem cimagelist dragleave cimagelist enddrag releasecapture showcursor selectdroptarget m_pdraggingitem m_pdraggingitem redrawwindow ctreectrl oncancelmode void c shared dirs tree ctrl initalize standard items add standard items delete all items delete m prootdirectoryitem delete m prootunshareddirectries fetch shared dirs list m prootdirectoryitem new c directory item c string tvi root c directory item p all new c directory item c string 0 sdi all p all m htitem insert item tvif text tvif param tvif image tvif selectedimage get res string ids allsharedfiles 0 0 0 0 lparam p all tvi root tvi last m prootdirectoryitem li sub directories add tail p all c directory item p incoming new c directory item c string tvi root sdi incoming p incoming m htitem insert item tvif text tvif param tvif image tvif selectedimage get res string ids incoming files 2 2 0 0 lparam p incoming tvi root tvi last m prootdirectoryitem li sub directories add tail p incoming c directory item p temp new c directory item c string tvi root sdi temp p temp m htitem insert item tvif text tvif param tvif image tvif selectedimage get res string ids incomplete files 1 1 0 0 lparam p temp tvi root tvi last m prootdirectoryitem li sub directories add tail p temp c directory item p dir new c directory item c string tvi root sdi directory p dir m htitem insert item tvif text tvif param tvif image tvif selectedimage tvif state get res string ids shared directories 5 5 tvis expanded tvis expanded lparam p dir tvi root tvi last m prootdirectoryitem li sub directories add tail p dir m prootunshareddirectries new c directory item c string tvi root sdi filesystemparent m prootunshareddirectries m htitem insert item tvif text tvif param tvif image tvif selectedimage tvif children get res string ids alldirectories 4 4 0 0 lparam m prootunshareddirectries tvi root tvi last cshareddirstreectrl initalizestandarditems deleteallitems m_prootdirectoryitem m_prootunshareddirectries fetchshareddirslist m_prootdirectoryitem cdirectoryitem cstring tvi_root cdirectoryitem pall cdirectoryitem cstring sdi_all pall m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage getresstring ids_allsharedfiles pall tvi_root tvi_last m_prootdirectoryitem lisubdirectories addtail pall cdirectoryitem pincoming cdirectoryitem cstring tvi_root sdi_incoming pincoming m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage getresstring ids_incoming_files pincoming tvi_root tvi_last m_prootdirectoryitem lisubdirectories addtail pincoming cdirectoryitem ptemp cdirectoryitem cstring tvi_root sdi_temp ptemp m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage getresstring ids_incomplete_files ptemp tvi_root tvi_last m_prootdirectoryitem lisubdirectories addtail ptemp cdirectoryitem pdir cdirectoryitem cstring tvi_root sdi_directory pdir m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage tvif_state getresstring ids_shared_directories tvis_expanded tvis_expanded pdir tvi_root tvi_last m_prootdirectoryitem lisubdirectories addtail pdir m_prootunshareddirectries cdirectoryitem cstring tvi_root sdi_filesystemparent m_prootunshareddirectries m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage tvif_children getresstring ids_alldirectories m_prootunshareddirectries tvi_root tvi_last void c shared dirs tree ctrl file system tree create tree tchar drivebuffer 500 get logical drive strings arrsize drivebuffer drivebuffer e g a c d const tchar pos drivebuffer while pos t 0 copy drive name tchar drive 4 tcsncpy drive pos arrsize drive drive arrsize drive 1 t 0 switch drive 0 case t a case t a case t b case t b skip floppy disk break default drive 2 t 0 file system tree add child item m prootunshareddirectries drive true e g c point to the next drive 4 chars interval pos pos 4 cshareddirstreectrl filesystemtreecreatetree getlogicaldrivestrings _t _tcsncpy _t _t _t _t _t _t filesystemtreeaddchilditem m_prootunshareddirectries void c shared dirs tree ctrl file system tree add child item c directory item p root c string str text bool b top level c string str path p root m strfullpath if str path right 1 t str path is empty str path t c string str dir str path str text tv insertstruct it insert memset it insert 0 sizeof it insert if m buseicons it insert item mask tvif children tvif handle tvif text tvif state tvif image tvif selectedimage it insert item state mask tvis bold tvis stateimagemask else it insert item mask tvif children tvif handle tvif text tvif state it insert item state mask tvis bold if file system tree has shared subdirectory str dir it insert item state tvis bold else it insert item state 0 if file system tree has subdirectories str dir it insert item c children i childrencallback used to display the symbol next to each item else it insert item c children 0 if str dir right 1 str dir str dir left str path get length 1 c directory item pti new c directory item str dir 0 sdi unshareddirectory it insert item psz text const cast lptstr lpctstr str text it insert h insert after b top level tvi sort tvi last it insert h parent p root m htitem it insert item mask tvif param it insert item l param lparam pti if m buseicons if file system tree is shared str dir it insert item state mask tvis overlaymask it insert item state indextooverlaymask 1 c string str temp str dir if str temp right 1 t str temp t uint n type get drive type str temp if drive removable n type n type drive ramdisk it insert item i image n type shfileinfo sh finfo sh finfo sz display name 0 t 0 if sh get file info str temp 0 sh finfo sizeof sh finfo shgfi icon shgfi smallicon shgfi displayname trace t error gettting system file info it insert itemex i image 0 else it insert itemex i image add system icon sh finfo h icon sh finfo i icon destroy icon sh finfo h icon if b top level sh finfo sz display name 0 t 0 str text sh finfo sz display name it insert item psz text const cast lptstr lpctstr str text if sh get file info str temp 0 sh finfo sizeof sh finfo shgfi icon shgfi openicon shgfi smallicon trace t error gettting system file info it insert itemex i image 0 else it insert itemex i selected image add system icon sh finfo h icon sh finfo i icon destroy icon sh finfo h icon pti m htitem insert item it insert p root li sub directories add tail pti str text release buffer cshareddirstreectrl filesystemtreeaddchilditem cdirectoryitem proot cstring strtext btoplevel cstring strpath proot m_strfullpath strpath _t strpath isempty strpath _t cstring strdir strpath strtext tv_insertstruct itinsert itinsert itinsert m_buseicons itinsert tvif_children tvif_handle tvif_text tvif_state tvif_image tvif_selectedimage itinsert statemask tvis_bold tvis_stateimagemask itinsert tvif_children tvif_handle tvif_text tvif_state itinsert statemask tvis_bold filesystemtreehassharedsubdirectory strdir itinsert tvis_bold itinsert filesystemtreehassubdirectories strdir itinsert cchildren i_childrencallback itinsert cchildren strdir strdir strdir strpath getlength cdirectoryitem cdirectoryitem strdir sdi_unshareddirectory itinsert psztext const_cast strtext itinsert hinsertafter btoplevel tvi_sort tvi_last itinsert hparent proot m_htitem itinsert tvif_param itinsert lparam m_buseicons filesystemtreeisshared strdir itinsert statemask tvis_overlaymask itinsert cstring strtemp strdir strtemp _t strtemp _t ntype getdrivetype strtemp drive_removable ntype ntype drive_ramdisk itinsert iimage ntype shfinfo shfinfo szdisplayname _t shgetfileinfo strtemp shfinfo shfinfo shgfi_icon shgfi_smallicon shgfi_displayname _t systemfileinfo itinsert iimage itinsert iimage addsystemicon shfinfo hicon shfinfo iicon destroyicon shfinfo hicon btoplevel shfinfo szdisplayname _t strtext shfinfo szdisplayname itinsert psztext const_cast strtext shgetfileinfo strtemp shfinfo shfinfo shgfi_icon shgfi_openicon shgfi_smallicon _t systemfileinfo itinsert iimage itinsert iselectedimage addsystemicon shfinfo hicon shfinfo iicon destroyicon shfinfo hicon m_htitem insertitem itinsert proot lisubdirectories addtail strtext releasebuffer bool c shared dirs tree ctrl file system tree has subdirectories c string str dir if str dir right 1 t str dir t c file find finder bool b working finder find file str dir t while b working b working finder find next file if finder is dots continue if finder is system continue if finder is directory continue finder close return true finder close return false cshareddirstreectrl filesystemtreehassubdirectories cstring strdir strdir _t strdir _t cfilefind bworking findfile strdir _t bworking bworking findnextfile isdots issystem isdirectory bool c shared dirs tree ctrl file system tree has shared subdirectory c string str dir if str dir right 1 t str dir t str dir make lower for position pos m strlishareddirs get head position pos null c string str current m strlishareddirs get next pos str current make lower if str current find str dir 0 str dir str current return true return false cshareddirstreectrl filesystemtreehassharedsubdirectory cstring strdir strdir _t strdir _t strdir makelower m_strlishareddirs getheadposition cstring strcurrent m_strlishareddirs getnext strcurrent makelower strcurrent strdir strdir strcurrent void c shared dirs tree ctrl file system tree add subdirectories c directory item p root c string str dir p root m strfullpath if str dir right 1 t str dir t c file find finder bool b working finder find file str dir t while b working b working finder find next file if finder is dots finder is system finder is directory continue c string str filename finder get file name if str filename reverse find t 1 str filename str filename mid str filename reverse find t 1 file system tree add child item p root str filename false finder close cshareddirstreectrl filesystemtreeaddsubdirectories cdirectoryitem proot cstring strdir proot m_strfullpath strdir _t strdir _t cfilefind bworking findfile strdir _t bworking bworking findnextfile isdots issystem isdirectory cstring strfilename getfilename strfilename reversefind _t strfilename strfilename strfilename reversefind _t filesystemtreeaddchilditem proot strfilename bool c shared dirs tree ctrl file system tree is shared c string str dir if str dir right 1 t str dir t for position pos m strlishareddirs get head position pos null c string str m strlishareddirs get next pos if str right 1 t str t if str compare no case str dir 0 return true return false cshareddirstreectrl filesystemtreeisshared cstring strdir strdir _t strdir _t m_strlishareddirs getheadposition cstring m_strlishareddirs getnext _t _t comparenocase strdir void c shared dirs tree ctrl file system tree update bold state c directory item p dir if p dir null p dir m prootunshareddirectries set item state p dir m htitem file system tree has shared subdirectory p dir m strfullpath tvis bold 0 tvis bold position pos p dir li sub directories get head position while pos null file system tree update bold state p dir li sub directories get next pos cshareddirstreectrl filesystemtreeupdateboldstate cdirectoryitem pdir pdir pdir m_prootunshareddirectries setitemstate pdir m_htitem filesystemtreehassharedsubdirectory pdir m_strfullpath tvis_bold tvis_bold pdir lisubdirectories getheadposition filesystemtreeupdateboldstate pdir lisubdirectories getnext void c shared dirs tree ctrl file system tree set share state c directory item p dir bool b shared bool b sub directories if m buseicons p dir m htitem null set item state p dir m htitem b shared indextooverlaymask 1 0 tvis overlaymask if b sub directories position pos p dir li sub directories get head position while pos null file system tree set share state p dir li sub directories get next pos b shared true cshareddirstreectrl filesystemtreesetsharestate cdirectoryitem pdir bshared bsubdirectories m_buseicons pdir m_htitem setitemstate pdir m_htitem bshared tvis_overlaymask bsubdirectories pdir lisubdirectories getheadposition filesystemtreesetsharestate pdir lisubdirectories getnext bshared void c shared dirs tree ctrl filter tree add sub directories c directory item p directory c string list li dirs int n level just some sanity check against too deep shared dirs shouldnt be needed but never trust the filesystem or a recursive function if n level 14 assert false return position pos li dirs get head position c string str directory path p directory m strfullpath str directory path make lower while pos c string str current the prefs shareddir list get next pos c string str current low str current str current low make lower if str directory path is empty str current low find str directory path t 0 0 str current low str directory path if filter tree is sub directory str current low str directory path li dirs c string str name str current if str name right 1 str name str name left str name get length 1 str name str name right str name get length str name reverse find 1 c directory item p new item new c directory item str current p new item m htitem insert item tvif text tvif param tvif image tvif selectedimage str name 5 5 0 0 lparam p new item p directory m htitem tvi last p directory li sub directories add tail p new item filter tree add sub directories p new item li dirs n level 1 cshareddirstreectrl filtertreeaddsubdirectories cdirectoryitem pdirectory cstringlist lidirs nlevel nlevel lidirs getheadposition cstring strdirectorypath pdirectory m_strfullpath strdirectorypath makelower cstring strcurrent theprefs shareddir_list getnext cstring strcurrentlow strcurrent strcurrentlow makelower strdirectorypath isempty strcurrentlow strdirectorypath _t strcurrentlow strdirectorypath filtertreeissubdirectory strcurrentlow strdirectorypath lidirs cstring strname strcurrent strname strname strname strname getlength strname strname strname getlength strname reversefind cdirectoryitem pnewitem cdirectoryitem strcurrent pnewitem m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage strname pnewitem pdirectory m_htitem tvi_last pdirectory lisubdirectories addtail pnewitem filtertreeaddsubdirectories pnewitem lidirs nlevel bool c shared dirs tree ctrl filter tree is sub directory c string str dir c string str root c string list li dirs position pos li dirs get head position str root make lower str dir make lower if str dir right 1 t str dir t if str root right 1 t str root t while pos c string str current the prefs shareddir list get next pos str current make lower if str current right 1 t str current t if str root find str current 0 0 str dir find str current 0 0 str current str root str current str dir return true return false cshareddirstreectrl filtertreeissubdirectory cstring strdir cstring strroot cstringlist lidirs lidirs getheadposition strroot makelower strdir makelower strdir _t strdir _t strroot _t strroot _t cstring strcurrent theprefs shareddir_list getnext strcurrent makelower strcurrent _t strcurrent _t strroot strcurrent strdir strcurrent strcurrent strroot strcurrent strdir void c shared dirs tree ctrl filter tree reload tree m bcreatingtree true store current selection c directory item p old selected item null if get selected filter null p old selected item get selected filter clone content create the tree substructure of directories we want to show position pos m prootdirectoryitem li sub directories get head position while pos null c directory item p current m prootdirectoryitem li sub directories get next pos clear old items delete child items p current switch p current m eitemtype case sdi all break case sdi incoming c string str main inc dir the prefs get incoming dir if str main inc dir right 1 str main inc dir str main inc dir left str main inc dir get length 1 if the prefs get cat count 1 m strlicatincomingdirs remove all for int i 0 i the prefs get cat count i category struct p cat struct the prefs get category i if p cat struct null c string str cat incoming path p cat struct incomingpath if str cat incoming path right 1 str cat incoming path str cat incoming path left str cat incoming path get length 1 if str cat incoming path is empty str cat incoming path compare no case str main inc dir 0 m strlicatincomingdirs find str cat incoming path null m strlicatincomingdirs add tail str cat incoming path c string str name str cat incoming path if str name right 1 str name str name left str name get length 1 str name str name right str name get length str name reverse find 1 c directory item p cat inc new c directory item str cat incoming path 0 sdi catincoming p cat inc m htitem insert item tvif text tvif param tvif image tvif selectedimage str name 5 5 0 0 lparam p cat inc p current m htitem tvi last p current li sub directories add tail p cat inc break case sdi temp if the prefs get cat count 1 for int i 0 i the prefs get cat count i category struct p cat struct the prefs get category i if p cat struct null temp dir c directory item p cat temp new c directory item c string 0 sdi temp i p cat temp m htitem insert item tvif text tvif param tvif image tvif selectedimage c string p cat struct title 3 3 0 0 lparam p cat temp p current m htitem tvi last p current li sub directories add tail p cat temp break case sdi directory add subdirectories filter tree add sub directories p current m strlishareddirs break default assert false restore selection htreeitem ht old section if p old selected item null ht old section m prootdirectoryitem find item p old selected item null select ht old section tvgn caret ensure visible ht old section else if get selected item null m prootdirectoryitem li sub directories is empty select m prootdirectoryitem li sub directories get head m htitem tvgn caret delete p old selected item m bcreatingtree false cshareddirstreectrl filtertreereloadtree m_bcreatingtree cdirectoryitem poldselecteditem getselectedfilter poldselecteditem getselectedfilter clonecontent m_prootdirectoryitem lisubdirectories getheadposition cdirectoryitem pcurrent m_prootdirectoryitem lisubdirectories getnext deletechilditems pcurrent pcurrent m_eitemtype sdi_all sdi_incoming cstring strmainincdir theprefs getincomingdir strmainincdir strmainincdir strmainincdir strmainincdir getlength theprefs getcatcount m_strlicatincomingdirs removeall theprefs getcatcount category_struct pcatstruct theprefs getcategory pcatstruct cstring strcatincomingpath pcatstruct strcatincomingpath strcatincomingpath strcatincomingpath strcatincomingpath getlength strcatincomingpath isempty strcatincomingpath comparenocase strmainincdir m_strlicatincomingdirs strcatincomingpath m_strlicatincomingdirs addtail strcatincomingpath cstring strname strcatincomingpath strname strname strname strname getlength strname strname strname getlength strname reversefind cdirectoryitem pcatinc cdirectoryitem strcatincomingpath sdi_catincoming pcatinc m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage strname pcatinc pcurrent m_htitem tvi_last pcurrent lisubdirectories addtail pcatinc sdi_temp theprefs getcatcount theprefs getcatcount category_struct pcatstruct theprefs getcategory pcatstruct cdirectoryitem pcattemp cdirectoryitem cstring sdi_temp pcattemp m_htitem insertitem tvif_text tvif_param tvif_image tvif_selectedimage cstring pcatstruct pcattemp pcurrent m_htitem tvi_last pcurrent lisubdirectories addtail pcattemp sdi_directory filtertreeaddsubdirectories pcurrent m_strlishareddirs htoldsection poldselecteditem htoldsection m_prootdirectoryitem finditem poldselecteditem htoldsection tvgn_caret ensurevisible htoldsection getselecteditem m_prootdirectoryitem lisubdirectories isempty m_prootdirectoryitem lisubdirectories gethead m_htitem tvgn_caret poldselecteditem m_bcreatingtree virtual bool putc unsigned char c default implementation size t n wrote write c 1 1 return bool n wrote 1 size_t nwrote nwrote virtual bool putc unsigned char c default implementation size t n wrote write c 1 1 return bool n wrote 1 size_t nwrote nwrote cxio file file fp null m fp fp m bclosefile bool fp 0 cxiofile m_fp m_bclosefile cxio file close cxiofile bool open const char filename const char mode if m fp return false can t re open without closing first m fp fopen filename mode if m fp return false m bclosefile true return true m_fp m_fp m_fp m_bclosefile virtual bool close int i err 0 if m fp m bclosefile i err fclose m fp m fp null return bool i err 0 ierr m_fp m_bclosefile ierr m_fp m_fp ierr virtual size t read void buffer size t size size t count if m fp return 0 return fread buffer size count m fp size_t size_t size_t m_fp m_fp virtual size t write const void buffer size t size size t count if m fp return 0 return fwrite buffer size count m fp size_t size_t size_t m_fp m_fp virtual bool seek long offset int origin if m fp return false return bool fseek m fp offset origin 0 m_fp m_fp virtual long tell if m fp return 0 return ftell m fp m_fp m_fp virtual long size if m fp return 1 long pos size pos ftell m fp fseek m fp 0 seek end size ftell m fp fseek m fp pos seek set return size m_fp m_fp m_fp seek_end m_fp m_fp seek_set virtual bool flush if m fp return false return bool fflush m fp 0 m_fp m_fp virtual bool eof if m fp return true return bool feof m fp 0 m_fp m_fp virtual long error if m fp return 1 return ferror m fp m_fp m_fp virtual bool putc unsigned char c if m fp return false return bool fputc c m fp c m_fp m_fp virtual long getc if m fp return eof return getc m fp m_fp m_fp cxio file file fp null m fp fp m bclosefile bool fp 0 cxiofile m_fp m_bclosefile cxio file close cxiofile bool open const char filename const char mode if m fp return false can t re open without closing first m fp fopen filename mode if m fp return false m bclosefile true return true m_fp m_fp m_fp m_bclosefile virtual bool close int i err 0 if m fp m bclosefile i err fclose m fp m fp null return bool i err 0 ierr m_fp m_bclosefile ierr m_fp m_fp ierr virtual size t read void buffer size t size size t count if m fp return 0 return fread buffer size count m fp size_t size_t size_t m_fp m_fp virtual size t write const void buffer size t size size t count if m fp return 0 return fwrite buffer size count m fp size_t size_t size_t m_fp m_fp virtual bool seek long offset int origin if m fp return false return bool fseek m fp offset origin 0 m_fp m_fp virtual long tell if m fp return 0 return ftell m fp m_fp m_fp virtual long size if m fp return 1 long pos size pos ftell m fp fseek m fp 0 seek end size ftell m fp fseek m fp pos seek set return size m_fp m_fp m_fp seek_end m_fp m_fp seek_set virtual bool flush if m fp return false return bool fflush m fp 0 m_fp m_fp virtual bool eof if m fp return true return bool feof m fp 0 m_fp m_fp virtual long error if m fp return 1 return ferror m fp m_fp m_fp virtual bool putc unsigned char c if m fp return false return bool fputc c m fp c m_fp m_fp virtual long getc if m fp return eof return getc m fp m_fp m_fp cx mem file byte p buffer null dword size 0 m pbuffer p buffer m position 0 m size m edge size m bfreeonclose bool p buffer 0 cxmemfile pbuffer m_pbuffer pbuffer m_position m_size m_edge m_bfreeonclose pbuffer cx mem file close cxmemfile virtual bool close if m pbuffer m bfreeonclose free m pbuffer m pbuffer null m size 0 return true m_pbuffer m_bfreeonclose m_pbuffer m_pbuffer m_size bool open if m pbuffer return false can t re open without closing first m position m size m edge 0 m pbuffer byte malloc 0 m bfreeonclose true return m pbuffer 0 m_pbuffer m_position m_size m_edge m_pbuffer m_bfreeonclose m_pbuffer cx mem file byte p buffer null dword size 0 m pbuffer p buffer m position 0 m size m edge size m bfreeonclose bool p buffer 0 cxmemfile pbuffer m_pbuffer pbuffer m_position m_size m_edge m_bfreeonclose pbuffer cx mem file close cxmemfile virtual bool close if m pbuffer m bfreeonclose free m pbuffer m pbuffer null m size 0 return true m_pbuffer m_bfreeonclose m_pbuffer m_pbuffer m_size bool open if m pbuffer return false can t re open without closing first m position m size m edge 0 m pbuffer byte malloc 0 m bfreeonclose true return m pbuffer 0 m_pbuffer m_position m_size m_edge m_pbuffer m_bfreeonclose m_pbuffer size t cx mem file read void buffer size t size size t count if m pbuffer null return 0 if buffer null return 0 if m position long m size return 0 long n count count size if n count 0 return 0 long n read if m position n count long m size n read m size m position else n read n count memcpy buffer m pbuffer m position n read m position n read return size t n read size size_t cxmemfile size_t size_t m_pbuffer m_position m_size ncount ncount nread m_position ncount m_size nread m_size m_position nread ncount m_pbuffer m_position nread m_position nread size_t nread size t cx mem file write const void buffer size t size size t count if m pbuffer null return 0 if buffer null return 0 long n count count size if n count 0 return 0 if m position n count m edge alloc m position n count memcpy m pbuffer m position buffer n count m position n count if m position long m size m size m position return count size_t cxmemfile size_t size_t m_pbuffer ncount ncount m_position ncount m_edge m_position ncount m_pbuffer m_position ncount m_position ncount m_position m_size m_size m_position bool cx mem file seek long offset int origin if m pbuffer null return false long l new pos m position if origin seek set l new pos offset else if origin seek cur l new pos offset else if origin seek end l new pos m size offset else return false if l new pos 0 return false m position l new pos return true cxmemfile m_pbuffer lnewpos m_position seek_set lnewpos seek_cur lnewpos seek_end lnewpos m_size lnewpos m_position lnewpos long cx mem file tell if m pbuffer null return 1 return m position cxmemfile m_pbuffer m_position long cx mem file size if m pbuffer null return 1 return m size cxmemfile m_pbuffer m_size bool cx mem file flush if m pbuffer null return false return true cxmemfile m_pbuffer bool cx mem file eof if m pbuffer null return true return m position long m size cxmemfile m_pbuffer m_position m_size long cx mem file error if m pbuffer null return 1 return m position long m size cxmemfile m_pbuffer m_position m_size bool cx mem file putc unsigned char c if m pbuffer null return false if m position 1 m edge alloc m position 1 memcpy m pbuffer m position c 1 m position 1 if m position long m size m size m position return true cxmemfile m_pbuffer m_position m_edge m_position m_pbuffer m_position m_position m_position m_size m_size m_position long cx mem file getc if eof return eof return byte byte m pbuffer m position cxmemfile m_pbuffer m_position void cx mem file alloc dword dw new len if dw new len dword m edge determine new buffer size dword dw new buffer size dword m edge while dw new buffer size dw new len dw new buffer size 4096 allocate new buffer if m pbuffer null m pbuffer byte malloc dw new buffer size else m pbuffer byte realloc m pbuffer dw new buffer size i own this buffer now caller knows nothing about it m bfreeonclose true m edge dw new buffer size return cxmemfile dwnewlen dwnewlen m_edge dwnewbuffersize m_edge dwnewbuffersize dwnewlen dwnewbuffersize m_pbuffer m_pbuffer dwnewbuffersize m_pbuffer m_pbuffer dwnewbuffersize m_bfreeonclose m_edge dwnewbuffersize void cx mem file free close cxmemfile c time tick c time tick m ntimeelapsed quad part 0 m ntime quad part 0 ctimetick ctimetick m_ntimeelapsed quadpart m_ntime quadpart c time tick c time tick ctimetick ctimetick void c time tick start if m nperformancefrequency query performance counter m ntimeelapsed m ntime quad part 0 ctimetick m_nperformancefrequency queryperformancecounter m_ntimeelapsed m_ntime quadpart float c time tick tick large integer n time if m nperformancefrequency query performance counter n time float n tick time get time in milli seconds n time quad part m ntimeelapsed quad part m ntimeelapsed quad part n time quad part return n tick time return 0 0f ctimetick large_integer ntime m_nperformancefrequency queryperformancecounter ntime nticktime gettimeinmilliseconds ntime quadpart m_ntimeelapsed quadpart m_ntimeelapsed quadpart ntime quadpart nticktime int64 c time tick get performance frequency large integer n performance frequency if query performance frequency n performance frequency return n performance frequency quad part else return 0 __int64 ctimetick getperformancefrequency large_integer nperformancefrequency queryperformancefrequency nperformancefrequency nperformancefrequency quadpart float c time tick get time in milli seconds int64 n time return float n time 1000i64 float m nperformancefrequency ctimetick gettimeinmilliseconds __int64 ntime ntime m_nperformancefrequency void cemule dlg send notification mail int i msg type lpctstr psz text if the prefs is notifier send mail enabled return c string str host name the prefs get notifier mail server str host name trim if str host name is empty return c string str recipient the prefs get notifier mail receiver str recipient trim if str recipient is empty return c string str sender the prefs get notifier mail sender str sender trim if str sender is empty return c notifier mail thread p thread c notifier mail thread afx begin thread runtime class c notifier mail thread thread priority below normal 0 create suspended if p thread p thread m strhostname str host name p thread m strrecipient str recipient p thread m strsender str sender p thread m strencryptcertname the app get profile string t e mule t notifier mail encrypt cert name trim p thread m strsubject get res string ids emulenotification switch i msg type case tbn chat p thread m strsubject t get res string ids pw tbn pop always break case tbn downloadfinished p thread m strsubject t get res string ids pw tbn ondownload break case tbn downloadadded p thread m strsubject t get res string ids tbn onnewdownload break case tbn log p thread m strsubject t get res string ids pw tbn onlog break case tbn importantevent p thread m strsubject t get res string ids error break case tbn newversion p thread m strsubject t get res string ids cb tbn onnewversion break default assert 0 p thread m strbody psz text p thread resume thread cemuledlg sendnotificationmail imsgtype psztext theprefs isnotifiersendmailenabled cstring strhostname theprefs getnotifiermailserver strhostname strhostname isempty cstring strrecipient theprefs getnotifiermailreceiver strrecipient strrecipient isempty cstring strsender theprefs getnotifiermailsender strsender strsender isempty cnotifiermailthread pthread cnotifiermailthread afxbeginthread runtime_class cnotifiermailthread thread_priority_below_normal create_suspended pthread pthread m_strhostname strhostname pthread m_strrecipient strrecipient pthread m_strsender strsender pthread m_strencryptcertname theapp getprofilestring _t emule _t notifiermailencryptcertname pthread m_strsubject getresstring ids_emulenotification imsgtype tbn_chat pthread m_strsubject _t getresstring ids_pw_tbn_pop_always tbn_downloadfinished pthread m_strsubject _t getresstring ids_pw_tbn_ondownload tbn_downloadadded pthread m_strsubject _t getresstring ids_tbn_onnewdownload tbn_log pthread m_strsubject _t getresstring ids_pw_tbn_onlog tbn_importantevent pthread m_strsubject _t getresstring ids_error tbn_newversion pthread m_strsubject _t getresstring ids_cb_tbn_onnewversion pthread m_strbody psztext pthread resumethread c text to speech c text to speech assert m pispvoice null releasetts ctexttospeech ctexttospeech m_pispvoice bool c text to speech createtts bool b result false if m pispvoice null hresult hr if succeeded hr m pispvoice co create instance clsid spvoice m lttslangid makelangid lang neutral sublang neutral b result true return b result ctexttospeech bresult m_pispvoice m_pispvoice cocreateinstance clsid_spvoice m_lttslangid lang_neutral sublang_neutral bresult bresult void c text to speech releasetts m lttslangid makelangid lang neutral sublang neutral m pispvoice release ctexttospeech m_lttslangid lang_neutral sublang_neutral m_pispvoice bool c text to speech speak lpctstr pwsz bool b result false uses conversion if m pispvoice if succeeded m pispvoice speak t2cw pwsz spf async spf is not xml null b result true return b result ctexttospeech bresult uses_conversion m_pispvoice m_pispvoice spf_async spf_is_not_xml bresult bresult c taskbar notifier c taskbar notifier m strcaption m pwndparent null m bmouseisover false m hbitmapregion null m hcursor null m crnormaltextcolor rgb 133 146 181 m crselectedtextcolor rgb 10 36 106 m nbitmapheight 0 m nbitmapwidth 0 m dwtimetostay 0 m dwshowevents 0 m dwhideevents 0 m ncurrentposx 0 m ncurrentposy 0 m ncurrentwidth 0 m ncurrentheight 0 m nincrementshow 0 m nincrementhide 0 m dwtimetoshow 500 m dwtimetostay 4000 m dwtimetohide 200 m ntaskbarplacement abe bottom m nanimstatus idt hidden m rctext set rect 0 0 0 0 m rcclosebtn set rect 0 0 0 0 m utextformat dt modifystring dt wordbreak dt path ellipsis dt end ellipsis default text format see draw text in the win32 api for the different values m hcursor load cursor null makeintresource 32649 system hand cursor m nhistoryposition 0 m nactivemessagetype tbn null m btextselected false m bautoclose true if running on nt timer precision is 10 ms if not timer precision is 50 ms osversioninfo osvi osvi dwos version info size sizeof osversioninfo get version ex osvi if osvi dw platform id ver platform win32 nt m dwtimerprecision 10 else m dwtimerprecision 50 set text default font we use default gui font ctaskbarnotifier ctaskbarnotifier m_strcaption m_pwndparent m_bmouseisover m_hbitmapregion m_hcursor m_crnormaltextcolor m_crselectedtextcolor m_nbitmapheight m_nbitmapwidth m_dwtimetostay m_dwshowevents m_dwhideevents m_ncurrentposx m_ncurrentposy m_ncurrentwidth m_ncurrentheight m_nincrementshow m_nincrementhide m_dwtimetoshow m_dwtimetostay m_dwtimetohide m_ntaskbarplacement abe_bottom m_nanimstatus idt_hidden m_rctext setrect m_rcclosebtn setrect m_utextformat dt_modifystring dt_wordbreak dt_path_ellipsis dt_end_ellipsis drawtext m_hcursor loadcursor m_nhistoryposition m_nactivemessagetype tbn_null m_btextselected m_bautoclose dwosversioninfosize getversionex dwplatformid ver_platform_win32_nt m_dwtimerprecision m_dwtimerprecision settextdefaultfont c taskbar notifier c taskbar notifier while m messagehistory get count 0 c taskbar notifier history messageptr c taskbar notifier history m messagehistory remove tail delete messageptr ctaskbarnotifier ctaskbarnotifier m_messagehistory getcount ctaskbarnotifierhistory ctaskbarnotifierhistory m_messagehistory removetail int c taskbar notifier create c wnd p wnd parent assert p wnd parent null m pwndparent p wnd parent wndclassex wcx wcx cb size sizeof wcx from http www trigeminal com usenet usenet031 asp 1033 subject if you are using mfc 6 0 or 7 0 and you want to use mslu there is one additional problem that can occur if you are using afx wnd proc mfc s main shared window proc wrapper as an actual wndproc in any of your windows you see mfc has code in it so that if afx wnd proc is called and is told that the wndproc to follow up with is afx wnd proc it notices that it is being asked to call itself and forwards for def window proc instead unfortunately mslu breaks this code by having its own proc be the one that shows up mfc has no way of detecting this case so it calls the mslu proc which calls afx wnd proc which calls the mslu proc etc until the stack overflows by using either def window proc or your own proc yourself you avoid the stack overflow extern bool g bunicows if g bunicows wcx lpfn wnd proc my afxwndproc else wcx lpfn wnd proc afx wnd proc static const tchar s szclassname t emule taskbarnotifierwndclass wcx style cs dblclks cs savebits wcx cb cls extra 0 wcx cb wnd extra 0 wcx h instance afx get instance handle wcx h icon null wcx h cursor load cursor null idc arrow wcx hbr background get sys color brush color window wcx lpsz menu name null wcx lpsz class name s szclassname wcx h icon sm null register class ex wcx return create ex ws ex topmost s szclassname null ws popup 0 0 0 0 p wnd parent m hwnd null ctaskbarnotifier cwnd pwndparent pwndparent m_pwndparent pwndparent cbsize afxwndproc afxwndproc afxwndproc defwindowproc afxwndproc defwindowproc g_bunicows g_bunicows lpfnwndproc my_afxwndproc lpfnwndproc afxwndproc s_szclassname _t emule_taskbarnotifierwndclass cs_dblclks cs_savebits cbclsextra cbwndextra hinstance afxgetinstancehandle hicon hcursor loadcursor idc_arrow hbrbackground getsyscolorbrush color_window lpszmenuname lpszclassname s_szclassname hiconsm registerclassex createex ws_ex_topmost s_szclassname ws_popup pwndparent m_hwnd void c taskbar notifier show lpctstr sz caption int n msg type lpctstr psz link bool b auto close if n msg type tbn nonotify return uint n screen width uint n screen height uint n events uint n bitmap size c rect rc taskbar c taskbar notifier history messageptr m strcaption sz caption m nactivemessagetype n msg type m strlink psz link if m bautoclose sets it only if already true else wait for user action m bautoclose b auto close if n msg type tbn null n msg type tbn log n msg type tbn importantevent add element into string list max 5 elements if m messagehistory get count 5 messageptr c taskbar notifier history m messagehistory remove head delete messageptr messageptr null messageptr new c taskbar notifier history messageptr m strmessage m strcaption messageptr m nmessagetype n msg type messageptr m strlink m strlink m messagehistory add tail messageptr n screen width get system metrics sm cxscreen n screen height get system metrics sm cyscreen hwnd h wnd taskbar find window t shell traywnd 0 get window rect h wnd taskbar rc taskbar daniel lohmann calculate taskbar position from its window rect however on xp it may be that the taskbar is slightly larger or smaller than the screen size therefore we allow some tolerance here if nearly equal rc taskbar left 0 taskbar x tolerance nearly equal rc taskbar right n screen width taskbar x tolerance taskbar is on top or on bottom m ntaskbarplacement nearly equal rc taskbar top 0 taskbar y tolerance abe top abe bottom n bitmap size m nbitmapheight else taskbar is on left or on right m ntaskbarplacement nearly equal rc taskbar left 0 taskbar x tolerance abe left abe right n bitmap size m nbitmapwidth we calculate the pixel increment and the timer value for the showing animation if m dwtimetoshow m dwtimerprecision n events min m dwtimetoshow m dwtimerprecision 2 n bitmap size enkeydev ottavio84 reduced frames of a half m dwshowevents m dwtimetoshow n events m nincrementshow n bitmap size n events else m dwshowevents m dwtimerprecision m nincrementshow n bitmap size we calculate the pixel increment and the timer value for the hiding animation if m dwtimetohide m dwtimerprecision n events min m dwtimetohide m dwtimerprecision 2 n bitmap size enkeydev ottavio84 reduced frames of a half m dwhideevents m dwtimetohide n events m nincrementhide n bitmap size n events else m dwshowevents m dwtimerprecision m nincrementhide n bitmap size compute init values for the animation switch m nanimstatus case idt hidden if m ntaskbarplacement abe right m ncurrentposx rc taskbar left m ncurrentposy rc taskbar bottom m nbitmapheight m ncurrentwidth 0 m ncurrentheight m nbitmapheight else if m ntaskbarplacement abe left m ncurrentposx rc taskbar right m ncurrentposy rc taskbar bottom m nbitmapheight m ncurrentwidth 0 m ncurrentheight m nbitmapheight else if m ntaskbarplacement abe top m ncurrentposx rc taskbar right m nbitmapwidth m ncurrentposy rc taskbar bottom m ncurrentwidth m nbitmapwidth m ncurrentheight 0 else taskbar is on the bottom or invisible m ncurrentposx rc taskbar right m nbitmapwidth m ncurrentposy rc taskbar top m ncurrentwidth m nbitmapwidth m ncurrentheight 0 show window sw shownoactivate set timer idt appearing m dwshowevents null break case idt appearing redraw window break case idt waiting redraw window kill timer idt waiting set timer idt waiting m dwtimetostay null break case idt disappearing kill timer idt disappearing set timer idt waiting m dwtimetostay null if m ntaskbarplacement abe right m ncurrentposx rc taskbar left m nbitmapwidth m ncurrentwidth m nbitmapwidth else if m ntaskbarplacement abe left m ncurrentposx rc taskbar right m ncurrentwidth m nbitmapwidth else if m ntaskbarplacement abe top m ncurrentposy rc taskbar bottom m ncurrentheight m nbitmapheight else m ncurrentposy rc taskbar top m nbitmapheight m ncurrentheight m nbitmapheight set window pos wnd top most m ncurrentposx m ncurrentposy m ncurrentwidth m ncurrentheight swp noactivate redraw window break ctaskbarnotifier szcaption nmsgtype pszlink bautoclose nmsgtype tbn_nonotify nscreenwidth nscreenheight nevents nbitmapsize crect rctaskbar ctaskbarnotifierhistory m_strcaption szcaption m_nactivemessagetype nmsgtype m_strlink pszlink m_bautoclose m_bautoclose bautoclose nmsgtype tbn_null nmsgtype tbn_log nmsgtype tbn_importantevent m_messagehistory getcount ctaskbarnotifierhistory m_messagehistory removehead ctaskbarnotifierhistory m_strmessage m_strcaption m_nmessagetype nmsgtype m_strlink m_strlink m_messagehistory addtail nscreenwidth getsystemmetrics sm_cxscreen nscreenheight getsystemmetrics sm_cyscreen hwndtaskbar findwindow _t shell_traywnd getwindowrect hwndtaskbar rctaskbar nearlyequal rctaskbar taskbar_x_tolerance nearlyequal rctaskbar nscreenwidth taskbar_x_tolerance m_ntaskbarplacement nearlyequal rctaskbar taskbar_y_tolerance abe_top abe_bottom nbitmapsize m_nbitmapheight m_ntaskbarplacement nearlyequal rctaskbar taskbar_x_tolerance abe_left abe_right nbitmapsize m_nbitmapwidth m_dwtimetoshow m_dwtimerprecision nevents m_dwtimetoshow m_dwtimerprecision nbitmapsize m_dwshowevents m_dwtimetoshow nevents m_nincrementshow nbitmapsize nevents m_dwshowevents m_dwtimerprecision m_nincrementshow nbitmapsize m_dwtimetohide m_dwtimerprecision nevents m_dwtimetohide m_dwtimerprecision nbitmapsize m_dwhideevents m_dwtimetohide nevents m_nincrementhide nbitmapsize nevents m_dwshowevents m_dwtimerprecision m_nincrementhide nbitmapsize m_nanimstatus idt_hidden m_ntaskbarplacement abe_right m_ncurrentposx rctaskbar m_ncurrentposy rctaskbar m_nbitmapheight m_ncurrentwidth m_ncurrentheight m_nbitmapheight m_ntaskbarplacement abe_left m_ncurrentposx rctaskbar m_ncurrentposy rctaskbar m_nbitmapheight m_ncurrentwidth m_ncurrentheight m_nbitmapheight m_ntaskbarplacement abe_top m_ncurrentposx rctaskbar m_nbitmapwidth m_ncurrentposy rctaskbar m_ncurrentwidth m_nbitmapwidth m_ncurrentheight m_ncurrentposx rctaskbar m_nbitmapwidth m_ncurrentposy rctaskbar m_ncurrentwidth m_nbitmapwidth m_ncurrentheight showwindow sw_shownoactivate settimer idt_appearing m_dwshowevents idt_appearing redrawwindow idt_waiting redrawwindow killtimer idt_waiting settimer idt_waiting m_dwtimetostay idt_disappearing killtimer idt_disappearing settimer idt_waiting m_dwtimetostay m_ntaskbarplacement abe_right m_ncurrentposx rctaskbar m_nbitmapwidth m_ncurrentwidth m_nbitmapwidth m_ntaskbarplacement abe_left m_ncurrentposx rctaskbar m_ncurrentwidth m_nbitmapwidth m_ntaskbarplacement abe_top m_ncurrentposy rctaskbar m_ncurrentheight m_nbitmapheight m_ncurrentposy rctaskbar m_nbitmapheight m_ncurrentheight m_nbitmapheight setwindowpos wndtopmost m_ncurrentposx m_ncurrentposy m_ncurrentwidth m_ncurrentheight swp_noactivate redrawwindow void c taskbar notifier show last history message if m messagehistory get count 0 c taskbar notifier history messageptr c taskbar notifier history m messagehistory remove head show messageptr m strmessage messageptr m nmessagetype messageptr m strlink delete messageptr else show get res string ids tbn nomessagehistory tbn null null ctaskbarnotifier showlasthistorymessage m_messagehistory getcount ctaskbarnotifierhistory ctaskbarnotifierhistory m_messagehistory removehead m_strmessage m_nmessagetype m_strlink getresstring ids_tbn_nomessagehistory tbn_null int c taskbar notifier get message type return m nactivemessagetype ctaskbarnotifier getmessagetype m_nactivemessagetype void c taskbar notifier hide switch m nanimstatus case idt appearing kill timer idt appearing break case idt waiting kill timer idt waiting break case idt disappearing kill timer idt disappearing break move window 0 0 0 0 show window sw hide m nanimstatus idt hidden m nactivemessagetype tbn null ctaskbarnotifier m_nanimstatus idt_appearing killtimer idt_appearing idt_waiting killtimer idt_waiting idt_disappearing killtimer idt_disappearing movewindow showwindow sw_hide m_nanimstatus idt_hidden m_nactivemessagetype tbn_null bool c taskbar notifier set bitmap uint n bitmapid int red int green int blue m bitmapbackground delete object if m bitmapbackground load bitmap n bitmapid return false bitmap bm get object m bitmapbackground get safe handle sizeof bm bm m nbitmapwidth bm bm width m nbitmapheight bm bm height if red 1 green 1 blue 1 no need to delete the hrgn set window rgn owns it after being called m hbitmapregion create rgn from bitmap hbitmap m bitmapbackground get safe handle rgb red green blue set window rgn m hbitmapregion true return true ctaskbarnotifier setbitmap nbitmapid m_bitmapbackground deleteobject m_bitmapbackground loadbitmap nbitmapid getobject m_bitmapbackground getsafehandle m_nbitmapwidth bmwidth m_nbitmapheight bmheight setwindowrgn m_hbitmapregion creatergnfrombitmap m_bitmapbackground getsafehandle setwindowrgn m_hbitmapregion bool c taskbar notifier set bitmap lpctstr sz file name int red int green int blue if sz file name null sz file name 0 t 0 return false hbitmap h bmp hbitmap load image afx get instance handle sz file name image bitmap 0 0 lr loadfromfile if h bmp return false m bitmapbackground delete object m bitmapbackground attach h bmp bitmap bm get object m bitmapbackground get safe handle sizeof bm bm m nbitmapwidth bm bm width m nbitmapheight bm bm height if red 1 green 1 blue 1 no need to delete the hrgn set window rgn owns it after being called m hbitmapregion create rgn from bitmap hbitmap m bitmapbackground get safe handle rgb red green blue set window rgn m hbitmapregion true return true ctaskbarnotifier setbitmap szfilename szfilename szfilename _t hbmp loadimage afxgetinstancehandle szfilename image_bitmap lr_loadfromfile hbmp m_bitmapbackground deleteobject m_bitmapbackground hbmp getobject m_bitmapbackground getsafehandle m_nbitmapwidth bmwidth m_nbitmapheight bmheight setwindowrgn m_hbitmapregion creatergnfrombitmap m_bitmapbackground getsafehandle setwindowrgn m_hbitmapregion bool c taskbar notifier set bitmap c bitmap bitmap int red int green int blue m bitmapbackground delete object if m bitmapbackground attach bitmap detach return false bitmap bm get object m bitmapbackground get safe handle sizeof bm bm m nbitmapwidth bm bm width m nbitmapheight bm bm height if red 1 green 1 blue 1 no need to delete the hrgn set window rgn owns it after being called m hbitmapregion create rgn from bitmap hbitmap m bitmapbackground get safe handle rgb red green blue set window rgn m hbitmapregion true return true ctaskbarnotifier setbitmap cbitmap m_bitmapbackground deleteobject m_bitmapbackground getobject m_bitmapbackground getsafehandle m_nbitmapwidth bmwidth m_nbitmapheight bmheight setwindowrgn m_hbitmapregion creatergnfrombitmap m_bitmapbackground getsafehandle setwindowrgn m_hbitmapregion void c taskbar notifier set text font lpctstr sz font int n size int n normal style int n selected style logfont lf m mynormalfont delete object m mynormalfont create point font n size sz font m mynormalfont get log font lf we set the font of the unselected item if n normal style tn text bold lf lf weight fw bold else lf lf weight fw normal if n normal style tn text italic lf lf italic true else lf lf italic false if n normal style tn text underline lf lf underline true else lf lf underline false m mynormalfont delete object m mynormalfont create font indirect lf we set the font of the selected item if n selected style tn text bold lf lf weight fw bold else lf lf weight fw normal if n selected style tn text italic lf lf italic true else lf lf italic false if n selected style tn text underline lf lf underline true else lf lf underline false m myselectedfont delete object m myselectedfont create font indirect lf ctaskbarnotifier settextfont szfont nsize nnormalstyle nselectedstyle m_mynormalfont deleteobject m_mynormalfont createpointfont nsize szfont m_mynormalfont getlogfont nnormalstyle tn_text_bold lfweight fw_bold lfweight fw_normal nnormalstyle tn_text_italic lfitalic lfitalic nnormalstyle tn_text_underline lfunderline lfunderline m_mynormalfont deleteobject m_mynormalfont createfontindirect nselectedstyle tn_text_bold lfweight fw_bold lfweight fw_normal nselectedstyle tn_text_italic lfitalic lfitalic nselectedstyle tn_text_underline lfunderline lfunderline m_myselectedfont deleteobject m_myselectedfont createfontindirect void c taskbar notifier set text default font logfont lf c font p font c font from handle hfont get stock object default gui font p font get log font lf m mynormalfont delete object m myselectedfont delete object m mynormalfont create font indirect lf lf lf underline true m myselectedfont create font indirect lf ctaskbarnotifier settextdefaultfont cfont pfont cfont fromhandle getstockobject default_gui_font pfont getlogfont m_mynormalfont deleteobject m_myselectedfont deleteobject m_mynormalfont createfontindirect lfunderline m_myselectedfont createfontindirect void c taskbar notifier set text color colorref cr normal text color colorref cr selected text color m crnormaltextcolor cr normal text color m crselectedtextcolor cr selected text color redraw window ctaskbarnotifier settextcolor crnormaltextcolor crselectedtextcolor m_crnormaltextcolor crnormaltextcolor m_crselectedtextcolor crselectedtextcolor redrawwindow void c taskbar notifier set text rect rect rc text m rctext rc text ctaskbarnotifier settextrect rctext m_rctext rctext void c taskbar notifier set close btn rect rect rc close btn m rcclosebtn rc close btn ctaskbarnotifier setclosebtnrect rcclosebtn m_rcclosebtn rcclosebtn void c taskbar notifier set history btn rect rect rc history btn m rchistorybtn rc history btn ctaskbarnotifier sethistorybtnrect rchistorybtn m_rchistorybtn rchistorybtn void c taskbar notifier set text format uint u text format m utextformat u text format ctaskbarnotifier settextformat utextformat m_utextformat utextformat bool c taskbar notifier load configuration lpctstr sz file name tchar sz config dir max path int n red n green n blue s red s green s blue int rc left rc top rc right rc bottom int bmp trasparent red bmp trasparent green bmp trasparent blue int font size c string font type bmp full path str bmp file name hide m strconfigfilepath sz file name c ini ini sz file name t config tcsncpy sz config dir sz file name countof sz config dir sz config dir countof sz config dir 1 t 0 lptstr psz file name tcsrchr sz config dir t if psz file name null return false psz file name 1 t 0 n red ini get int t text normal red 255 n green ini get int t text normal green 255 n blue ini get int t text normal blue 255 s red ini get int t text selected red 255 s green ini get int t text selected green 255 s blue ini get int t text selected blue 255 bmp trasparent red ini get int t bmp trasparent red 255 bmp trasparent green ini get int t bmp trasparent green 0 bmp trasparent blue ini get int t bmp trasparent blue 255 font type ini get string t font type t ms shell dlg font size ini get int t font size 8 10 m dwtimetostay ini get int t time to stay 4000 m dwtimetoshow ini get int t time to show 500 m dwtimetohide ini get int t time to hide 200 str bmp file name ini get string t bmp file name t if str bmp file name is empty if path is relative str bmp file name bmp full path format t s s sz config dir str bmp file name else bmp full path str bmp file name get text rectangle coordinates rc left ini get int t rc text left 5 rc top ini get int t rc text top 45 rc right ini get int t rc text right 220 rc bottom ini get int t rc text bottom 85 if rc left 0 rc left 1 if rc top 0 rc top 1 if rc right 0 rc right 1 if rc bottom 0 rc bottom 1 set text rect c rect rc left rc top rc right rc bottom get close button rectangle coordinates rc left ini get int t rc close btn left 286 rc top ini get int t rc close btn top 40 rc right ini get int t rc close btn right 300 rc bottom ini get int t rc close btn bottom 54 if rc left 0 rc left 1 if rc top 0 rc top 1 if rc right 0 rc right 1 if rc bottom 0 rc bottom 1 set close btn rect c rect rc left rc top rc right rc bottom get history button rectangle coordinates rc left ini get int t rc history btn left 283 rc top ini get int t rc history btn top 14 rc right ini get int t rc history btn right 299 rc bottom ini get int t rc history btn bottom 39 if rc left 0 rc left 1 if rc top 0 rc top 1 if rc right 0 rc right 1 if rc bottom 0 rc bottom 1 set history btn rect c rect rc left rc top rc right rc bottom if bmp full path is empty set bitmap bmp full path bmp trasparent red bmp trasparent green bmp trasparent blue c en bitmap img taskbar if img taskbar load image idr taskbar t gif if set bitmap img taskbar bmp trasparent red bmp trasparent green bmp trasparent blue return false set text font font type font size tn text normal tn text underline set text color rgb n red n green n blue rgb s red s green s blue return true ctaskbarnotifier loadconfiguration szfilename szconfigdir max_path nred ngreen nblue sred sgreen sblue rcleft rctop rcright rcbottom bmptrasparentred bmptrasparentgreen bmptrasparentblue fontsize cstring fonttype bmpfullpath strbmpfilename m_strconfigfilepath szfilename cini szfilename _t _tcsncpy szconfigdir szfilename _countof szconfigdir szconfigdir _countof szconfigdir _t pszfilename _tcsrchr szconfigdir _t pszfilename pszfilename _t nred getint _t textnormalred ngreen getint _t textnormalgreen nblue getint _t textnormalblue sred getint _t textselectedred sgreen getint _t textselectedgreen sblue getint _t textselectedblue bmptrasparentred getint _t bmptrasparentred bmptrasparentgreen getint _t bmptrasparentgreen bmptrasparentblue getint _t bmptrasparentblue fonttype getstring _t fonttype _t fontsize getint _t fontsize m_dwtimetostay getint _t timetostay m_dwtimetoshow getint _t timetoshow m_dwtimetohide getint _t timetohide strbmpfilename getstring _t bmpfilename _t strbmpfilename isempty pathisrelative strbmpfilename bmpfullpath _t szconfigdir strbmpfilename bmpfullpath strbmpfilename rcleft getint _t rctextleft rctop getint _t rctexttop rcright getint _t rctextright rcbottom getint _t rctextbottom rcleft rcleft rctop rctop rcright rcright rcbottom rcbottom settextrect crect rcleft rctop rcright rcbottom rcleft getint _t rcclosebtnleft rctop getint _t rcclosebtntop rcright getint _t rcclosebtnright rcbottom getint _t rcclosebtnbottom rcleft rcleft rctop rctop rcright rcright rcbottom rcbottom setclosebtnrect crect rcleft rctop rcright rcbottom rcleft getint _t rchistorybtnleft rctop getint _t rchistorybtntop rcright getint _t rchistorybtnright rcbottom getint _t rchistorybtnbottom rcleft rcleft rctop rctop rcright rcright rcbottom rcbottom sethistorybtnrect crect rcleft rctop rcright rcbottom bmpfullpath isempty setbitmap bmpfullpath bmptrasparentred bmptrasparentgreen bmptrasparentblue cenbitmap imgtaskbar imgtaskbar loadimage idr_taskbar _t setbitmap imgtaskbar bmptrasparentred bmptrasparentgreen bmptrasparentblue settextfont fonttype fontsize tn_text_normal tn_text_underline settextcolor nred ngreen nblue sred sgreen sblue void c taskbar notifier set auto close bool auto close m bautoclose auto close if auto close true switch m nanimstatus case idt appearing kill timer idt appearing break case idt waiting kill timer idt waiting break case idt disappearing kill timer idt disappearing break m nanimstatus idt disappearing set timer idt disappearing m dwhideevents null ctaskbarnotifier setautoclose autoclose m_bautoclose autoclose autoclose m_nanimstatus idt_appearing killtimer idt_appearing idt_waiting killtimer idt_waiting idt_disappearing killtimer idt_disappearing m_nanimstatus idt_disappearing settimer idt_disappearing m_dwhideevents hrgn c taskbar notifier create rgn from bitmap hbitmap h bmp colorref color if h bmp return null cdc pdc getdc if pdc return null bitmap bm get object h bmp sizeof bitmap bm get bitmap attributes cdc dc bmp dc bmp create compatibledc pdc creates a memory device context for the bitmap hgdiobj h old bmp dc bmp select object h bmp selects the bitmap in the device context const dword rdhdr sizeof rgndataheader const dword maxbuf 40 size of one block in rec ts i e maxbuf sizeof rect in bytes lprect p rects dword c blocks 0 number of allocated blocks int i j current position in mask image int first 0 left position of current scan line where mask was found bool wasfirst false set when if mask was found in current scan line bool ismask set when current color is mask color allocate memory for region data rgndataheader p rgn data rgndataheader new byte rdhdr c blocks maxbuf sizeof rect memset p rgn data 0 rdhdr c blocks maxbuf sizeof rect fill it by default p rgn data dw size rdhdr p rgn data i type rdh rectangles p rgn data n count 0 for i 0 i bm bm height i for j 0 j bm bm width j get color ismask dc bmp get pixel j bm bm height i 1 color place part of scan line as rect region if transparent color found after mask color or mask color found at the end of mask image if wasfirst ismask j bm bm width 1 ismask j bm bm width get offset to rect array if rgndata buffer p rects lprect lpbyte p rgn data rdhdr save current rect p rects p rgn data n count c rect first bm bm height i 1 j j bm bm width 1 bm bm height i if buffer full reallocate it if p rgn data n count c blocks maxbuf lpbyte p rgn data new new byte rdhdr c blocks maxbuf sizeof rect memcpy p rgn data new p rgn data rdhdr c blocks 1 maxbuf sizeof rect delete p rgn data p rgn data rgndataheader p rgn data new wasfirst false else if wasfirst ismask set wasfirst when mask is found first j wasfirst true dc bmp select object h old bmp dc bmp deletedc release the bitmap create region under winnt the ext create region returns null by fable aramszu net hrgn h rgn ext create region null rdhdr p rgn data n count sizeof rect lprgndata p rgn data ext create region replacement hrgn h rgn create rect rgn 0 0 0 0 assert h rgn null p rects lprect lpbyte p rgn data rdhdr for i 0 i int p rgn data n count i hrgn hr create rect rgn p rects i left p rects i top p rects i right p rects i bottom verify combine rgn h rgn h rgn hr rgn or error if hr delete object hr assert h rgn null ext create region replacement delete p rgn data releasedc pdc return h rgn ctaskbarnotifier creatergnfrombitmap hbmp hbmp getobject hbmp dcbmp dcbmp createcompatibledc holdbmp dcbmp selectobject hbmp rects prects cblocks prgndata cblocks prgndata cblocks prgndata dwsize prgndata itype rdh_rectangles prgndata ncount bmheight bmwidth dcbmp getpixel bmheight bmwidth bmwidth prects prgndata prects prgndata ncount crect bmheight bmwidth bmheight prgndata ncount cblocks prgndatanew cblocks prgndatanew prgndata cblocks prgndata prgndata prgndatanew dcbmp selectobject holdbmp dcbmp extcreateregion hrgn extcreateregion prgndata ncount prgndata extcreateregion hrgn createrectrgn hrgn prects prgndata prgndata ncount createrectrgn prects prects prects prects combinergn hrgn hrgn rgn_or deleteobject hrgn extcreateregion prgndata hrgn void c taskbar notifier on mouse move uint n flags c point point trackmouseevent t mouseevent t mouseevent cb size sizeof trackmouseevent t mouseevent dw flags tme leave tme hover t mouseevent hwnd track m hwnd t mouseevent dw hover time 1 we tell windows we want to receive wm mousehover and wm mouseleave trackmouseevent t mouseevent c wnd on mouse move n flags point ctaskbarnotifier onmousemove nflags cpoint t_mouseevent t_mouseevent cbsize t_mouseevent dwflags tme_leave tme_hover t_mouseevent hwndtrack m_hwnd t_mouseevent dwhovertime wm_mousehover wm_mouseleave _trackmouseevent t_mouseevent cwnd onmousemove nflags void c taskbar notifier onl button up uint n flags c point point close button clicked if m rcclosebtn pt in rect point m bautoclose true set true so next time arrive an autoclose event the popup will autoclose when m bautoclose is false a true event will be ignored until the user manually close the windows switch m nanimstatus case idt appearing kill timer idt appearing break case idt waiting kill timer idt waiting break case idt disappearing kill timer idt disappearing break m nanimstatus idt disappearing set timer idt disappearing m dwhideevents null hide cycle history button clicked if m rchistorybtn pt in rect point if m messagehistory get count 0 c taskbar notifier history messageptr c taskbar notifier history m messagehistory remove head show messageptr m strmessage messageptr m nmessagetype messageptr m strlink delete messageptr message clicked if m rctext pt in rect point notify the parent window that the notifier popup was clicked lpctstr psz link m strlink is empty null tcsdup m strlink m pwndparent post message um taskbarnotifierclicked 0 lparam psz link c wnd onl button up n flags point ctaskbarnotifier onlbuttonup nflags cpoint m_rcclosebtn ptinrect m_bautoclose m_bautoclose m_nanimstatus idt_appearing killtimer idt_appearing idt_waiting killtimer idt_waiting idt_disappearing killtimer idt_disappearing m_nanimstatus idt_disappearing settimer idt_disappearing m_dwhideevents m_rchistorybtn ptinrect m_messagehistory getcount ctaskbarnotifierhistory ctaskbarnotifierhistory m_messagehistory removehead m_strmessage m_nmessagetype m_strlink m_rctext ptinrect pszlink m_strlink isempty _tcsdup m_strlink m_pwndparent postmessage um_taskbarnotifierclicked pszlink cwnd onlbuttonup nflags lresult c taskbar notifier on mouse hover wparam w param lparam l param if m nanimstatus idt waiting kill timer idt waiting points mp mp makepoints l param m ptmouseposition x mp x m ptmouseposition y mp y if m bmouseisover false m bmouseisover true redraw window else if m ptmouseposition x m rctext left m ptmouseposition x m rctext right m ptmouseposition y m rctext top m ptmouseposition y m rctext bottom if m btextselected redraw window else if m btextselected redraw window return 0 ctaskbarnotifier onmousehover wparam lparam m_nanimstatus idt_waiting killtimer idt_waiting lparam m_ptmouseposition m_ptmouseposition m_bmouseisover m_bmouseisover redrawwindow m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_btextselected redrawwindow m_btextselected redrawwindow lresult c taskbar notifier on mouse leave wparam w param lparam l param if m bmouseisover true m bmouseisover false redraw window if m nanimstatus idt waiting set timer idt waiting m dwtimetostay null return 0 ctaskbarnotifier onmouseleave wparam lparam m_bmouseisover m_bmouseisover redrawwindow m_nanimstatus idt_waiting settimer idt_waiting m_dwtimetostay bool c taskbar notifier on erase bkgnd cdc pdc cdc memdc memdc create compatibledc pdc c bitmap p old bitmap memdc select object m bitmapbackground pdc bit blt 0 0 m ncurrentwidth m ncurrentheight memdc 0 0 srccopy memdc select object p old bitmap return true ctaskbarnotifier onerasebkgnd createcompatibledc cbitmap poldbitmap selectobject m_bitmapbackground bitblt m_ncurrentwidth m_ncurrentheight selectobject poldbitmap void c taskbar notifier on paint c paintdc dc this c font p old font if m bmouseisover if m ptmouseposition x m rctext left m ptmouseposition x m rctext right m ptmouseposition y m rctext top m ptmouseposition y m rctext bottom m btextselected true dc set text color m crselectedtextcolor p old font dc select object m myselectedfont else m btextselected false dc set text color m crnormaltextcolor p old font dc select object m mynormalfont else dc set text color m crnormaltextcolor p old font dc select object m mynormalfont dc set bk mode transparent dc draw text m strcaption m strcaption get length m rctext m utextformat dc select object p old font ctaskbarnotifier onpaint cpaintdc cfont poldfont m_bmouseisover m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_ptmouseposition m_rctext m_btextselected settextcolor m_crselectedtextcolor poldfont selectobject m_myselectedfont m_btextselected settextcolor m_crnormaltextcolor poldfont selectobject m_mynormalfont settextcolor m_crnormaltextcolor poldfont selectobject m_mynormalfont setbkmode drawtext m_strcaption m_strcaption getlength m_rctext m_utextformat selectobject poldfont bool c taskbar notifier on set cursor c wnd p wnd uint n hit test uint message if n hit test htclient if m rcclosebtn pt in rect m ptmouseposition m rchistorybtn pt in rect m ptmouseposition m rctext pt in rect m ptmouseposition set cursor m hcursor return true return c wnd on set cursor p wnd n hit test message ctaskbarnotifier onsetcursor cwnd pwnd nhittest nhittest m_rcclosebtn ptinrect m_ptmouseposition m_rchistorybtn ptinrect m_ptmouseposition m_rctext ptinrect m_ptmouseposition setcursor m_hcursor cwnd onsetcursor pwnd nhittest void c taskbar notifier on timer uint nid event switch nid event case idt appearing m nanimstatus idt appearing switch m ntaskbarplacement case abe bottom if m ncurrentheight m nbitmapheight m ncurrentposy m nincrementshow m ncurrentheight m nincrementshow else kill timer idt appearing set timer idt waiting m dwtimetostay null m nanimstatus idt waiting break case abe top if m ncurrentheight m nbitmapheight m ncurrentheight m nincrementshow else kill timer idt appearing set timer idt waiting m dwtimetostay null m nanimstatus idt waiting break case abe left if m ncurrentwidth m nbitmapwidth m ncurrentwidth m nincrementshow else kill timer idt appearing set timer idt waiting m dwtimetostay null m nanimstatus idt waiting break case abe right if m ncurrentwidth m nbitmapwidth m ncurrentposx m nincrementshow m ncurrentwidth m nincrementshow else kill timer idt appearing set timer idt waiting m dwtimetostay null m nanimstatus idt waiting break set window pos wnd top most m ncurrentposx m ncurrentposy m ncurrentwidth m ncurrentheight swp noactivate break case idt waiting kill timer idt waiting if m bautoclose set timer idt disappearing m dwhideevents null break case idt disappearing m nanimstatus idt disappearing switch m ntaskbarplacement case abe bottom if m ncurrentheight 0 m ncurrentposy m nincrementhide m ncurrentheight m nincrementhide else kill timer idt disappearing hide break case abe top if m ncurrentheight 0 m ncurrentheight m nincrementhide else kill timer idt disappearing hide break case abe left if m ncurrentwidth 0 m ncurrentwidth m nincrementhide else kill timer idt disappearing hide break case abe right if m ncurrentwidth 0 m ncurrentposx m nincrementhide m ncurrentwidth m nincrementhide else kill timer idt disappearing hide break set window pos wnd top most m ncurrentposx m ncurrentposy m ncurrentwidth m ncurrentheight swp noactivate break c wnd on timer nid event ctaskbarnotifier ontimer nidevent nidevent idt_appearing m_nanimstatus idt_appearing m_ntaskbarplacement abe_bottom m_ncurrentheight m_nbitmapheight m_ncurrentposy m_nincrementshow m_ncurrentheight m_nincrementshow killtimer idt_appearing settimer idt_waiting m_dwtimetostay m_nanimstatus idt_waiting abe_top m_ncurrentheight m_nbitmapheight m_ncurrentheight m_nincrementshow killtimer idt_appearing settimer idt_waiting m_dwtimetostay m_nanimstatus idt_waiting abe_left m_ncurrentwidth m_nbitmapwidth m_ncurrentwidth m_nincrementshow killtimer idt_appearing settimer idt_waiting m_dwtimetostay m_nanimstatus idt_waiting abe_right m_ncurrentwidth m_nbitmapwidth m_ncurrentposx m_nincrementshow m_ncurrentwidth m_nincrementshow killtimer idt_appearing settimer idt_waiting m_dwtimetostay m_nanimstatus idt_waiting setwindowpos wndtopmost m_ncurrentposx m_ncurrentposy m_ncurrentwidth m_ncurrentheight swp_noactivate idt_waiting killtimer idt_waiting m_bautoclose settimer idt_disappearing m_dwhideevents idt_disappearing m_nanimstatus idt_disappearing m_ntaskbarplacement abe_bottom m_ncurrentheight m_ncurrentposy m_nincrementhide m_ncurrentheight m_nincrementhide killtimer idt_disappearing abe_top m_ncurrentheight m_ncurrentheight m_nincrementhide killtimer idt_disappearing abe_left m_ncurrentwidth m_ncurrentwidth m_nincrementhide killtimer idt_disappearing abe_right m_ncurrentwidth m_ncurrentposx m_nincrementhide m_ncurrentwidth m_nincrementhide killtimer idt_disappearing setwindowpos wndtopmost m_ncurrentposx m_ncurrentposy m_ncurrentwidth m_ncurrentheight swp_noactivate cwnd ontimer nidevent void c taskbar notifier on sys color change c wnd on sys color change load configuration m strconfigfilepath ctaskbarnotifier onsyscolorchange cwnd onsyscolorchange loadconfiguration m_strconfigfilepath c splash screen c splash screen c wnd p parent null c dialog c splash screen idd p parent csplashscreen csplashscreen cwnd pparent cdialog csplashscreen pparent c splash screen c splash screen m imgsplash delete object csplashscreen csplashscreen m_imgsplash deleteobject void c splash screen do data exchange c data exchange pdx c dialog do data exchange pdx csplashscreen dodataexchange cdataexchange cdialog dodataexchange bool c splash screen on init dialog c dialog on init dialog init window styles this verify m imgsplash attach the app load image t about t jpg if m imgsplash get safe handle bitmap bmp 0 if m imgsplash get bitmap bmp 0 windowplacement wp get window placement wp wp rc normal position right wp rc normal position left bmp bm width wp rc normal position bottom wp rc normal position top bmp bm height set window placement wp return true csplashscreen oninitdialog cdialog oninitdialog initwindowstyles m_imgsplash theapp loadimage _t _t m_imgsplash getsafehandle m_imgsplash getbitmap getwindowplacement rcnormalposition rcnormalposition bmwidth rcnormalposition rcnormalposition bmheight setwindowplacement bool c splash screen pre translate message msg p msg bool b result c dialog pre translate message p msg if p msg message wm keydown p msg message wm syskeydown p msg message wm lbuttondown p msg message wm rbuttondown p msg message wm mbuttondown p msg message wm nclbuttondown p msg message wm ncrbuttondown p msg message wm ncmbuttondown destroy window return b result csplashscreen pretranslatemessage pmsg bresult cdialog pretranslatemessage pmsg pmsg wm_keydown pmsg wm_syskeydown pmsg wm_lbuttondown pmsg wm_rbuttondown pmsg wm_mbuttondown pmsg wm_nclbuttondown pmsg wm_ncrbuttondown pmsg wm_ncmbuttondown destroywindow bresult void c splash screen on paint c paintdc dc this device context for painting if m imgsplash get safe handle cdc dc mem if dc mem create compatibledc dc c bitmap p oldbm dc mem select object m imgsplash bitmap bm m imgsplash get bitmap bm dc bit blt 0 0 bm bm width bm bm height dc mem 0 0 srccopy if p oldbm dc mem select object p oldbm c rect rc 0 int bm bm height 0 65 bm bm width bm bm height dc fill solid rect rc left 1 rc top 1 rc width 2 rc height 2 rgb 255 255 255 logfont lf 0 lf lf height 30 lf lf weight fw bold lf lf quality afx data b win95 nonantialiased quality antialiased quality tcscpy lf lf face name t arial c font font font create font indirect lf c font p old font dc select object font c string str app version t e mule the app m strcurversionlong rc top dc draw text str app version rc dt center dt noprefix if p old font dc select object p old font font delete object rc top 8 lf lf height 14 lf lf weight fw normal lf lf quality afx data b win95 nonantialiased quality antialiased quality tcscpy lf lf face name t arial font create font indirect lf p old font dc select object font dc draw text t copyright c 2002 2006 merkur rc dt center dt noprefix if p old font dc select object p old font font delete object csplashscreen onpaint cpaintdc m_imgsplash getsafehandle dcmem dcmem createcompatibledc cbitmap poldbm dcmem selectobject m_imgsplash m_imgsplash getbitmap bitblt bmwidth bmheight dcmem poldbm dcmem selectobject poldbm crect bmheight bmwidth bmheight fillsolidrect lfheight lfweight fw_bold lfquality afxdata bwin95 nonantialiased_quality antialiased_quality _tcscpy lffacename _t cfont createfontindirect cfont poldfont selectobject cstring strappversion _t emule theapp m_strcurversionlong drawtext strappversion dt_center dt_noprefix poldfont selectobject poldfont deleteobject lfheight lfweight fw_normal lfquality afxdata bwin95 nonantialiased_quality antialiased_quality _tcscpy lffacename _t createfontindirect poldfont selectobject drawtext _t dt_center dt_noprefix poldfont selectobject poldfont deleteobject c resizable page c file info dialog idd 0 m pafiles null m bdatachanged false m strcaption get res string ids fileinfo m psp psz title m strcaption m psp dw flags psp usetitle memset m cfdef 0 sizeof m cfdef memset m cfbold 0 sizeof m cfbold memset m cfred 0 sizeof m cfred cresizablepage cfileinfodialog m_pafiles m_bdatachanged m_strcaption getresstring ids_fileinfo m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_cfdef m_cfdef m_cfbold m_cfbold m_cfred m_cfred c file info dialog c file info dialog cfileinfodialog cfileinfodialog void c file info dialog localize get dlg item idc fd xi1 set window text get res string ids fd size get dlg item idc fd xi2 set window text get res string ids length t get dlg item idc fd xi3 set window text get res string ids video get dlg item idc fd xi4 set window text get res string ids audio get dlg item idc fd xi5 set window text get res string ids codec t get dlg item idc fd xi6 set window text get res string ids codec t get dlg item idc fd xi7 set window text get res string ids bitrate t get dlg item idc fd xi8 set window text get res string ids bitrate t get dlg item idc fd xi9 set window text get res string ids width t get dlg item idc fd xi11 set window text get res string ids height t get dlg item idc fd xi13 set window text get res string ids fps t get dlg item idc fd xi10 set window text get res string ids channels t get dlg item idc fd xi12 set window text get res string ids samplerate t get dlg item idc staticfi set window text get res string ids fileformat t get dlg item idc fd xi14 set window text get res string ids aspectratio t cfileinfodialog getdlgitem idc_fd_xi1 setwindowtext getresstring ids_fd_size getdlgitem idc_fd_xi2 setwindowtext getresstring ids_length _t getdlgitem idc_fd_xi3 setwindowtext getresstring ids_video getdlgitem idc_fd_xi4 setwindowtext getresstring ids_audio getdlgitem idc_fd_xi5 setwindowtext getresstring ids_codec _t getdlgitem idc_fd_xi6 setwindowtext getresstring ids_codec _t getdlgitem idc_fd_xi7 setwindowtext getresstring ids_bitrate _t getdlgitem idc_fd_xi8 setwindowtext getresstring ids_bitrate _t getdlgitem idc_fd_xi9 setwindowtext getresstring ids_width _t getdlgitem idc_fd_xi11 setwindowtext getresstring ids_height _t getdlgitem idc_fd_xi13 setwindowtext getresstring ids_fps _t getdlgitem idc_fd_xi10 setwindowtext getresstring ids_channels _t getdlgitem idc_fd_xi12 setwindowtext getresstring ids_samplerate _t getdlgitem idc_staticfi setwindowtext getresstring ids_fileformat _t getdlgitem idc_fd_xi14 setwindowtext getresstring ids_aspectratio _t void c file info dialog add file info lpctstr psz fmt va list p argp va start p argp psz fmt c string str info str info formatv psz fmt p argp va end p argp m fi set sel m fi get window text length m fi get window text length m fi replace sel str info cfileinfodialog addfileinfo pszfmt va_list pargp va_start pargp pszfmt cstring strinfo strinfo pszfmt pargp va_end pargp m_fi setsel m_fi getwindowtextlength m_fi getwindowtextlength m_fi replacesel strinfo void c file info dialog do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc full file info m fi cfileinfodialog dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_full_file_info m_fi bool c file info dialog on init dialog c wait cursor cur wait we may get quite busy here replace rich edit ctrl get dlg item idc full file info this get dlg item idc fd xi1 get font c resizable page on init dialog init window styles this add anchor idc full file info top left bottom right m fi send message em setmargins ec leftmargin ec rightmargin makelong 3 3 m fi set autourl detect m fi set event mask m fi get event mask enm link paraformat pf 0 pf cb size sizeof pf if m fi get para format pf pf dw mask pfm tabstops pf c tab count 1 pf rgx tabs 0 3000 m fi set para format pf m cfdef cb size sizeof m cfdef if m fi get selection char format m cfdef m cfbold m cfdef m cfbold dw mask cfm bold m cfbold dw effects cfe bold m cfred m cfdef m cfred dw mask cfm color m cfred dw effects cfe autocolor m cfred cr text color rgb 255 0 0 c resizable page update data false localize return true cfileinfodialog oninitdialog cwaitcursor curwait replacericheditctrl getdlgitem idc_full_file_info getdlgitem idc_fd_xi1 getfont cresizablepage oninitdialog initwindowstyles addanchor idc_full_file_info top_left bottom_right m_fi sendmessage em_setmargins ec_leftmargin ec_rightmargin m_fi setautourldetect m_fi seteventmask m_fi geteventmask enm_link cbsize m_fi getparaformat dwmask pfm_tabstops ctabcount rgxtabs m_fi setparaformat m_cfdef cbsize m_cfdef m_fi getselectioncharformat m_cfdef m_cfbold m_cfdef m_cfbold dwmask cfm_bold m_cfbold dweffects cfe_bold m_cfred m_cfdef m_cfred dwmask cfm_color m_cfred dweffects cfe_autocolor m_cfred crtextcolor cresizablepage updatedata bool c file info dialog on set active if c resizable page on set active return false if m bdatachanged c string str wait get res string ids fstat waiting set dlg item text idc format str wait set dlg item text idc filesize str wait set dlg item text idc length str wait set dlg item text idc vcodec str wait set dlg item text idc vbitrate str wait set dlg item text idc vwidth str wait set dlg item text idc vheight str wait set dlg item text idc vaspect str wait set dlg item text idc vfps str wait set dlg item text idc acodec str wait set dlg item text idc achannel str wait set dlg item text idc asamplerate str wait set dlg item text idc abitrate str wait set dlg item text idc alanguage str wait set dlg item text idc full file info str wait c get media info thread p thread c get media info thread afx begin thread runtime class c get media info thread thread priority normal 0 create suspended if p thread p thread set values m hwnd m pafiles p thread resume thread m bdatachanged false return true cfileinfodialog onsetactive cresizablepage onsetactive m_bdatachanged cstring strwait getresstring ids_fstat_waiting setdlgitemtext idc_format strwait setdlgitemtext idc_filesize strwait setdlgitemtext idc_length strwait setdlgitemtext idc_vcodec strwait setdlgitemtext idc_vbitrate strwait setdlgitemtext idc_vwidth strwait setdlgitemtext idc_vheight strwait setdlgitemtext idc_vaspect strwait setdlgitemtext idc_vfps strwait setdlgitemtext idc_acodec strwait setdlgitemtext idc_achannel strwait setdlgitemtext idc_asamplerate strwait setdlgitemtext idc_abitrate strwait setdlgitemtext idc_alanguage strwait setdlgitemtext idc_full_file_info strwait cgetmediainfothread pthread cgetmediainfothread afxbeginthread runtime_class cgetmediainfothread thread_priority_normal create_suspended pthread pthread setvalues m_hwnd m_pafiles pthread resumethread m_bdatachanged lresult c file info dialog on media info result wparam lparam l param set dlg item text idc fd xi3 get res string ids video set dlg item text idc fd xi4 get res string ids audio set dlg item text idc format t set dlg item text idc filesize t set dlg item text idc length t set dlg item text idc vcodec t set dlg item text idc vbitrate t set dlg item text idc vwidth t set dlg item text idc vheight t set dlg item text idc vaspect t set dlg item text idc vfps t set dlg item text idc acodec t set dlg item text idc achannel t set dlg item text idc asamplerate t set dlg item text idc abitrate t set dlg item text idc alanguage t set dlg item text idc full file info t c array s media info pa media info c array s media info l param if pa media info null return 0 if pa media info get size m pafiles get size set dlg item text idc format t set dlg item text idc filesize t set dlg item text idc length t set dlg item text idc vcodec t set dlg item text idc vbitrate t set dlg item text idc vwidth t set dlg item text idc vheight t set dlg item text idc vaspect t set dlg item text idc vfps t set dlg item text idc acodec t set dlg item text idc achannel t set dlg item text idc asamplerate t set dlg item text idc abitrate t set dlg item text idc alanguage t set dlg item text idc full file info t delete pa media info return 0 uint64 u total file size 0 s media info ami bool b diff video stream count false bool b diff video compression false bool b diff video width false bool b diff video height false bool b diff video frame rate false bool b diff video bit rate false bool b diff video aspect ratio false bool b diff audio stream count false bool b diff audio compression false bool b diff audio channels false bool b diff audio samples per sec false bool b diff audio avg bytes per sec false bool b diff audio language false for int i 0 i pa media info get size i const s media info mi pa media info get at i u total file size uint64 mi ul file size if i 0 ami mi else if ami str file format mi str file format ami str file format empty if ami str mime type mi str mime type ami str mime type empty ami f video length sec mi f video length sec if ami i video streams 0 mi i video streams 0 ami i video streams 0 mi i video streams 0 if ami i video streams 0 ami i video streams mi i video streams b diff video stream count true b diff video compression true b diff video width true b diff video height true b diff video frame rate true b diff video bit rate true b diff video aspect ratio true else if ami i video streams mi i video streams b diff video stream count true if ami str video format mi str video format b diff video compression true if ami video bmi header bi width mi video bmi header bi width b diff video width true if ami video bmi header bi height mi video bmi header bi height b diff video height true if ami f video frame rate mi f video frame rate b diff video frame rate true if ami video dw bit rate mi video dw bit rate b diff video bit rate true if ami f video aspect ratio mi f video aspect ratio b diff video aspect ratio true ami f audio length sec mi f audio length sec if ami i audio streams 0 mi i audio streams 0 ami i audio streams 0 mi i audio streams 0 if ami i audio streams 0 ami i audio streams mi i audio streams b diff audio stream count true b diff audio compression true b diff audio channels true b diff audio samples per sec true b diff audio avg bytes per sec true b diff audio language true else if ami i audio streams mi i audio streams b diff audio stream count true if ami str audio format mi str audio format b diff audio compression true if ami audio n channels mi audio n channels b diff audio channels true if ami audio n samples per sec mi audio n samples per sec b diff audio samples per sec true if ami audio n avg bytes per sec mi audio n avg bytes per sec b diff audio avg bytes per sec true if ami str audio language compare no case mi str audio language 0 b diff audio language true if ami str info str is empty ami str info n ami str info mi str info str c string buffer buffer ami str file format if ami str mime type is empty if buffer is empty buffer t mime type buffer append format t s ami str mime type set dlg item text idc format buffer if u total file size set dlg item text idc filesize cast itox bytes u total file size false false if ami f video length sec set dlg item text idc length cast seconds tohm time t ami f video length sec else if ami f audio length sec set dlg item text idc length cast seconds tohm time t ami f audio length sec if ami i video streams if b diff video stream count ami i video streams 1 set dlg item text idc fd xi3 get res string ids video t 1 else set dlg item text idc fd xi3 get res string ids video if b diff video compression ami str video format is empty set dlg item text idc vcodec ami str video format else set dlg item text idc vcodec t if b diff video bit rate ami video dw bit rate if ami video dw bit rate dword 1 buffer t variable else buffer format t u s ami video dw bit rate 500 1000 get res string ids kbitssec set dlg item text idc vbitrate buffer else set dlg item text idc vbitrate t if b diff video width ami video bmi header bi width set dlg item int idc vwidth abs ami video bmi header bi width false else set dlg item text idc vwidth t if b diff video height ami video bmi header bi height set dlg item int idc vheight abs ami video bmi header bi height false else set dlg item text idc vheight t if b diff video aspect ratio ami f video aspect ratio buffer format t 3f ami f video aspect ratio c string strar get known aspect ratio display string float ami f video aspect ratio if strar is empty buffer append format t s strar set dlg item text idc vaspect buffer else set dlg item text idc vaspect t if b diff video frame rate ami f video frame rate buffer format t 2f ami f video frame rate set dlg item text idc vfps buffer else set dlg item text idc vfps t if ami i audio streams if b diff audio stream count ami i audio streams 1 set dlg item text idc fd xi4 get res string ids audio t 1 else set dlg item text idc fd xi4 get res string ids audio if b diff audio compression ami str audio format is empty set dlg item text idc acodec ami str audio format else set dlg item text idc acodec t if b diff audio channels ami audio n channels switch ami audio n channels case 1 set dlg item text idc achannel t 1 mono break case 2 set dlg item text idc achannel t 2 stereo break case 5 set dlg item text idc achannel t 5 1 surround break default set dlg item int idc achannel ami audio n channels false break else set dlg item text idc achannel t if b diff audio samples per sec ami audio n samples per sec buffer format t 3f k hz ami audio n samples per sec 1000 0 set dlg item text idc asamplerate buffer else set dlg item text idc asamplerate t if b diff audio avg bytes per sec ami audio n avg bytes per sec if ami audio n avg bytes per sec dword 1 buffer t variable else buffer format t u s uint ami audio n avg bytes per sec 8 1000 0 0 5 get res string ids kbitssec set dlg item text idc abitrate buffer else set dlg item text idc abitrate t if b diff audio language ami str audio language is empty set dlg item text idc alanguage ami str audio language else set dlg item text idc alanguage t set dlg item text idc full file info ami str info str m fi set sel 0 0 delete pa media info return 0 cfileinfodialog onmediainforesult lparam setdlgitemtext idc_fd_xi3 getresstring ids_video setdlgitemtext idc_fd_xi4 getresstring ids_audio setdlgitemtext idc_format _t setdlgitemtext idc_filesize _t setdlgitemtext idc_length _t setdlgitemtext idc_vcodec _t setdlgitemtext idc_vbitrate _t setdlgitemtext idc_vwidth _t setdlgitemtext idc_vheight _t setdlgitemtext idc_vaspect _t setdlgitemtext idc_vfps _t setdlgitemtext idc_acodec _t setdlgitemtext idc_achannel _t setdlgitemtext idc_asamplerate _t setdlgitemtext idc_abitrate _t setdlgitemtext idc_alanguage _t setdlgitemtext idc_full_file_info _t carray smediainfo pamediainfo carray smediainfo lparam pamediainfo pamediainfo getsize m_pafiles getsize setdlgitemtext idc_format _t setdlgitemtext idc_filesize _t setdlgitemtext idc_length _t setdlgitemtext idc_vcodec _t setdlgitemtext idc_vbitrate _t setdlgitemtext idc_vwidth _t setdlgitemtext idc_vheight _t setdlgitemtext idc_vaspect _t setdlgitemtext idc_vfps _t setdlgitemtext idc_acodec _t setdlgitemtext idc_achannel _t setdlgitemtext idc_asamplerate _t setdlgitemtext idc_abitrate _t setdlgitemtext idc_alanguage _t setdlgitemtext idc_full_file_info _t pamediainfo utotalfilesize smediainfo bdiffvideostreamcount bdiffvideocompression bdiffvideowidth bdiffvideoheight bdiffvideoframerate bdiffvideobitrate bdiffvideoaspectratio bdiffaudiostreamcount bdiffaudiocompression bdiffaudiochannels bdiffaudiosamplespersec bdiffaudioavgbytespersec bdiffaudiolanguage pamediainfo getsize smediainfo pamediainfo getat utotalfilesize ulfilesize strfileformat strfileformat strfileformat strmimetype strmimetype strmimetype fvideolengthsec fvideolengthsec ivideostreams ivideostreams ivideostreams ivideostreams ivideostreams ivideostreams ivideostreams bdiffvideostreamcount bdiffvideocompression bdiffvideowidth bdiffvideoheight bdiffvideoframerate bdiffvideobitrate bdiffvideoaspectratio ivideostreams ivideostreams bdiffvideostreamcount strvideoformat strvideoformat bdiffvideocompression bmiheader biwidth bmiheader biwidth bdiffvideowidth bmiheader biheight bmiheader biheight bdiffvideoheight fvideoframerate fvideoframerate bdiffvideoframerate dwbitrate dwbitrate bdiffvideobitrate fvideoaspectratio fvideoaspectratio bdiffvideoaspectratio faudiolengthsec faudiolengthsec iaudiostreams iaudiostreams iaudiostreams iaudiostreams iaudiostreams iaudiostreams iaudiostreams bdiffaudiostreamcount bdiffaudiocompression bdiffaudiochannels bdiffaudiosamplespersec bdiffaudioavgbytespersec bdiffaudiolanguage iaudiostreams iaudiostreams bdiffaudiostreamcount straudioformat straudioformat bdiffaudiocompression nchannels nchannels bdiffaudiochannels nsamplespersec nsamplespersec bdiffaudiosamplespersec navgbytespersec navgbytespersec bdiffaudioavgbytespersec straudiolanguage comparenocase straudiolanguage bdiffaudiolanguage strinfo isempty strinfo strinfo strinfo cstring strfileformat strmimetype isempty isempty _t appendformat _t strmimetype setdlgitemtext idc_format utotalfilesize setdlgitemtext idc_filesize castitoxbytes utotalfilesize fvideolengthsec setdlgitemtext idc_length castsecondstohm time_t fvideolengthsec faudiolengthsec setdlgitemtext idc_length castsecondstohm time_t faudiolengthsec ivideostreams bdiffvideostreamcount ivideostreams setdlgitemtext idc_fd_xi3 getresstring ids_video _t setdlgitemtext idc_fd_xi3 getresstring ids_video bdiffvideocompression strvideoformat isempty setdlgitemtext idc_vcodec strvideoformat setdlgitemtext idc_vcodec _t bdiffvideobitrate dwbitrate dwbitrate _t _t dwbitrate getresstring ids_kbitssec setdlgitemtext idc_vbitrate setdlgitemtext idc_vbitrate _t bdiffvideowidth bmiheader biwidth setdlgitemint idc_vwidth bmiheader biwidth setdlgitemtext idc_vwidth _t bdiffvideoheight bmiheader biheight setdlgitemint idc_vheight bmiheader biheight setdlgitemtext idc_vheight _t bdiffvideoaspectratio fvideoaspectratio _t fvideoaspectratio cstring getknownaspectratiodisplaystring fvideoaspectratio isempty appendformat _t setdlgitemtext idc_vaspect setdlgitemtext idc_vaspect _t bdiffvideoframerate fvideoframerate _t fvideoframerate setdlgitemtext idc_vfps setdlgitemtext idc_vfps _t iaudiostreams bdiffaudiostreamcount iaudiostreams setdlgitemtext idc_fd_xi4 getresstring ids_audio _t setdlgitemtext idc_fd_xi4 getresstring ids_audio bdiffaudiocompression straudioformat isempty setdlgitemtext idc_acodec straudioformat setdlgitemtext idc_acodec _t bdiffaudiochannels nchannels nchannels setdlgitemtext idc_achannel _t setdlgitemtext idc_achannel _t setdlgitemtext idc_achannel _t setdlgitemint idc_achannel nchannels setdlgitemtext idc_achannel _t bdiffaudiosamplespersec nsamplespersec _t khz nsamplespersec setdlgitemtext idc_asamplerate setdlgitemtext idc_asamplerate _t bdiffaudioavgbytespersec navgbytespersec navgbytespersec _t _t navgbytespersec getresstring ids_kbitssec setdlgitemtext idc_abitrate setdlgitemtext idc_abitrate _t bdiffaudiolanguage straudiolanguage isempty setdlgitemtext idc_alanguage straudiolanguage setdlgitemtext idc_alanguage _t setdlgitemtext idc_full_file_info strinfo m_fi setsel pamediainfo lresult c file info dialog on data changed wparam lparam m bdatachanged true return 1 cfileinfodialog ondatachanged m_bdatachanged c list ctrlx c list ctrlx m pparent null m pmenu null m uidmenu uint 1 m broutemenucmdstomainframe false m uidaccel uint 1 m haccel null m isortcolumn 1 m uidhdrimglist uint 1 m sizehdrimglisticon cx 0 m sizehdrimglisticon cy 0 m ihdrimglistimages 0 m busehdrctrlsortbitmaps false m strfindtext m bfindmatchcase false m ifinddirection 1 m ifindcolumn 0 m pfnfinditem find item m lfinditemparam 0 clistctrlx clistctrlx m_pparent m_pmenu m_uidmenu m_broutemenucmdstomainframe m_uidaccel m_haccel m_isortcolumn m_uidhdrimglist m_sizehdrimglisticon m_sizehdrimglisticon m_ihdrimglistimages m_busehdrctrlsortbitmaps m_strfindtext m_bfindmatchcase m_ifinddirection m_ifindcolumn m_pfnfinditem finditem m_lfinditemparam c list ctrlx c list ctrlx clistctrlx clistctrlx void c list ctrlx enable hdr ctrl sort bitmaps bool b use hdr ctrl sort bitmaps if b use hdr ctrl sort bitmaps the app m ullcomctrlver makedllverull 6 0 0 0 m busehdrctrlsortbitmaps true else ifdef idb sort states set hdr img list idb sort states lcx sort state image width lcx sort state image height lcx sort state images else assert 0 endif clistctrlx enablehdrctrlsortbitmaps busehdrctrlsortbitmaps busehdrctrlsortbitmaps theapp m_ullcomctrlver m_busehdrctrlsortbitmaps idb_sort_states sethdrimglist idb_sort_states lcx_sort_state_image_width lcx_sort_state_image_height lcx_sort_state_images void c list ctrlx set hdr img list uint u resid int cx int cy int i images m uidhdrimglist u resid m sizehdrimglisticon cx cx m sizehdrimglisticon cy cy m ihdrimglistimages i images clistctrlx sethdrimglist uresid iimages m_uidhdrimglist uresid m_sizehdrimglisticon m_sizehdrimglisticon m_ihdrimglistimages iimages void c list ctrlx set sort column int i columns lcx column init p columns int i sort column unreferenced parameter i columns assert i sort column i columns m isortcolumn i sort column p columns m isortcolumn e sort order p columns m isortcolumn e dflt sort order update sort column i columns p columns clistctrlx setsortcolumn icolumns lcx_column_init pcolumns isortcolumn unreferenced_parameter icolumns isortcolumn icolumns m_isortcolumn isortcolumn pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn edfltsortorder updatesortcolumn icolumns pcolumns void c list ctrlx update sort column int i columns lcx column init p columns unreferenced parameter i columns assert m isortcolumn i columns update hdr ctrl sort bitmap m isortcolumn p columns m isortcolumn e sort order clistctrlx updatesortcolumn icolumns lcx_column_init pcolumns unreferenced_parameter icolumns m_isortcolumn icolumns updatehdrctrlsortbitmap m_isortcolumn pcolumns m_isortcolumn esortorder void c list ctrlx create columns int i columns lcx column init p columns insert column 0 t dummy lvcfmt left 0 for int i col 0 i col i columns i col c string str heading if p columns i col u head resid str heading get res string p columns i col u head resid if str heading is empty str heading p columns i col psz heading int i col width if p columns i col i width 0 i col width p columns i col i width else get the optimal column width if p columns i col psz sample int i width sample get string width p columns i col psz sample int i width header get string width str heading i width header 30 if using the comctl 6 0 header bitmaps up down arrows we need more space i col width 6 max i width sample i width header 6 left right margin if p columns i col u format lvcfmt right right justified text i col width 4 else i col width 0 lvcolumn lvc lvc mask lvcf text lvcf width lvcf fmt lvcf subitem lvc psz text const cast lptstr lpctstr str heading lvc cx i col width lvc fmt p columns i col u format lvc i sub item p columns i col i colid insert column p columns i col i colid 1 skip dummy column lvc delete column 0 clistctrlx createcolumns icolumns lcx_column_init pcolumns insertcolumn _t lvcfmt_left icol icol icolumns icol cstring strheading pcolumns icol uheadresid strheading getresstring pcolumns icol uheadresid strheading isempty strheading pcolumns icol pszheading icolwidth pcolumns icol iwidth icolwidth pcolumns icol iwidth pcolumns icol pszsample iwidthsample getstringwidth pcolumns icol pszsample iwidthheader getstringwidth strheading iwidthheader icolwidth __max iwidthsample iwidthheader pcolumns icol uformat lvcfmt_right icolwidth icolwidth lvcf_text lvcf_width lvcf_fmt lvcf_subitem psztext const_cast strheading icolwidth pcolumns icol uformat isubitem pcolumns icol icolid insertcolumn pcolumns icol icolid deletecolumn void c list ctrlx read column stats int i columns lcx column init p columns assert m strregkey is empty read column stats i columns p columns m strregkey clistctrlx readcolumnstats icolumns lcx_column_init pcolumns m_strregkey isempty readcolumnstats icolumns pcolumns m_strregkey void c list ctrlx read column stats int i columns lcx column init p columns lpctstr psz section read column stats i columns p columns psz section m strregprefix dword dw val the app get profile int psz section m strregprefix t sortcolumn 1 m isortcolumn short loword dw val if m isortcolumn 0 m isortcolumn i columns lcx sort order e sort order lcx sort order short hiword dw val if e sort order ascending e sort order descending p columns m isortcolumn e sort order e sort order if p columns m isortcolumn e sort order none p columns m isortcolumn e sort order p columns m isortcolumn e dflt sort order none p columns m isortcolumn e dflt sort order ascending else m isortcolumn 1 clistctrlx readcolumnstats icolumns lcx_column_init pcolumns pszsection readcolumnstats icolumns pcolumns pszsection m_strregprefix dwval theapp getprofileint pszsection m_strregprefix _t _sortcolumn m_isortcolumn dwval m_isortcolumn m_isortcolumn icolumns lcx_sort_order esortorder lcx_sort_order dwval esortorder esortorder pcolumns m_isortcolumn esortorder esortorder pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn edfltsortorder pcolumns m_isortcolumn edfltsortorder m_isortcolumn void c list ctrlx write column stats int i columns const lcx column init p columns assert m strregkey is empty write column stats i columns p columns m strregkey clistctrlx writecolumnstats icolumns lcx_column_init pcolumns m_strregkey isempty writecolumnstats icolumns pcolumns m_strregkey void c list ctrlx write column stats int i columns const lcx column init p columns lpctstr psz section write column stats this i columns p columns psz section m strregprefix dword dw val makelong m isortcolumn p columns m isortcolumn e sort order the app write profile int psz section m strregprefix t sortcolumn dw val clistctrlx writecolumnstats icolumns lcx_column_init pcolumns pszsection writecolumnstats icolumns pcolumns pszsection m_strregprefix dwval m_isortcolumn pcolumns m_isortcolumn esortorder theapp writeprofileint pszsection m_strregprefix _t _sortcolumn dwval void c list ctrlx init column orders int i columns const lcx column init p columns init column orders this i columns p columns clistctrlx initcolumnorders icolumns lcx_column_init pcolumns initcolumnorders icolumns pcolumns void c list ctrlx select all items set item state 1 lvis selected lvis selected clistctrlx selectallitems setitemstate lvis_selected lvis_selected void c list ctrlx deselect all items set item state 1 0 lvis selected clistctrlx deselectallitems setitemstate lvis_selected void c list ctrlx check selected items int n curr item assert get extended style lvs ex checkboxes first check if this item is selected lvitem lvi lvi i item n curr item lvi i sub item 0 lvi mask lvif state lvi state mask lvis selected get item lvi if item is not selected don t do anything if lvi state lvis selected return new check state will be reverse of the current state bool b check get check n curr item int n item 1 int n old item 1 while n item get next item n old item lvni selected 1 if n item n curr item set check n item b check n old item n item clistctrlx checkselecteditems ncurritem getextendedstyle lvs_ex_checkboxes iitem ncurritem isubitem lvif_state statemask lvis_selected getitem lvis_selected bcheck getcheck ncurritem nitem nolditem nitem getnextitem nolditem lvni_selected nitem ncurritem setcheck nitem bcheck nolditem nitem void c list ctrlx update sort order lpnmlistview pnmlv int i columns lcx column init p columns assert pnmlv i item 1 assert pnmlv i sub item 0 pnmlv i sub item i columns void i columns get sorting order for column if pnmlv i sub item m isortcolumn the sorting order is toggled only if the user has clicked on the same column which was used for the prev sorting like windows explorer if p columns m isortcolumn e sort order ascending p columns m isortcolumn e sort order descending else p columns m isortcolumn e sort order ascending else everytime the user has clicked a column which was not used for the prev sorting use the default sorting order like windows explorer resp ms outlook m isortcolumn pnmlv i sub item p columns m isortcolumn e sort order p columns m isortcolumn e dflt sort order update hdr ctrl sort bitmap m isortcolumn p columns m isortcolumn e sort order clistctrlx updatesortorder icolumns lcx_column_init pcolumns iitem isubitem isubitem icolumns icolumns isubitem m_isortcolumn pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn esortorder m_isortcolumn isubitem pcolumns m_isortcolumn esortorder pcolumns m_isortcolumn edfltsortorder updatehdrctrlsortbitmap m_isortcolumn pcolumns m_isortcolumn esortorder void c list ctrlx update hdr ctrl sort bitmap int i sorted column lcx sort order e sort order update the listview column headers to show the current sorting order c header ctrl p hdr ctrl get header ctrl if p hdr ctrl null int i columns p hdr ctrl get item count for int i 0 i i columns i hditem hdi hdi mask hdi format p hdr ctrl get item i hdi if i i sorted column if m busehdrctrlsortbitmaps hdi fmt hdf sortup hdf sortdown hdi fmt e sort order ascending hdf sortup hdf sortdown else if m uidhdrimglist uint 1 hdi mask hdi format hdi image hdi fmt hdf image hdf bitmap on right hdi i image e sort order ascending lcx idx sort img ascending lcx idx sort img descending p hdr ctrl set item i hdi else if m busehdrctrlsortbitmaps hdi fmt hdf sortup hdf sortdown else hdi fmt hdf image hdf bitmap on right p hdr ctrl set item i hdi clistctrlx updatehdrctrlsortbitmap isortedcolumn lcx_sort_order esortorder cheaderctrl phdrctrl getheaderctrl phdrctrl icolumns phdrctrl getitemcount icolumns hdi_format phdrctrl getitem isortedcolumn m_busehdrctrlsortbitmaps hdf_sortup hdf_sortdown esortorder hdf_sortup hdf_sortdown m_uidhdrimglist hdi_format hdi_image hdf_image hdf_bitmap_on_right iimage esortorder lcx_idx_sort_img_ascending lcx_idx_sort_img_descending phdrctrl setitem m_busehdrctrlsortbitmaps hdf_sortup hdf_sortdown hdf_image hdf_bitmap_on_right phdrctrl setitem void c list ctrlx update hdr image list if m uidhdrimglist uint 1 m sizehdrimglisticon cx 0 m sizehdrimglisticon cy 0 m ihdrimglistimages 0 update hdr image list this m imlhdr m uidhdrimglist m sizehdrimglisticon m ihdrimglistimages clistctrlx updatehdrimagelist m_uidhdrimglist m_sizehdrimglisticon m_sizehdrimglisticon m_ihdrimglistimages updatehdrimagelist m_imlhdr m_uidhdrimglist m_sizehdrimglisticon m_ihdrimglistimages void c list ctrlx apply image list himagelist himl send message lvm setimagelist lvsil small lparam himl if m imlhdr m himagelist null must again set the image list for the header control because lvm setimagelist always resets any already specified header control image lists get header ctrl set image list m imlhdr clistctrlx applyimagelist sendmessage lvm_setimagelist lvsil_small m_imlhdr m_himagelist lvm_setimagelist getheaderctrl setimagelist m_imlhdr void c list ctrlx on find start c list view search dlg dlg dlg m plistview this dlg m strfindtext m strfindtext dlg m isearchcolumn m ifindcolumn if dlg do modal idok dlg m strfindtext is empty return m strfindtext dlg m strfindtext m ifindcolumn dlg m isearchcolumn do find next true b show error clistctrlx onfindstart clistviewsearchdlg m_plistview m_strfindtext m_strfindtext m_isearchcolumn m_ifindcolumn domodal m_strfindtext isempty m_strfindtext m_strfindtext m_ifindcolumn m_isearchcolumn dofindnext bshowerror void c list ctrlx on find next do find next false b show error clistctrlx onfindnext dofindnext bshowerror void c list ctrlx on find prev int i start item get next item 1 lvni selected lvni focused if i start item 1 i start item 0 else i start item i start item m ifinddirection 1 1 do find i start item m ifinddirection false b show error clistctrlx onfindprev istartitem getnextitem lvni_selected lvni_focused istartitem istartitem istartitem istartitem m_ifinddirection dofind istartitem m_ifinddirection bshowerror void c list ctrlx do find next bool b show error int i start item get next item 1 lvni selected lvni focused if i start item 1 i start item 0 else i start item i start item m ifinddirection 1 1 do find i start item m ifinddirection b show error clistctrlx dofindnext bshowerror istartitem getnextitem lvni_selected lvni_focused istartitem istartitem istartitem istartitem m_ifinddirection dofind istartitem m_ifinddirection bshowerror void c list ctrlx do find int i start item int i direction 1 down 0 up bool b show error c wait cursor cur hourglass if i start item 0 message beep mb ok return int i num items i direction get item count 0 int i item i start item while i direction i item i num items i item 0 if m pfnfinditem this i item m lfinditemparam deselect all listview entries deselect all items select the found listview entry set item state i item lvis selected lvis focused lvis selected lvis focused set selection mark i item ensure visible i item false b partialok set focus return if i direction i item else i item if b show error afx message box t no matching entry found mb iconinformation else message beep mb ok clistctrlx dofind istartitem idirection bshowerror cwaitcursor curhourglass istartitem messagebeep mb_ok inumitems idirection getitemcount iitem istartitem idirection iitem inumitems iitem m_pfnfinditem iitem m_lfinditemparam deselectallitems setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark iitem ensurevisible iitem bpartialok setfocus idirection iitem iitem bshowerror afxmessagebox _t mb_iconinformation messagebeep mb_ok bool c list ctrlx pre translate message msg p msg if m haccel null if p msg message wm keyfirst p msg message wm keylast if we want to handle the vk return key we have to do that via accelerators if translate accelerator m hwnd m haccel p msg return true return c list ctrl pre translate message p msg clistctrlx pretranslatemessage pmsg m_haccel pmsg wm_keyfirst pmsg wm_keylast vk_return translateaccelerator m_hwnd m_haccel pmsg clistctrl pretranslatemessage pmsg void c list ctrlx pre subclass window c list ctrl pre subclass window if we want to handle the vk return key we have to do that via accelerators if m uidaccel uint 1 m haccel load accelerators afx get resource handle makeintresource m uidaccel assert m haccel clistctrlx presubclasswindow clistctrl presubclasswindow vk_return m_uidaccel m_haccel loadaccelerators afxgetresourcehandle m_uidaccel m_haccel void c list ctrlx on key down uint n char uint n rep cnt uint n flags if n char vk space if get extended style lvs ex checkboxes check all selected items int n curr item get next item 1 lvni focused if n curr item 1 get key state vk control 0 check selected items n curr item else if n char a get key state vk control 0x8000 ctrl a select all items if get style lvs singlesel 0 set item state 1 lvis selected lvis selected else if n char c get key state vk control 0x8000 ctrl c copy listview items to clipboard on copy 0 0 else if n char f get key state vk control 0x8000 ctrl f search item on find start else if n char vk f3 if get key state vk shift 0x8000 shift f3 search previous on find prev else f3 search next on find next c list ctrl on key down n char n rep cnt n flags clistctrlx onkeydown nchar nrepcnt nflags nchar vk_space getextendedstyle lvs_ex_checkboxes ncurritem getnextitem lvni_focused ncurritem getkeystate vk_control checkselecteditems ncurritem nchar getkeystate vk_control getstyle lvs_singlesel setitemstate lvis_selected lvis_selected nchar getkeystate vk_control oncopy nchar getkeystate vk_control onfindstart nchar vk_f3 getkeystate vk_shift onfindprev onfindnext clistctrl onkeydown nchar nrepcnt nflags void c list ctrlx on sys color change c list ctrl on sys color change update hdr image list clistctrlx onsyscolorchange clistctrl onsyscolorchange updatehdrimagelist void c list ctrlx on set focus c wnd p old wnd c list ctrl on set focus p old wnd set item focus this clistctrlx onsetfocus cwnd poldwnd clistctrl onsetfocus poldwnd setitemfocus void c list ctrlx on destroy c list ctrl on destroy m imlhdr delete image list clistctrlx ondestroy clistctrl ondestroy m_imlhdr deleteimagelist int c list ctrlx on create lpcreatestruct lp create struct if c list ctrl on create lp create struct 1 return 1 if we want to handle the vk return key we have to do that via accelerators if m uidaccel uint 1 m haccel load accelerators afx get resource handle makeintresource m uidaccel assert m haccel return 0 clistctrlx oncreate lpcreatestruct clistctrl oncreate lpcreatestruct vk_return m_uidaccel m_haccel loadaccelerators afxgetresourcehandle m_uidaccel m_haccel void c list ctrlx on init menu popup c menu p popup menu uint n index bool b sys menu c list ctrl on init menu popup p popup menu n index b sys menu if m broutemenucmdstomainframe note to enable the on update cmdui stuff for a dialog or a control we must explicitly call an appropriate function which was stolen from c frame wnd otherwise out on update cmdui callbacks would not be called wnd init menu popup update cmdui this p popup menu n index b sys menu clistctrlx oninitmenupopup cmenu ppopupmenu nindex bsysmenu clistctrl oninitmenupopup ppopupmenu nindex bsysmenu m_broutemenucmdstomainframe onupdatecmdui cframewnd onupdatecmdui wndinitmenupopupupdatecmdui ppopupmenu nindex bsysmenu void c list ctrlx on menu select uint n itemid uint n flags hmenu h sys menu c list ctrl on menu select n itemid n flags h sys menu if m broutemenucmdstomainframe to enable the display of the statusbar message strings for the currently selected menu item we must explicitly call an appropriate function which is stolen from c frame wnd wnd menu select update message text n itemid n flags h sys menu clistctrlx onmenuselect nitemid nflags hsysmenu clistctrl onmenuselect nitemid nflags hsysmenu m_broutemenucmdstomainframe cframewnd wndmenuselectupdatemessagetext nitemid nflags hsysmenu void c list ctrlx on context menu c wnd p wnd c point point if m uidmenu uint 1 m pmenu null default return c menu p menu null c menu menu popup if m pmenu null m uidmenu uint 1 if menu popup load menu m uidmenu p menu menu popup get sub menu 0 else p menu m pmenu if p menu null if the context menu was not opened using the right mouse button but the keyboard shift f10 get a useful position for the context menu if point x 1 point y 1 int i idx item get next item 1 lvni selected lvni focused if i idx item 1 rect rc if get item rect i idx item rc lvir bounds point x rc left get column width 0 2 point y rc top rc bottom rc top 2 client to screen point else point x 16 point y 32 client to screen point p menu track popup menu tpm leftalign tpm leftbutton tpm rightbutton point x point y m broutemenucmdstomainframe afx get main wnd m pparent m pparent this clistctrlx oncontextmenu cwnd pwnd cpoint m_uidmenu m_pmenu cmenu pmenu cmenu menupopup m_pmenu m_uidmenu menupopup loadmenu m_uidmenu pmenu menupopup getsubmenu pmenu m_pmenu pmenu iidxitem getnextitem lvni_selected lvni_focused iidxitem getitemrect iidxitem lvir_bounds getcolumnwidth clienttoscreen clienttoscreen pmenu trackpopupmenu tpm_leftalign tpm_leftbutton tpm_rightbutton m_broutemenucmdstomainframe afxgetmainwnd m_pparent m_pparent bool c list ctrlx on hdr begin drag uint nmhdr lresult if the app m ullcomctrlver makedllverull 6 0 0 0 c image list piml get header ctrl get image list if piml null piml set bk color get sys color color 3dshadow return false force default processing of notification clistctrlx onhdrbegindrag theapp m_ullcomctrlver cimagelist getheaderctrl getimagelist setbkcolor getsyscolor color_3dshadow bool c list ctrlx on hdr end drag uint nmhdr lresult if the app m ullcomctrlver makedllverull 6 0 0 0 c image list piml get header ctrl get image list if piml null piml set bk color get sys color color btnface return false force default processing of notification clistctrlx onhdrenddrag theapp m_ullcomctrlver cimagelist getheaderctrl getimagelist setbkcolor getsyscolor color_btnface lresult c list ctrlx on copy wparam w param lparam l param c string str report create item report this str report if str report is empty the app copy text to clipboard str report return 0 clistctrlx oncopy wparam lparam cstring strreport createitemreport strreport strreport isempty theapp copytexttoclipboard strreport c resizable page c meta data dlg idd 0 m pafiles null m bdatachanged false m taglist null m strcaption get res string ids meta data m psp psz title m strcaption m psp dw flags psp usetitle m pmenutags null m tags m pparent this m tags set registry key pref ini section m tags set registry prefix t metadatatags cresizablepage cmetadatadlg m_pafiles m_bdatachanged m_taglist m_strcaption getresstring ids_meta_data m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_pmenutags m_tags m_pparent m_tags setregistrykey pref_ini_section m_tags setregistryprefix _t metadatatags_ c meta data dlg c meta data dlg delete m pmenutags cmetadatadlg cmetadatadlg m_pmenutags void c meta data dlg set tag list kademlia tag list taglist m taglist taglist cmetadatadlg settaglist taglist m_taglist void c meta data dlg refresh data c wait cursor cur wait m tags delete all items m tags set redraw false int i meta tags 0 if m pafiles get size 1 lvitem lvi lvi mask lvif text lvi i item int max lvi i sub item meta data col name c string str buff get res string ids fd hash strip trailing collon str buff lvi psz text const cast lptstr lpctstr str buff int i item m tags insert item lvi if i item 0 lvi mask lvif text lvi i item i item str buff empty intentionally left blank as it s not a real meta tag lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col type m tags set item lvi str buff md4str static downcast c abstract file m pafiles 0 get file hash lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col value m tags set item lvi const c array c tag c tag a tags static downcast c abstract file m pafiles 0 get tags int i tags a tags get count for int i 0 i i tags i const c tag p tag a tags get at i lvitem lvi lvi mask lvif text lvi i item int max lvi i sub item meta data col name str buff get name p tag lvi psz text const cast lptstr lpctstr str buff int i item m tags insert item lvi if i item 0 lvi mask lvif text lvi i item i item str buff get type p tag get type lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col type m tags set item lvi str buff get value p tag lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col value m tags set item lvi i meta tags else if m taglist null const kademlia c kad tag p tag kademlia tag list const iterator it for it m taglist begin it m taglist end it p tag it c string str buff lvitem lvi lvi mask lvif text lvi i item int max lvi i sub item meta data col name str buff get name p tag lvi psz text const cast lptstr lpctstr str buff int i item m tags insert item lvi if i item 0 lvi mask lvif text lvi i item i item str buff get type p tag m type lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col type m tags set item lvi str buff get value p tag lvi psz text const cast lptstr lpctstr str buff lvi i sub item meta data col value m tags set item lvi i meta tags c string str tmp str tmp format t s u get res string ids metatags i meta tags set dlg item text idc total tags str tmp m tags set redraw cmetadatadlg refreshdata cwaitcursor curwait m_tags deleteallitems m_tags setredraw imetatags m_pafiles getsize lvif_text iitem int_max isubitem meta_data_col_name cstring strbuff getresstring ids_fd_hash striptrailingcollon strbuff psztext const_cast strbuff iitem m_tags insertitem iitem lvif_text iitem iitem strbuff psztext const_cast strbuff isubitem meta_data_col_type m_tags setitem strbuff static_downcast cabstractfile m_pafiles getfilehash psztext const_cast strbuff isubitem meta_data_col_value m_tags setitem carray ctag ctag atags static_downcast cabstractfile m_pafiles gettags itags atags getcount itags ctag ptag atags getat lvif_text iitem int_max isubitem meta_data_col_name strbuff getname ptag psztext const_cast strbuff iitem m_tags insertitem iitem lvif_text iitem iitem strbuff gettype ptag gettype psztext const_cast strbuff isubitem meta_data_col_type m_tags setitem strbuff getvalue ptag psztext const_cast strbuff isubitem meta_data_col_value m_tags setitem imetatags m_taglist ckadtag ptag taglist const_iterator m_taglist m_taglist ptag cstring strbuff lvif_text iitem int_max isubitem meta_data_col_name strbuff getname ptag psztext const_cast strbuff iitem m_tags insertitem iitem lvif_text iitem iitem strbuff gettype ptag m_type psztext const_cast strbuff isubitem meta_data_col_type m_tags setitem strbuff getvalue ptag psztext const_cast strbuff isubitem meta_data_col_value m_tags setitem imetatags cstring strtmp strtmp _t getresstring ids_metatags imetatags setdlgitemtext idc_total_tags strtmp m_tags setredraw void c meta data dlg do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc tags m tags cmetadatadlg dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_tags m_tags bool c meta data dlg on init dialog c resizable page on init dialog init window styles this add anchor idc tags top left bottom right add anchor idc total tags bottom left bottom right get dlg item idc total tags set window text get res string ids metatags m tags set extended style lvs ex fullrowselect lvs ex gridlines m tags read column stats arrsize acolumns acolumns m tags create columns arrsize acolumns acolumns m pmenutags new c menu if m pmenutags create popup menu m pmenutags append menu mf enabled mf string mp copyselected get res string ids copy m pmenutags append menu mf separator m pmenutags append menu mf enabled mf string mp selectall get res string ids selectall m tags m pmenu m pmenutags m tags m pparent this return true return true unless you set the focus to a control exception ocx property pages should return false cmetadatadlg oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_tags top_left bottom_right addanchor idc_total_tags bottom_left bottom_right getdlgitem idc_total_tags setwindowtext getresstring ids_metatags m_tags setextendedstyle lvs_ex_fullrowselect lvs_ex_gridlines m_tags readcolumnstats _acolumns _acolumns m_tags createcolumns _acolumns _acolumns m_pmenutags cmenu m_pmenutags createpopupmenu m_pmenutags appendmenu mf_enabled mf_string mp_copyselected getresstring ids_copy m_pmenutags appendmenu mf_separator m_pmenutags appendmenu mf_enabled mf_string mp_selectall getresstring ids_selectall m_tags m_pmenu m_pmenutags m_tags m_pparent bool c meta data dlg on set active if c resizable page on set active return false if m bdatachanged refresh data m bdatachanged false return true cmetadatadlg onsetactive cresizablepage onsetactive m_bdatachanged refreshdata m_bdatachanged void c meta data dlg on lvn keydown tags nmhdr pnmhdr lresult p result lpnmlvkeydown plv key down reinterpret cast lpnmlvkeydown pnmhdr if plv key down wv key c get key state vk control 0x8000 on copy tags p result 0 cmetadatadlg onlvnkeydowntags presult plvkeydown reinterpret_cast plvkeydown wvkey getkeystate vk_control oncopytags presult void c meta data dlg on copy tags c wait cursor cur wait int i selected 0 c string str data position pos m tags get first selected item position while pos int i item m tags get next selected item pos c string str value m tags get item text i item meta data col value if str value is empty if str data is empty str data t r n str data str value i selected if str data is empty if i selected 1 str data t r n the app copy text to clipboard str data cmetadatadlg oncopytags cwaitcursor curwait iselected cstring strdata m_tags getfirstselecteditemposition iitem m_tags getnextselecteditem cstring strvalue m_tags getitemtext iitem meta_data_col_value strvalue isempty strdata isempty strdata _t strdata strvalue iselected strdata isempty iselected strdata _t theapp copytexttoclipboard strdata void c meta data dlg on select all tags m tags select all items cmetadatadlg onselectalltags m_tags selectallitems void c meta data dlg on destroy m tags write column stats arrsize acolumns acolumns c resizable page on destroy cmetadatadlg ondestroy m_tags writecolumnstats _acolumns _acolumns cresizablepage ondestroy lresult c meta data dlg on data changed wparam lparam m bdatachanged true return 1 cmetadatadlg ondatachanged m_bdatachanged c resizable page ced2k link dlg idd ids cmt readall m pafiles null m bdatachanged false m strcaption get res string ids filelink m psp psz title m strcaption m psp dw flags psp usetitle cresizablepage ced2klinkdlg ids_cmt_readall m_pafiles m_bdatachanged m_strcaption getresstring ids_filelink m_psp psztitle m_strcaption m_psp dwflags psp_usetitle ced2k link dlg ced2k link dlg ced2klinkdlg ced2klinkdlg void ced2k link dlg update link c string str links c string str buffer const bool b hashset c button get dlg item idc ld hashsetche get check bst checked const bool bhtml c button get dlg item idc ld htmlche get check bst checked const bool b source c button get dlg item idc ld sourceche get check bst checked the app is connected the app is firewalled const bool b hostname c button get dlg item idc ld hostnameche get check bst checked the app is connected the app is firewalled the prefs get your hostname is empty the prefs get your hostname find t 1 const bool bem hash c button get dlg item idc ld emulehashche get check bst checked for int i 0 i m pafiles get size i if str links is empty str links t r n r n if bhtml str links t a href const c known file file static downcast c known file m pafiles i str links createed2k link file false if b hashset file get hash count 0 file get hash count file geted2k part hash count str links t p for uint j 0 j file get hash count j if j 0 str links t str links encode base16 file get part hash j 16 str links t if bem hash file getaich hashset has valid master hash file getaich hashset get status aich verified file getaich hashset get status aich hashsetcomplete str buffer format t h s file getaich hashset get master hash get string str links str buffer str links t if b hostname str buffer format t sources s i the prefs get your hostname the prefs get port str links str buffer else if b source uint32 dwid the app getid str buffer format t sources i i i i i uint8 dwid uint8 dwid 8 uint8 dwid 16 uint8 dwid 24 the prefs get port str links str buffer if bhtml str links t strip invalid filename chars file get file name true t a m ctrllinkedit set window text str links ced2klinkdlg updatelink cstring strlinks cstring strbuffer bhashset cbutton getdlgitem idc_ld_hashsetche getcheck bst_checked cbutton getdlgitem idc_ld_htmlche getcheck bst_checked bsource cbutton getdlgitem idc_ld_sourceche getcheck bst_checked theapp isconnected theapp isfirewalled bhostname cbutton getdlgitem idc_ld_hostnameche getcheck bst_checked theapp isconnected theapp isfirewalled theprefs getyourhostname isempty theprefs getyourhostname _t bemhash cbutton getdlgitem idc_ld_emulehashche getcheck bst_checked m_pafiles getsize strlinks isempty strlinks _t strlinks _t cknownfile static_downcast cknownfile m_pafiles strlinks createed2klink bhashset gethashcount gethashcount geted2kparthashcount strlinks _t gethashcount strlinks _t strlinks encodebase16 getparthash strlinks _t bemhash getaichhashset hasvalidmasterhash getaichhashset getstatus aich_verified getaichhashset getstatus aich_hashsetcomplete strbuffer _t getaichhashset getmasterhash getstring strlinks strbuffer strlinks _t bhostname strbuffer _t theprefs getyourhostname theprefs getport strlinks strbuffer bsource theapp strbuffer _t theprefs getport strlinks strbuffer strlinks _t stripinvalidfilenamechars getfilename _t m_ctrllinkedit setwindowtext strlinks bool ced2k link dlg on init dialog c resizable page on init dialog init window styles this add anchor idc ld linkgroup top left bottom right add anchor idc ld linkedi top left bottom right add anchor idc ld clipboardbut bottom right add anchor idc ld basicgroup bottom left bottom right add anchor idc ld sourceche bottom left bottom left add anchor idc ld emulehashche bottom left bottom left add anchor idc ld advancedgroup bottom left bottom right add anchor idc ld htmlche bottom left bottom left add anchor idc ld hashsetche bottom left bottom left add anchor idc ld hostnameche bottom left bottom left enabled disable checkbox depending on situation if the app is connected the app is firewalled get dlg item idc ld sourceche enable window true else get dlg item idc ld sourceche enable window false c button get dlg item idc ld sourceche set check bst unchecked if the app is connected the app is firewalled the prefs get your hostname is empty the prefs get your hostname find t 1 get dlg item idc ld hostnameche enable window true else get dlg item idc ld hostnameche enable window false c button get dlg item idc ld hostnameche set check bst unchecked localize return true ced2klinkdlg oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_ld_linkgroup top_left bottom_right addanchor idc_ld_linkedi top_left bottom_right addanchor idc_ld_clipboardbut bottom_right addanchor idc_ld_basicgroup bottom_left bottom_right addanchor idc_ld_sourceche bottom_left bottom_left addanchor idc_ld_emulehashche bottom_left bottom_left addanchor idc_ld_advancedgroup bottom_left bottom_right addanchor idc_ld_htmlche bottom_left bottom_left addanchor idc_ld_hashsetche bottom_left bottom_left addanchor idc_ld_hostnameche bottom_left bottom_left theapp isconnected theapp isfirewalled getdlgitem idc_ld_sourceche enablewindow getdlgitem idc_ld_sourceche enablewindow cbutton getdlgitem idc_ld_sourceche setcheck bst_unchecked theapp isconnected theapp isfirewalled theprefs getyourhostname isempty theprefs getyourhostname _t getdlgitem idc_ld_hostnameche enablewindow getdlgitem idc_ld_hostnameche enablewindow cbutton getdlgitem idc_ld_hostnameche setcheck bst_unchecked void ced2k link dlg do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc ld linkedi m ctrllinkedit ced2klinkdlg dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_ld_linkedi m_ctrllinkedit bool ced2k link dlg on set active if c resizable page on set active return false if m bdatachanged hashsetlink check if at least one file has a hasset bool b show false for int i 0 i m pafiles get size i const c known file file static downcast c known file m pafiles i if file get hash count 0 file get hash count file geted2k part hash count continue b show true break get dlg item idc ld hashsetche enable window b show if b show c button get dlg item idc ld hashsetche set check bst unchecked aich hash check if at least one file has a valid hash b show false for int i 0 i m pafiles get size i const c known file file static downcast c known file m pafiles i if file getaich hashset has valid master hash file getaich hashset get status aich verified file getaich hashset get status aich hashsetcomplete b show true break get dlg item idc ld emulehashche enable window b show if b show c button get dlg item idc ld emulehashche set check bst unchecked else c button get dlg item idc ld emulehashche set check bst checked update link m bdatachanged false return true ced2klinkdlg onsetactive cresizablepage onsetactive m_bdatachanged bshow m_pafiles getsize cknownfile static_downcast cknownfile m_pafiles gethashcount gethashcount geted2kparthashcount bshow getdlgitem idc_ld_hashsetche enablewindow bshow bshow cbutton getdlgitem idc_ld_hashsetche setcheck bst_unchecked bshow m_pafiles getsize cknownfile static_downcast cknownfile m_pafiles getaichhashset hasvalidmasterhash getaichhashset getstatus aich_verified getaichhashset getstatus aich_hashsetcomplete bshow getdlgitem idc_ld_emulehashche enablewindow bshow bshow cbutton getdlgitem idc_ld_emulehashche setcheck bst_unchecked cbutton getdlgitem idc_ld_emulehashche setcheck bst_checked updatelink m_bdatachanged bool ced2k link dlg on command wparam w param lparam l param if loword w param idcancel return send message get parent m hwnd wm command w param l param return c resizable page on command w param l param ced2klinkdlg oncommand wparam lparam wparam sendmessage getparent m_hwnd wm_command wparam lparam cresizablepage oncommand wparam lparam void ced2k link dlg on bn clicked clipboard c string str buffer m ctrllinkedit get window text str buffer the app copy text to clipboard str buffer ced2klinkdlg onbnclickedclipboard cstring strbuffer m_ctrllinkedit getwindowtext strbuffer theapp copytexttoclipboard strbuffer void ced2k link dlg on settings change update link ced2klinkdlg onsettingschange updatelink lresult ced2k link dlg on data changed wparam lparam m bdatachanged true return 1 ced2klinkdlg ondatachanged m_bdatachanged c combo box ex2 c combo box ex2 ccomboboxex2 ccomboboxex2 c combo box ex2 c combo box ex2 ccomboboxex2 ccomboboxex2 int c combo box ex2 add item lpctstr psz text int i image comboboxexitem cbi 0 cbi mask cbeif text cbi i item 1 cbi psz text lptstr psz text if i image 1 cbi mask cbeif image cbeif selectedimage cbi i image i image cbi i selected image i image return insert item cbi ccomboboxex2 additem psztext iimage cbeif_text iitem psztext psztext iimage cbeif_image cbeif_selectedimage iimage iimage iselectedimage iimage insertitem bool c combo box ex2 select string lpctstr psz text c combo box select string seems also not to work c combo box pctrlcb get combo box ctrl if pctrlcb null int i count pctrlcb get count for int i 0 i i count i c string str item pctrlcb getlb text i str item if str item psz text set cur sel i get parent send message wm command makelong word get window long m hwnd gwl id cbn selchange lparam m hwnd return true return false ccomboboxex2 selectstring psztext ccombobox selectstring ccombobox getcomboboxctrl icount getcount icount cstring stritem getlbtext stritem stritem psztext setcursel getparent sendmessage wm_command getwindowlong m_hwnd gwl_id cbn_selchange m_hwnd bool c combo box ex2 select item data stringa lpcstr psz text c combo box pctrlcb get combo box ctrl if pctrlcb null int i count pctrlcb get count for int i 0 i i count i void pv item data get item data ptr i if pv item data strcmp lpcstr pv item data psz text 0 set cur sel i get parent send message wm command makelong word get window long m hwnd gwl id cbn selchange lparam m hwnd return true return false ccomboboxex2 selectitemdatastringa psztext ccombobox getcomboboxctrl icount getcount icount pvitemdata getitemdataptr pvitemdata pvitemdata psztext setcursel getparent sendmessage wm_command getwindowlong m_hwnd gwl_id cbn_selchange m_hwnd bool c combo box ex2 pre translate message msg p msg there seems to be no way that we get the wm chartoitem for this control assert p msg message wm chartoitem if p msg message wm keydown uint u char map virtual key p msg w param 2 if u char 0 c combo box select string seems also not to work c combo box pctrlcb get combo box ctrl if pctrlcb null int i count pctrlcb get count for int i 0 i i count i c string str item pctrlcb getlb text i str item if str item is empty continue those casts are indeed all needed to get that thing at least running correctly for ansi code pages if that will also work for mbcs code pages has to be tested uint u first char uint tuchar str item 0 uint u first char lower uint tuchar totlower tint u first char uint u the char uint tuchar totlower tint uint u char if u first char lower u the char set cur sel i get parent send message wm command makelong word get window long m hwnd gwl id cbn selchange lparam m hwnd return true return c combo box ex pre translate message p msg ccomboboxex2 pretranslatemessage pmsg wm_chartoitem pmsg wm_chartoitem pmsg wm_keydown uchar mapvirtualkey pmsg wparam uchar ccombobox selectstring ccombobox getcomboboxctrl icount getcount icount cstring stritem getlbtext stritem stritem isempty ufirstchar _tuchar stritem ufirstcharlower _tuchar _totlower _tint ufirstchar uthechar _tuchar _totlower _tint uchar ufirstcharlower uthechar setcursel getparent sendmessage wm_command getwindowlong m_hwnd gwl_id cbn_selchange m_hwnd ccomboboxex pretranslatemessage pmsg c comment list ctrl c comment list ctrl c list ctrl item walk this ccommentlistctrl ccommentlistctrl clistctrlitemwalk c comment list ctrl c comment list ctrl ccommentlistctrl ccommentlistctrl void c comment list ctrl add item c up down client client lvfindinfo find find flags lvfi param find l param lparam client int i item find item find if i item 1 do not try to access the client object after inserting this item it is possible that the object is deleted int index insert item lvif text lvif param 0 client get user name 0 0 1 lparam client set item text index 1 client get client filename set item text index 2 get rate string client get file rating set item text index 3 client get file comment ccommentlistctrl additem cupdownclient lvfi_param lparam iitem finditem iitem insertitem lvif_text lvif_param getusername setitemtext getclientfilename setitemtext getratestring getfilerating setitemtext getfilecomment void c comment list ctrl add item kademlia c entry entry lvfindinfo find find flags lvfi param find l param lparam entry int i item find item find if i item 1 do not try to access the entry object after inserting this item it is possible that the object is deleted int index insert item lvif text lvif param 0 lpctstr t 0 0 1 lparam entry set item text index 1 entry m filename set item text index 2 get rate string uint entry get int tag value tag filerating set item text index 3 entry get str tag value tag description ccommentlistctrl additem centry lvfi_param lparam iitem finditem iitem insertitem lvif_text lvif_param _t setitemtext m_filename setitemtext getratestring getinttagvalue tag_filerating setitemtext getstrtagvalue tag_description void c comment list ctrl on context menu c wnd p wnd c point point uint flag mf string if get next item 1 lvis selected lvis focused 1 flag mf grayed c title menu popup menu popup menu create popup menu popup menu append menu mf string flag mp message get res string ids cmt copyclipboard get popup menu pos this point popup menu track popup menu tpm leftalign tpm rightbutton point x point y this verify popup menu destroy menu ccommentlistctrl oncontextmenu cwnd pwnd cpoint mf_string getnextitem lvis_selected lvis_focused mf_grayed ctitlemenu popupmenu popupmenu createpopupmenu popupmenu appendmenu mf_string mp_message getresstring ids_cmt_copyclipboard getpopupmenupos popupmenu trackpopupmenu tpm_leftalign tpm_rightbutton popupmenu destroymenu bool c comment list ctrl on command wparam w param lparam l param int i sel get next item 1 lvis selected lvis focused if i sel 1 switch w param case mp message the app copy text to clipboard get item text i sel 3 return true return c mule list ctrl on command w param l param ccommentlistctrl oncommand wparam lparam isel getnextitem lvis_selected lvis_focused isel wparam mp_message theapp copytexttoclipboard getitemtext isel cmulelistctrl oncommand wparam lparam c resizable page c comment dialog idd 0 m pafiles null m bdatachanged false m strcaption get res string ids comment m psp psz title m strcaption m psp dw flags psp usetitle m bmergedcomment false m bself false m timer 0 cresizablepage ccommentdialog m_pafiles m_bdatachanged m_strcaption getresstring ids_comment m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_bmergedcomment m_bself m_timer c comment dialog c comment dialog ccommentdialog ccommentdialog void c comment dialog do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc ratelist m ratebox ddx control pdx idc lst m lstcomments ccommentdialog dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_ratelist m_ratebox ddx_control idc_lst m_lstcomments bool c comment dialog on init dialog c resizable page on init dialog init window styles this add anchor idc lst top left bottom right add anchor idc cmt lquest top left top right add anchor idc cmt laide top left top right add anchor idc cmt text top left top right add anchor idc ratequest top left top right add anchor idc ratehelp top left top right add anchor idc usercomments top left bottom right add anchor idc reset top right add anchor idc searchkad bottom right m lstcomments init localize start time for calling refresh data verify m timer set timer 301 5000 0 null return true ccommentdialog oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_lst top_left bottom_right addanchor idc_cmt_lquest top_left top_right addanchor idc_cmt_laide top_left top_right addanchor idc_cmt_text top_left top_right addanchor idc_ratequest top_left top_right addanchor idc_ratehelp top_left top_right addanchor idc_usercomments top_left bottom_right addanchor idc_reset top_right addanchor idc_searchkad bottom_right m_lstcomments refreshdata m_timer settimer bool c comment dialog on set active if c resizable page on set active return false if m bdatachanged int i rating 1 m bmergedcomment false c string str comment for int i 0 i m pafiles get size i c known file file static downcast c known file m pafiles i if i 0 str comment file get file comment i rating file get file rating else if m bmergedcomment str comment compare file get file comment 0 str comment empty m bmergedcomment true if i rating 1 uint i rating file get file rating i rating 1 m bself true set dlg item text idc cmt text str comment c edit get dlg item idc cmt text set limit text maxfilecommentlen m ratebox set cur sel i rating m bself false m bdatachanged false refresh data return true ccommentdialog onsetactive cresizablepage onsetactive m_bdatachanged irating m_bmergedcomment cstring strcomment m_pafiles getsize cknownfile static_downcast cknownfile m_pafiles strcomment getfilecomment irating getfilerating m_bmergedcomment strcomment getfilecomment strcomment m_bmergedcomment irating irating getfilerating irating m_bself setdlgitemtext idc_cmt_text strcomment cedit getdlgitem idc_cmt_text setlimittext m_ratebox setcursel irating m_bself m_bdatachanged refreshdata bool c comment dialog on apply if m bdatachanged c string str comment get dlg item idc cmt text get window text str comment int i rating m ratebox get cur sel for int i 0 i m pafiles get size i c known file file static downcast c known file m pafiles i if str comment is empty m bmergedcomment file set file comment str comment if i rating 1 file set file rating i rating return c resizable page on apply ccommentdialog onapply m_bdatachanged cstring strcomment getdlgitem idc_cmt_text getwindowtext strcomment irating m_ratebox getcursel m_pafiles getsize cknownfile static_downcast cknownfile m_pafiles strcomment isempty m_bmergedcomment setfilecomment strcomment irating setfilerating irating cresizablepage onapply void c comment dialog refresh data bool delete old if delete old m lstcomments delete all items for int i 0 i m pafiles get size i c abstract file file static downcast c abstract file m pafiles i if file is part file for position pos c part file file srclist get head position pos null c up down client cur src c part file file srclist get next pos if cur src has file rating cur src get file comment is empty m lstcomments add item cur src const c typed ptr list c ptr list kademlia c entry list file get notes for position pos list get head position pos null kademlia c entry entry list get next pos m lstcomments add item entry ccommentdialog refreshdata deleteold deleteold m_lstcomments deleteallitems m_pafiles getsize cabstractfile static_downcast cabstractfile m_pafiles ispartfile cpartfile getheadposition cupdownclient cur_src cpartfile getnext cur_src hasfilerating cur_src getfilecomment isempty m_lstcomments additem cur_src ctypedptrlist cptrlist centry getnotes getheadposition centry getnext m_lstcomments additem void c comment dialog on bn clicked search kad if kademlia c kademlia is connected for int i 0 i m pafiles get size i c abstract file file static downcast c abstract file m pafiles i if file if kademlia c search manager prepare lookup kademlia c search notes true kademlia cu int128 file get file hash afx message box get res string ids kadsearchalready mb ok mb iconinformation 0 ccommentdialog onbnclickedsearchkad ckademlia isconnected m_pafiles getsize cabstractfile static_downcast cabstractfile m_pafiles csearchmanager preparelookup csearch cuint128 getfilehash afxmessagebox getresstring ids_kadsearchalready mb_ok mb_iconinformation void c comment dialog on bn clicked reset set dlg item text idc cmt text t m bmergedcomment false m ratebox set cur sel 0 ccommentdialog onbnclickedreset setdlgitemtext idc_cmt_text _t m_bmergedcomment m_ratebox setcursel lresult c comment dialog on data changed wparam lparam m bdatachanged true return 1 ccommentdialog ondatachanged m_bdatachanged void c comment dialog on en change cmt text if m bself set modified ccommentdialog onenchangecmttext m_bself setmodified void c comment dialog on cbn selendok ratelist if m bself set modified ccommentdialog oncbnselendokratelist m_bself setmodified void c comment dialog on cbn selchange ratelist if m bself set modified ccommentdialog oncbnselchangeratelist m_bself setmodified void c comment dialog on destroy m imlrating delete image list c resizable page on destroy if m timer kill timer m timer m timer 0 ccommentdialog ondestroy m_imlrating deleteimagelist cresizablepage ondestroy m_timer killtimer m_timer m_timer void c comment dialog on timer uint nid event refresh data false ccommentdialog ontimer nidevent refreshdata c web services c web services m tdefservicesfilelastmodified 0 cwebservices cwebservices m_tdefservicesfilelastmodified c string c web services get default services file const return the prefs get config dir t webservices dat cstring cwebservices getdefaultservicesfile theprefs getconfigdir _t int c web services read all services remove all services c string str file path get default services file file read file tfsopen str file path t r sh denywr if read file null c string name url sbuffer while feof read file tchar buffer 1024 if fgetts buffer arrsize buffer read file null break sbuffer buffer ignore comments too short lines if sbuffer get at 0 t sbuffer get at 0 t sbuffer get length 5 continue int i pos sbuffer find t if i pos 0 c string str url template sbuffer right sbuffer get length i pos 1 trim if str url template is empty bool b file macros false static const lpctstr apszmacros t hashid t filesize t filename t name t cleanfilename t cleanname for int i 0 i arrsize apszmacros i if str url template find apszmacros i 1 b file macros true break s ed2k link service svc svc u menuid mp weburl m aservices get count svc str menu label sbuffer left i pos trim svc str url str url template svc b file macros b file macros m aservices add svc fclose read file struct stat st if tstat str file path st 0 m tdefservicesfilelastmodified st st mtime return m aservices get count cwebservices readallservices removeallservices cstring strfilepath getdefaultservicesfile readfile _tfsopen strfilepath _t _sh_denywr readfile cstring readfile _fgetts readfile getat _t getat _t getlength ipos _t ipos cstring strurltemplate getlength ipos strurltemplate isempty bfilemacros _apszmacros _t _t _t _t _t _t _apszmacros strurltemplate _apszmacros bfilemacros sed2klinkservice umenuid mp_weburl m_aservices getcount strmenulabel ipos strurl strurltemplate bfilemacros bfilemacros m_aservices readfile _stat _tstat strfilepath m_tdefservicesfilelastmodified st_mtime m_aservices getcount void c web services remove all services m aservices remove all m tdefservicesfilelastmodified 0 cwebservices removeallservices m_aservices removeall m_tdefservicesfilelastmodified int c web services get all menu entries c title menu p menu dword dw flags if m aservices get count 0 read all services else struct stat st if tstat get default services file st 0 st st mtime m tdefservicesfilelastmodified read all services int i menu entries 0 for int i 0 i m aservices get count i const s ed2k link service r svc m aservices get at i if dw flags websvc gen urls r svc b file macros continue if dw flags websvc file urls r svc b file macros continue if p menu append menu mf string mp weburl i r svc str menu label t web i menu entries return i menu entries cwebservices getallmenuentries ctitlemenu pmenu dwflags m_aservices getcount readallservices _stat _tstat getdefaultservicesfile st_mtime m_tdefservicesfilelastmodified readallservices imenuentries m_aservices getcount sed2klinkservice rsvc m_aservices getat dwflags websvc_gen_urls rsvc bfilemacros dwflags websvc_file_urls rsvc bfilemacros pmenu appendmenu mf_string mp_weburl rsvc strmenulabel _t imenuentries imenuentries bool c web services runurl const c abstract file file uint u menuid for int i 0 i m aservices get count i const s ed2k link service r svc m aservices get at i if r svc u menuid u menuid c string str url template r svc str url if file null convert hash to hexadecimal text and add it to the url str url template replace t hashid md4str file get file hash add file size to the url c string temp temp format t i64u file get file size str url template replace t filesize temp add complete filename to the url str url template replace t filename encodeurl query param file get file name add basename to the url c string str base name file get file name path remove extension str base name get buffer str base name get length str base name release buffer str url template replace t name encodeurl query param str base name add cleaned up complete filename to the url str url template replace t cleanfilename encodeurl query param cleanup filename file get file name add cleaned up basename to the url str url template replace t cleanname encodeurl query param cleanup filename str base name false open url trace t starting url s n str url template return int shell execute null null str url template null the prefs get app dir sw showdefault 32 return false cwebservices cabstractfile umenuid m_aservices getcount sed2klinkservice rsvc m_aservices getat rsvc umenuid umenuid cstring strurltemplate rsvc strurl strurltemplate _t getfilehash cstring _t getfilesize strurltemplate _t strurltemplate _t encodeurlqueryparam getfilename cstring strbasename getfilename pathremoveextension strbasename getbuffer strbasename getlength strbasename releasebuffer strurltemplate _t encodeurlqueryparam strbasename strurltemplate _t encodeurlqueryparam cleanupfilename getfilename strurltemplate _t encodeurlqueryparam cleanupfilename strbasename _t strurltemplate shellexecute strurltemplate theprefs getappdir sw_showdefault void c web services edit shell execute null t open the prefs get txt editor t the prefs get config dir t webservices dat null sw show cwebservices shellexecute _t theprefs gettxteditor _t theprefs getconfigdir _t sw_show m pcollection null m bsharedfiles false m_pcollection m_bsharedfiles c collection create dialog c collection create dialog if m icownd verify destroy icon m icownd ccollectioncreatedialog ccollectioncreatedialog m_icownd destroyicon m_icownd void c collection create dialog set collection c collection p collection bool create if p collection assert 0 return m pcollection p collection m bcreatemode create ccollectioncreatedialog setcollection ccollection pcollection pcollection m_pcollection pcollection m_bcreatemode void c collection create dialog do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc collectionlistctrl m collectionlistctrl ddx control pdx idc collectionavaillist m collectionavaillistctrl ddx control pdx idc collectionnameedit m collectionnameedit ddx control pdx idc collectionviewsharebutton m collectionviewsharebutton ddx control pdx idc collectionadd m addcollectionbutton ddx control pdx idc collectionremove m removecollectionbutton ddx control pdx idc collectionlistlabel m collectionlistlabel ddx control pdx idc ccoll save m savebutton ddx control pdx idc ccoll cancel m cancelbutton ddx control pdx idc collectionlisticon m collectionlisticon ddx control pdx idc collectionsourcelisticon m collectionsourcelisticon ddx control pdx idc collectioncreatesigncheck m collectioncreatesignnamekeycheck ddx control pdx idc collectioncreateformat m collectioncreateformatcheck ccollectioncreatedialog dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_collectionlistctrl m_collectionlistctrl ddx_control idc_collectionavaillist m_collectionavaillistctrl ddx_control idc_collectionnameedit m_collectionnameedit ddx_control idc_collectionviewsharebutton m_collectionviewsharebutton ddx_control idc_collectionadd m_addcollectionbutton ddx_control idc_collectionremove m_removecollectionbutton ddx_control idc_collectionlistlabel m_collectionlistlabel ddx_control idc_ccoll_save m_savebutton ddx_control idc_ccoll_cancel m_cancelbutton ddx_control idc_collectionlisticon m_collectionlisticon ddx_control idc_collectionsourcelisticon m_collectionsourcelisticon ddx_control idc_collectioncreatesigncheck m_collectioncreatesignnamekeycheck ddx_control idc_collectioncreateformat m_collectioncreateformatcheck bool c collection create dialog on init dialog void c dialog on init dialog if m pcollection assert 0 return true set icon m icownd the app load icon t collection false if m bcreatemode set window text get res string ids createcollection else set window text get res string ids modifycollection m collectionlistctrl init t collection creater m collectionavaillistctrl init t collection createl m addcollectionbutton set icon the app load icon t forward m removecollectionbutton set icon the app load icon t back m collectionlisticon set icon the app load icon t collection m collectionsourcelisticon set icon the app load icon t shared files list m collectionlistlabel set window text get res string ids collectionlist m savebutton set window text get res string ids save m cancelbutton set window text get res string ids cancel m collectioncreatesignnamekeycheck set window text get res string ids coll sign m collectioncreateformatcheck set window text get res string ids coll textformat set dlg item text idc ccoll static name get res string ids sw name t set dlg item text idc ccoll basicoptions get res string ids ld basicopt set dlg item text idc ccoll advancedoptions get res string ids ld advancedopt add anchor idc collectionavaillist top left bottom center add anchor idc collectionlistctrl top center bottom right add anchor idc collectionlistlabel top center add anchor idc collectionlisticon top center add anchor idc collectionadd top center add anchor idc collectionremove top center add anchor idc ccoll save bottom right add anchor idc ccoll cancel bottom right add anchor idc ccoll basicoptions bottom left bottom right add anchor idc ccoll advancedoptions bottom left bottom right add anchor idc ccoll static name bottom left add anchor idc collectionnameedit bottom left bottom right add anchor idc collectioncreateformat bottom left bottom right add anchor idc collectioncreatesigncheck bottom left bottom right position pos m pcollection m collectionfilesmap get start position c collection file p collection file cs key key while pos null m pcollection m collectionfilesmap get next assoc pos key p collection file m collectionlistctrl add file to list p collection file on bn clicked collectionviewsharebutton m collectionnameedit set window text cleanup filename m pcollection m scollectionname m collectioncreateformatcheck set check m pcollection m btextformat on bn clicked collectioncreateformat get dlg item idc ccoll save enable window m collectionlistctrl get item count 0 return true ccollectioncreatedialog oninitdialog cdialog oninitdialog m_pcollection seticon m_icownd theapp loadicon _t m_bcreatemode setwindowtext getresstring ids_createcollection setwindowtext getresstring ids_modifycollection m_collectionlistctrl _t collectioncreater m_collectionavaillistctrl _t collectioncreatel m_addcollectionbutton seticon theapp loadicon _t m_removecollectionbutton seticon theapp loadicon _t m_collectionlisticon seticon theapp loadicon _t m_collectionsourcelisticon seticon theapp loadicon _t sharedfileslist m_collectionlistlabel setwindowtext getresstring ids_collectionlist m_savebutton setwindowtext getresstring ids_save m_cancelbutton setwindowtext getresstring ids_cancel m_collectioncreatesignnamekeycheck setwindowtext getresstring ids_coll_sign m_collectioncreateformatcheck setwindowtext getresstring ids_coll_textformat setdlgitemtext idc_ccoll_static_name getresstring ids_sw_name _t setdlgitemtext idc_ccoll_basicoptions getresstring ids_ld_basicopt setdlgitemtext idc_ccoll_advancedoptions getresstring ids_ld_advancedopt addanchor idc_collectionavaillist top_left bottom_center addanchor idc_collectionlistctrl top_center bottom_right addanchor idc_collectionlistlabel top_center addanchor idc_collectionlisticon top_center addanchor idc_collectionadd top_center addanchor idc_collectionremove top_center addanchor idc_ccoll_save bottom_right addanchor idc_ccoll_cancel bottom_right addanchor idc_ccoll_basicoptions bottom_left bottom_right addanchor idc_ccoll_advancedoptions bottom_left bottom_right addanchor idc_ccoll_static_name bottom_left addanchor idc_collectionnameedit bottom_left bottom_right addanchor idc_collectioncreateformat bottom_left bottom_right addanchor idc_collectioncreatesigncheck bottom_left bottom_right m_pcollection m_collectionfilesmap getstartposition ccollectionfile pcollectionfile cskey m_pcollection m_collectionfilesmap getnextassoc pcollectionfile m_collectionlistctrl addfiletolist pcollectionfile onbnclickedcollectionviewsharebutton m_collectionnameedit setwindowtext cleanupfilename m_pcollection m_scollectionname m_collectioncreateformatcheck setcheck m_pcollection m_btextformat onbnclickedcollectioncreateformat getdlgitem idc_ccoll_save enablewindow m_collectionlistctrl getitemcount void c collection create dialog add selected files void c typed ptr list c ptr list c known file known file list position pos m collectionavaillistctrl get first selected item position while pos null int index m collectionavaillistctrl get next selected item pos if index 0 known file list add tail c known file m collectionavaillistctrl get item data index while known file list get count 0 c abstract file p abstract file known file list remove head c collection file p collection file m pcollection add file to collection p abstract file true if p collection file m collectionlistctrl add file to list p collection file get dlg item idc ccoll save enable window m collectionlistctrl get item count 0 ccollectioncreatedialog addselectedfiles ctypedptrlist cptrlist cknownfile knownfilelist m_collectionavaillistctrl getfirstselecteditemposition m_collectionavaillistctrl getnextselecteditem knownfilelist addtail cknownfile m_collectionavaillistctrl getitemdata knownfilelist getcount cabstractfile pabstractfile knownfilelist removehead ccollectionfile pcollectionfile m_pcollection addfiletocollection pabstractfile pcollectionfile m_collectionlistctrl addfiletolist pcollectionfile getdlgitem idc_ccoll_save enablewindow m_collectionlistctrl getitemcount void c collection create dialog remove selected files void c typed ptr list c ptr list c collection file collection file list position pos m collectionlistctrl get first selected item position while pos null int index m collectionlistctrl get next selected item pos if index 0 collection file list add tail c collection file m collectionlistctrl get item data index while collection file list get count 0 c collection file p collection file collection file list remove head m collectionlistctrl remove file from list p collection file m pcollection remove file from collection p collection file get dlg item idc ccoll save enable window m collectionlistctrl get item count 0 ccollectioncreatedialog removeselectedfiles ctypedptrlist cptrlist ccollectionfile collectionfilelist m_collectionlistctrl getfirstselecteditemposition m_collectionlistctrl getnextselecteditem collectionfilelist addtail ccollectionfile m_collectionlistctrl getitemdata collectionfilelist getcount ccollectionfile pcollectionfile collectionfilelist removehead m_collectionlistctrl removefilefromlist pcollectionfile m_pcollection removefilefromcollection pcollectionfile getdlgitem idc_ccoll_save enablewindow m_collectionlistctrl getitemcount void c collection create dialog update avail files void m collectionavaillistctrl delete all items c map cc key const cc key c known file c known file files map if m bsharedfiles the app sharedfiles copy shared file map files map else the app knownfiles copy known file map files map position pos files map get start position c known file p known file cc key key while pos null files map get next assoc pos key p known file m collectionavaillistctrl add file to list p known file ccollectioncreatedialog updateavailfiles m_collectionavaillistctrl deleteallitems cmap cckey cckey cknownfile cknownfile files_map m_bsharedfiles theapp copysharedfilemap files_map theapp copyknownfilemap files_map files_map getstartposition cknownfile pknownfile cckey files_map getnextassoc pknownfile m_collectionavaillistctrl addfiletolist pknownfile void c collection create dialog on bn clicked collectionremove remove selected files ccollectioncreatedialog onbnclickedcollectionremove removeselectedfiles void c collection create dialog on bn clicked collectionadd add selected files ccollectioncreatedialog onbnclickedcollectionadd addselectedfiles void c collection create dialog on bn clicked ok some users have noted that the collection can at times save a collection with a invalid name on en killfocus collectionnameedit c string s file name m collectionnameedit get window text s file name if s file name is empty m pcollection m scollectionauthorname t m pcollection set collection author key null 0 m pcollection m scollectionname s file name m pcollection m btextformat m collectioncreateformatcheck get check bst checked c string s file path s file path format t s s emulecollection the prefs get incoming dir m pcollection m scollectionname using namespace cryptopp rsassa pkcs1v15 sha signer p signkey null if m collectioncreatesignnamekeycheck get check bool b create new key false handle h key file create file the prefs get config dir t collectioncryptkey dat generic read file share read null open existing file attribute normal null if h key file invalid handle value if get file size h key file null 0 b create new key true close handle h key file else b create new key true if b create new key try auto seeded random pool rng invertiblersa function privkey privkey initialize rng 1024 base64 encoder privkeysink new file sink c stringa the prefs get config dir t collectioncryptkey dat privkey der encode privkeysink privkeysink message end catch assert 0 try file source filesource c stringa the prefs get config dir t collectioncryptkey dat true new base64 decoder p signkey new rsassa pkcs1v15 sha signer filesource rsassa pkcs1v15 sha verifier pubkey p signkey byte aby my public key 1000 array sink asink aby my public key 1000 pubkey der encode asink int n len asink total put length asink message end m pcollection set collection author key aby my public key n len catch assert 0 m pcollection m scollectionauthorname the prefs get user nick if path file exists s file path m pcollection write to file add shared p signkey else if idno afx message box get res string ids coll replaceexisting mb iconwarning mb iconquestion mb defbutton2 mb yesno return bool b delete successful false if the prefs get remove to bin b delete successful delete file s file path else tchar todel max path 1 memset todel 0 sizeof todel tcsncpy todel s file path arrsize todel 2 shfileopstruct fp 0 fp w func fo delete fp hwnd the app emuledlg m hwnd fp p from todel fp f flags fof allowundo fof noconfirmation fof silent fof noerrorui b delete successful sh file operation fp 0 if b delete successful c known file p known file the app knownfiles find known file by path s file path if p known file the app sharedfiles remove file p known file if p known file is kind of runtime class c part file the app emuledlg transferwnd downloadlistctrl clear completed static cast c part file p known file m pcollection write to file add shared p signkey else afx message box get res string ids coll err deleting mb iconwarning mb iconquestion mb defbutton2 mb yesno delete p signkey p signkey null onok ccollectioncreatedialog onbnclickedok onenkillfocuscollectionnameedit cstring sfilename m_collectionnameedit getwindowtext sfilename sfilename isempty m_pcollection m_scollectionauthorname _t m_pcollection setcollectionauthorkey m_pcollection m_scollectionname sfilename m_pcollection m_btextformat m_collectioncreateformatcheck getcheck bst_checked cstring sfilepath sfilepath _t theprefs getincomingdir m_pcollection m_scollectionname rsassa_pkcs1v15_sha_signer psignkey m_collectioncreatesignnamekeycheck getcheck bcreatenewkey hkeyfile createfile theprefs getconfigdir _t generic_read file_share_read open_existing file_attribute_normal hkeyfile invalid_handle_value getfilesize hkeyfile bcreatenewkey closehandle hkeyfile bcreatenewkey bcreatenewkey autoseededrandompool invertiblersafunction base64encoder filesink cstringa theprefs getconfigdir _t derencode messageend filesource cstringa theprefs getconfigdir _t base64decoder psignkey rsassa_pkcs1v15_sha_signer rsassa_pkcs1v15_sha_verifier psignkey abymypublickey arraysink abymypublickey derencode nlen totalputlength messageend m_pcollection setcollectionauthorkey abymypublickey nlen m_pcollection m_scollectionauthorname theprefs getusernick pathfileexists sfilepath m_pcollection writetofileaddshared psignkey afxmessagebox getresstring ids_coll_replaceexisting mb_iconwarning mb_iconquestion mb_defbutton2 mb_yesno bdeletesuccessful theprefs getremovetobin bdeletesuccessful deletefile sfilepath max_path _tcsncpy sfilepath wfunc fo_delete theapp m_hwnd pfrom fflags fof_allowundo fof_noconfirmation fof_silent fof_noerrorui bdeletesuccessful shfileoperation bdeletesuccessful cknownfile pknownfile theapp findknownfilebypath sfilepath pknownfile theapp removefile pknownfile pknownfile iskindof runtime_class cpartfile theapp clearcompleted static_cast cpartfile pknownfile m_pcollection writetofileaddshared psignkey afxmessagebox getresstring ids_coll_err_deleting mb_iconwarning mb_iconquestion mb_defbutton2 mb_yesno psignkey psignkey void c collection create dialog on bn clicked collectionviewsharebutton m bsharedfiles m bsharedfiles update avail files if m bsharedfiles m collectionviewsharebutton set window text t get res string ids shared else m collectionviewsharebutton set window text t get res string ids known ccollectioncreatedialog onbnclickedcollectionviewsharebutton m_bsharedfiles m_bsharedfiles updateavailfiles m_bsharedfiles m_collectionviewsharebutton setwindowtext _t getresstring ids_shared m_collectionviewsharebutton setwindowtext _t getresstring ids_known void c collection create dialog onnm dblclk collectionavaillist nmhdr pnmhdr lresult p result add selected files p result 0 ccollectioncreatedialog onnmdblclkcollectionavaillist presult addselectedfiles presult void c collection create dialog onnm dblclk collectionlistctrl nmhdr pnmhdr lresult p result remove selected files p result 0 ccollectioncreatedialog onnmdblclkcollectionlistctrl presult removeselectedfiles presult void c collection create dialog on en killfocus collectionnameedit c string s file name c string s new file name m collectionnameedit get window text s file name s new file name valid filename s file name if s new file name compare s file name m collectionnameedit set window text s new file name ccollectioncreatedialog onenkillfocuscollectionnameedit cstring sfilename cstring snewfilename m_collectionnameedit getwindowtext sfilename snewfilename validfilename sfilename snewfilename sfilename m_collectionnameedit setwindowtext snewfilename void c collection create dialog on bn clicked collectioncreateformat if m collectioncreateformatcheck get check m collectioncreatesignnamekeycheck set check bst unchecked m collectioncreatesignnamekeycheck enable window false else m collectioncreatesignnamekeycheck enable window true ccollectioncreatedialog onbnclickedcollectioncreateformat m_collectioncreateformatcheck getcheck m_collectioncreatesignnamekeycheck setcheck bst_unchecked m_collectioncreatesignnamekeycheck enablewindow m_collectioncreatesignnamekeycheck enablewindow c resizable dialog c collection view dialog idd p parent m pcollection null cresizabledialog ccollectionviewdialog pparent m_pcollection c collection view dialog c collection view dialog if m icovwnd verify destroy icon m icovwnd ccollectionviewdialog ccollectionviewdialog m_icovwnd destroyicon m_icovwnd void c collection view dialog set collection c collection p collection if p collection assert 0 return m pcollection p collection ccollectionviewdialog setcollection ccollection pcollection pcollection m_pcollection pcollection bool c collection view dialog on init dialog void c dialog on init dialog if m pcollection assert 0 return true m collectionviewlist init t collection view set icon m icovwnd the app load icon t collection view false m addnewcatagory set check false set window text m pcollection m scollectionname m collectionviewlisticon set icon the app load icon t collection m collectiondownload set window text get res string ids download m collectionexit set window text get res string ids cw close m collectionviewlistlabel set window text get res string ids collectionlist set dlg item text idc collectionviewauthorlabel get res string ids author t set dlg item text idc collectionviewauthorkeylabel get res string ids authorkey t set dlg item text idc collectionviewcategorycheck get res string ids coll addincat set dlg item text idc vcoll details get res string ids details set dlg item text idc vcoll options get res string ids options m collectionviewauthor set window text m pcollection m scollectionauthorname m collectionviewauthorkey set window text m pcollection get author key hash string add anchor idc collectionvewlist top left bottom right add anchor idc vcoll details bottom left bottom right add anchor idc vcoll options bottom left bottom right add anchor idc collectionviewauthorlabel bottom left add anchor idc collectionviewauthorkeylabel bottom left add anchor idc collectionviewcategorycheck bottom left add anchor idc collectionviewauthor bottom left bottom right add anchor idc collectionviewauthorkey bottom left bottom right add anchor idc vcoll close bottom right add anchor idc viewcollectiondl bottom right position pos m pcollection m collectionfilesmap get start position c collection file p collection file cs key key while pos null m pcollection m collectionfilesmap get next assoc pos key p collection file int i item m collectionviewlist insert item lvif text lvif param m collectionviewlist get item count null 0 0 0 lparam p collection file if i item 1 m collectionviewlist set item text i item col name p collection file get file name m collectionviewlist set item text i item col size cast itox bytes p collection file get file size m collectionviewlist set item text i item col hash md4str p collection file get file hash int i item m collectionviewlist get item count while i item m collectionviewlist set item state i item lvis selected lvis selected return true ccollectionviewdialog oninitdialog cdialog oninitdialog m_pcollection m_collectionviewlist _t collectionview seticon m_icovwnd theapp loadicon _t collection_view m_addnewcatagory setcheck setwindowtext m_pcollection m_scollectionname m_collectionviewlisticon seticon theapp loadicon _t m_collectiondownload setwindowtext getresstring ids_download m_collectionexit setwindowtext getresstring ids_cw_close m_collectionviewlistlabel setwindowtext getresstring ids_collectionlist setdlgitemtext idc_collectionviewauthorlabel getresstring ids_author _t setdlgitemtext idc_collectionviewauthorkeylabel getresstring ids_authorkey _t setdlgitemtext idc_collectionviewcategorycheck getresstring ids_coll_addincat setdlgitemtext idc_vcoll_details getresstring ids_details setdlgitemtext idc_vcoll_options getresstring ids_options m_collectionviewauthor setwindowtext m_pcollection m_scollectionauthorname m_collectionviewauthorkey setwindowtext m_pcollection getauthorkeyhashstring addanchor idc_collectionvewlist top_left bottom_right addanchor idc_vcoll_details bottom_left bottom_right addanchor idc_vcoll_options bottom_left bottom_right addanchor idc_collectionviewauthorlabel bottom_left addanchor idc_collectionviewauthorkeylabel bottom_left addanchor idc_collectionviewcategorycheck bottom_left addanchor idc_collectionviewauthor bottom_left bottom_right addanchor idc_collectionviewauthorkey bottom_left bottom_right addanchor idc_vcoll_close bottom_right addanchor idc_viewcollectiondl bottom_right m_pcollection m_collectionfilesmap getstartposition ccollectionfile pcollectionfile cskey m_pcollection m_collectionfilesmap getnextassoc pcollectionfile iitem m_collectionviewlist insertitem lvif_text lvif_param m_collectionviewlist getitemcount pcollectionfile iitem m_collectionviewlist setitemtext iitem colname pcollectionfile getfilename m_collectionviewlist setitemtext iitem colsize castitoxbytes pcollectionfile getfilesize m_collectionviewlist setitemtext iitem colhash pcollectionfile getfilehash iitem m_collectionviewlist getitemcount iitem m_collectionviewlist setitemstate iitem lvis_selected lvis_selected void c collection view dialog do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc collectionvewlist m collectionviewlist ddx control pdx idc collectionviewcategorycheck m addnewcatagory ddx control pdx idc collectionviewlistlabel m collectionviewlistlabel ddx control pdx idc collectionviewlisticon m collectionviewlisticon ddx control pdx idc viewcollectiondl m collectiondownload ddx control pdx idc vcoll close m collectionexit ddx control pdx idc collectionviewauthor m collectionviewauthor ddx control pdx idc collectionviewauthorkey m collectionviewauthorkey ccollectionviewdialog dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_collectionvewlist m_collectionviewlist ddx_control idc_collectionviewcategorycheck m_addnewcatagory ddx_control idc_collectionviewlistlabel m_collectionviewlistlabel ddx_control idc_collectionviewlisticon m_collectionviewlisticon ddx_control idc_viewcollectiondl m_collectiondownload ddx_control idc_vcoll_close m_collectionexit ddx_control idc_collectionviewauthor m_collectionviewauthor ddx_control idc_collectionviewauthorkey m_collectionviewauthorkey void c collection view dialog download selected void int i new index 0 for int i index 1 i index the prefs get cat count i index if m pcollection m scollectionname compare no case the prefs get category i index title i new index i index break if m addnewcatagory get check i new index i new index the app emuledlg transferwnd add category m pcollection m scollectionname the prefs get incoming dir t t true the app emuledlg searchwnd update cat tabs c typed ptr list c ptr list c collection file collection file list position pos m collectionviewlist get first selected item position while pos null int index m collectionviewlist get next selected item pos if index 0 collection file list add tail c collection file m collectionviewlist get item data index while collection file list get count 0 c collection file p collection file collection file list remove head if p collection file the app downloadqueue add search to download createed2k link p collection file true the prefs add new files paused i new index ccollectionviewdialog downloadselected inewindex iindex iindex theprefs getcatcount iindex m_pcollection m_scollectionname comparenocase theprefs getcategory iindex inewindex iindex m_addnewcatagory getcheck inewindex inewindex theapp addcategory m_pcollection m_scollectionname theprefs getincomingdir _t _t theapp updatecattabs ctypedptrlist cptrlist ccollectionfile collectionfilelist m_collectionviewlist getfirstselecteditemposition m_collectionviewlist getnextselecteditem collectionfilelist addtail ccollectionfile m_collectionviewlist getitemdata collectionfilelist getcount ccollectionfile pcollectionfile collectionfilelist removehead pcollectionfile theapp addsearchtodownload createed2klink pcollectionfile theprefs addnewfilespaused inewindex void c collection view dialog onnm dblclk collectionvewlist nmhdr pnmhdr lresult p result download selected p result 0 ccollectionviewdialog onnmdblclkcollectionvewlist presult downloadselected presult void c collection view dialog on bn clicked viewcollectiondl download selected on bn clicked ok ccollectionviewdialog onbnclickedviewcollectiondl downloadselected onbnclickedok void c collection view dialog on bn clicked ok onok ccollectionviewdialog onbnclickedok c collection list ctrl c collection list ctrl c list ctrl item walk this ccollectionlistctrl ccollectionlistctrl clistctrlitemwalk c collection list ctrl c collection list ctrl ccollectionlistctrl ccollectionlistctrl void c collection list ctrl init c string str name add set name t collection list ctrl str name add modify style lvs singlesel 0 set extended style lvs ex fullrowselect lvs ex gridlines insert column col name get res string ids dl filename lvcfmt left 250 insert column col size get res string ids dl size lvcfmt left 100 insert column col hash get res string ids filehash lvcfmt left 250 load settings set sort arrow sort items sort proc makelong get sort item get sort ascending 0 1 ccollectionlistctrl cstring strnameadd setname _t collectionlistctrl strnameadd modifystyle lvs_singlesel setextendedstyle lvs_ex_fullrowselect lvs_ex_gridlines insertcolumn colname getresstring ids_dl_filename lvcfmt_left insertcolumn colsize getresstring ids_dl_size lvcfmt_left insertcolumn colhash getresstring ids_filehash lvcfmt_left loadsettings setsortarrow sortitems sortproc getsortitem getsortascending void c collection list ctrl add file to list c abstract file p abstract file lvfindinfo find find flags lvfi param find l param lparam p abstract file int i item find item find if i item 1 assert 0 return i item insert item lvif text lvif param get item count null 0 0 0 lparam p abstract file if i item 1 set item text i item col name p abstract file get file name set item text i item col size cast itox bytes p abstract file get file size set item text i item col hash md4str p abstract file get file hash ccollectionlistctrl addfiletolist cabstractfile pabstractfile lvfi_param lparam pabstractfile iitem finditem iitem iitem insertitem lvif_text lvif_param getitemcount pabstractfile iitem setitemtext iitem colname pabstractfile getfilename setitemtext iitem colsize castitoxbytes pabstractfile getfilesize setitemtext iitem colhash pabstractfile getfilehash void c collection list ctrl remove file from list c abstract file p abstract file lvfindinfo find find flags lvfi param find l param lparam p abstract file int i item find item find if i item 1 delete item i item else assert 0 ccollectionlistctrl removefilefromlist cabstractfile pabstractfile lvfi_param lparam pabstractfile iitem finditem iitem deleteitem iitem int c collection list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort c abstract file item1 c abstract file l param1 c abstract file item2 c abstract file l param2 if item1 null item2 null return 0 int i result switch loword l param sort case col name i result compare locale string no case item1 get file name item2 get file name break case col size i result item1 get file size item2 get file size 0 item1 get file size item2 get file size 1 1 break case col hash i result memcmp item1 get file hash item2 get file hash 16 break default return 0 if hiword l param sort i result i result return i result ccollectionlistctrl sortproc lparam1 lparam2 lparamsort cabstractfile cabstractfile lparam1 cabstractfile cabstractfile lparam2 iresult lparamsort colname iresult comparelocalestringnocase getfilename getfilename colsize iresult getfilesize getfilesize getfilesize getfilesize colhash iresult getfilehash getfilehash lparamsort iresult iresult iresult void c collection list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr determine ascending based on whether already sorted on this column int i sort item get sort item bool b old sort ascending get sort ascending bool b sort ascending i sort item pnm list view i sub item true b old sort ascending item is column clicked i sort item pnm list view i sub item sort table update sort history makelong i sort item b sort ascending 0 0x0001 set sort arrow i sort item b sort ascending sort items sort proc makelong i sort item b sort ascending 0 0x0001 p result 0 ccollectionlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview isortitem getsortitem boldsortascending getsortascending bsortascending isortitem pnmlistview isubitem boldsortascending isortitem pnmlistview isubitem updatesorthistory isortitem bsortascending setsortarrow isortitem bsortascending sortitems sortproc isortitem bsortascending presult void c collection list ctrl onnm rclick nmhdr pnmhdr lresult p result c typed ptr list c ptr list c abstract file abstract file list position pos get first selected item position while pos null int index get next selected item pos if index 0 abstract file list add tail c abstract file get item data index if abstract file list get count 0 c collection file details sheet dialog abstract file list 0 this dialog do modal p result 0 ccollectionlistctrl onnmrclick presult ctypedptrlist cptrlist cabstractfile abstractfilelist getfirstselecteditemposition getnextselecteditem abstractfilelist addtail cabstractfile getitemdata abstractfilelist getcount ccollectionfiledetailssheet abstractfilelist domodal presult c resizable form view c search results wnd idd m ned2ksearchid 0x80000000 global search timer 0 searchpacket null m b64bitsearchpacket false canceld false servercount 0 globsearch false icon search null m utimerlocalserver 0 m isentmorereq 0 searchselect m bcloseable true cresizableformview csearchresultswnd m_ned2ksearchid global_search_timer m_b64bitsearchpacket icon_search m_utimerlocalserver m_isentmorereq m_bcloseable c search results wnd c search results wnd if globsearch delete searchpacket if icon search verify destroy icon icon search if m utimerlocalserver verify kill timer m utimerlocalserver csearchresultswnd csearchresultswnd icon_search destroyicon icon_search m_utimerlocalserver killtimer m_utimerlocalserver void c search results wnd localize searchlistctrl localize update cat tabs get dlg item idc clearall set window text get res string ids removeallsearch get dlg item idc results lbl set window text get res string ids sw result get dlg item idc sdownload set window text get res string ids sw download get dlg item idc open params wnd set window text get res string ids searchparams t csearchresultswnd updatecattabs getdlgitem idc_clearall setwindowtext getresstring ids_removeallsearch getdlgitem idc_results_lbl setwindowtext getresstring ids_sw_result getdlgitem idc_sdownload setwindowtext getresstring ids_sw_download getdlgitem idc_open_params_wnd setwindowtext getresstring ids_searchparams _t void c search results wnd start search s search params p params switch p params e type case search type ed2k server case search type ed2k global case search type kademlia start new search p params break case search type file donkey shell open file create web query p params delete p params return default assert 0 delete p params csearchresultswnd startsearch ssearchparams pparams pparams etype searchtypeed2kserver searchtypeed2kglobal searchtypekademlia startnewsearch pparams searchtypefiledonkey shellopenfile createwebquery pparams pparams pparams bool c search results wnd search more if the app serverconnect is connected return false set active search results icon m ned2ksearchid canceld false packet packet new packet packet opcode op query more result if the prefs get debug servertcp level 0 debug t sending op querymoreresults n the stats add up data overhead server packet size the app serverconnect send packet packet m isentmorereq return true csearchresultswnd searchmore theapp isconnected setactivesearchresultsicon m_ned2ksearchid op_query_more_result theprefs getdebugservertcplevel _t op__querymoreresults thestats addupdataoverheadserver theapp sendpacket m_isentmorereq void c search results wnd cancel search uint u searchid if u searchid 0 int i cur sel searchselect get cur sel if i cur sel 1 return tcitem item item mask tcif param if searchselect get item i cur sel item item l param null u searchid const s search params item l param dw searchid if u searchid 0 return s search params p params get search results params u searchid if p params null return if p params e type search type ed2k server p params e type search type ed2k global cancel ed2k search else if p params e type search type kademlia kademlia c search manager stop search p params dw searchid false cancel kad search p params dw searchid csearchresultswnd cancelsearch usearchid usearchid icursel getcursel icursel tcif_param getitem icursel lparam usearchid ssearchparams lparam dwsearchid usearchid ssearchparams pparams getsearchresultsparams usearchid pparams pparams etype searchtypeed2kserver pparams etype searchtypeed2kglobal canceled2ksearch pparams etype searchtypekademlia csearchmanager stopsearch pparams dwsearchid cancelkadsearch pparams dwsearchid bool c search results wnd do new ed2k search s search params p params if the app serverconnect is connected return false bool b server supports64 bit the app serverconnect get current server null the app serverconnect get current server gettcp flags srv tcpflg largefiles bool b packet using64 bit false c safe mem file data 100 if get search packet data p params b server supports64 bit b packet using64 bit data get length 0 return false cancel ed2k search c stringa str result type p params str file type if str result type ed2kftstr program str result type empty m ned2ksearchid p params dw searchid m ned2ksearchid the app searchlist new search searchlistctrl str result type m ned2ksearchid p params e type canceld false if m utimerlocalserver verify kill timer m utimerlocalserver m utimerlocalserver 0 once we ve sent a new search request any previously received more gets invalid c wnd p wnd focus get focus m pwndparams m ctlmore enable window false if p wnd focus p wnd focus m hwnd m pwndparams m ctlmore m hwnd m pwndparams m ctlcancel set focus m isentmorereq 0 packet packet new packet data packet opcode op searchrequest if the prefs get debug servertcp level 0 debug t sending op searchrequest n the stats add up data overhead server packet size the app serverconnect send packet packet false if p params e type search type ed2k global the app serverconnect isudp socket available set timeout timer for local server m utimerlocalserver set timer timer server timeout 50000 null if the prefs get use server priorities the app serverlist reset search server pos if globsearch delete searchpacket searchpacket null m b64bitsearchpacket false searchpacket packet searchpacket opcode op globsearchreq will be changed later when actually sending the packet m b64bitsearchpacket b packet using64 bit servercount 0 searchprogress set range32 0 the app serverlist get server count 1 globsearch true else globsearch false delete packet create new tab p params return true csearchresultswnd donewed2ksearch ssearchparams pparams theapp isconnected bserversupports64bit theapp getcurrentserver theapp getcurrentserver gettcpflags srv_tcpflg_largefiles bpacketusing64bit csafememfile getsearchpacket pparams bserversupports64bit bpacketusing64bit getlength canceled2ksearch cstringa strresulttype pparams strfiletype strresulttype ed2kftstr_program strresulttype m_ned2ksearchid pparams dwsearchid m_ned2ksearchid theapp newsearch strresulttype m_ned2ksearchid pparams etype m_utimerlocalserver killtimer m_utimerlocalserver m_utimerlocalserver cwnd pwndfocus getfocus m_pwndparams m_ctlmore enablewindow pwndfocus pwndfocus m_hwnd m_pwndparams m_ctlmore m_hwnd m_pwndparams m_ctlcancel setfocus m_isentmorereq op_searchrequest theprefs getdebugservertcplevel _t op__searchrequest thestats addupdataoverheadserver theapp sendpacket pparams etype searchtypeed2kglobal theapp isudpsocketavailable m_utimerlocalserver settimer timerservertimeout theprefs getuseserverpriorities theapp resetsearchserverpos m_b64bitsearchpacket op_globsearchreq m_b64bitsearchpacket bpacketusing64bit setrange32 theapp getservercount createnewtab pparams void c search results wnd cancel ed2k search set inactive search results icon m ned2ksearchid canceld true delete any global search timer if globsearch delete searchpacket searchpacket null m b64bitsearchpacket false globsearch false if global search timer verify kill timer global search timer global search timer 0 searchprogress set pos 0 delete local server timeout timer if m utimerlocalserver verify kill timer m utimerlocalserver m utimerlocalserver 0 search canceled m ned2ksearchid csearchresultswnd canceled2ksearch setinactivesearchresultsicon m_ned2ksearchid m_b64bitsearchpacket global_search_timer killtimer global_search_timer global_search_timer setpos m_utimerlocalserver killtimer m_utimerlocalserver m_utimerlocalserver searchcanceled m_ned2ksearchid void c search results wnd local ed2k search end uint count bool b more results available local server has answered kill the timeout timer if m utimerlocalserver verify kill timer m utimerlocalserver m utimerlocalserver 0 if canceld count max results cancel ed2k search if canceld if globsearch search canceled m ned2ksearchid else verify global search timer set timer timer global search 750 0 null m pwndparams m ctlmore enable window b more results available m isentmorereq max more search req csearchresultswnd localed2ksearchend bmoreresultsavailable m_utimerlocalserver killtimer m_utimerlocalserver m_utimerlocalserver max_results canceled2ksearch searchcanceled m_ned2ksearchid global_search_timer settimer timerglobalsearch m_pwndparams m_ctlmore enablewindow bmoreresultsavailable m_isentmorereq max_more_search_req void c search results wnd add global ed2k search results uint count if canceld count max results cancel ed2k search csearchresultswnd addglobaled2ksearchresults max_results canceled2ksearch bool c search results wnd do new kad search s search params p params if kademlia c kademlia is connected return false int i pos 0 p params str keyword p params str expression tokenize t i pos p params str keyword trim if p params str keyword is empty p params str keyword find one of aszinvkadkeywordchars 1 c string str error str error format get res string ids kad search keyword invalid aszinvkadkeywordchars throw new c msg box exception str error mb iconwarning mb help emule faq search hid base prompt c safe mem file data 100 if get search packet data p params true null p params str boolean expr is empty data get length 0 return false lpbyte p search terms data null uint u search terms size uint data get length if u search terms size p search terms data new byte u search terms size data seek to begin data read p search terms data u search terms size kademlia c search p search null try p search kademlia c search manager prepare find keywords p params b unicode p params str keyword u search terms size p search terms data delete p search terms data if p search assert 0 return false catch c string str exception delete p search terms data throw new c msg box exception str exception mb iconwarning mb help emule faq search hid base prompt p params dw searchid p search get searchid c stringa str result type p params str file type if str result type ed2kftstr program str result type empty the app searchlist new search searchlistctrl str result type p params dw searchid p params e type create new tab p params return true csearchresultswnd donewkadsearch ssearchparams pparams ckademlia isconnected ipos pparams strkeyword pparams strexpression _t ipos pparams strkeyword pparams strkeyword isempty pparams strkeyword findoneof _aszinvkadkeywordchars cstring strerror strerror getresstring ids_kad_search_keyword_invalid _aszinvkadkeywordchars cmsgboxexception strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt csafememfile getsearchpacket pparams pparams strbooleanexpr isempty getlength psearchtermsdata usearchtermssize getlength usearchtermssize psearchtermsdata usearchtermssize seektobegin psearchtermsdata usearchtermssize csearch psearch psearch csearchmanager preparefindkeywords pparams bunicode pparams strkeyword usearchtermssize psearchtermsdata psearchtermsdata psearch cstring strexception psearchtermsdata cmsgboxexception strexception mb_iconwarning mb_help emule_faq_search hid_base_prompt pparams dwsearchid psearch getsearchid cstringa strresulttype pparams strfiletype strresulttype ed2kftstr_program strresulttype theapp newsearch strresulttype pparams dwsearchid pparams etype createnewtab pparams void c search results wnd cancel kad search uint u searchid search canceled u searchid csearchresultswnd cancelkadsearch usearchid searchcanceled usearchid bool c search results wnd can search related files const return the app serverconnect is connected the app serverconnect get current server null the app serverconnect get current server get related search support csearchresultswnd cansearchrelatedfiles theapp isconnected theapp getcurrentserver theapp getcurrentserver getrelatedsearchsupport void c search results wnd search related files const c abstract file file s search params p params new s search params p params str expression t related md4str file get file hash p params str special title get res string ids related t file get file name if p params str special title get length 50 p params str special title p params str special title left 50 t start search p params csearchresultswnd searchrelatedfiles cabstractfile ssearchparams pparams ssearchparams pparams strexpression _t getfilehash pparams strspecialtitle getresstring ids_related _t getfilename pparams strspecialtitle getlength pparams strspecialtitle pparams strspecialtitle _t startsearch pparams void c search results wnd download selected download selected the prefs add new files paused csearchresultswnd downloadselected downloadselected theprefs addnewfilespaused void c search results wnd download selected bool b paused c wait cursor cur wait position pos searchlistctrl get first selected item position while pos null int i index searchlistctrl get next selected item pos if i index 0 get selected listview item may be a child item from an expanded search result const c search file sel file c search file searchlistctrl get item data i index get parent const c search file parent if sel file get list parent null parent sel file get list parent else parent sel file if parent is complete 0 parent get source count 50 c string str msg str msg format get res string ids askdlincomplete sel file get file name int i answer afx message box str msg mb iconquestion mb yesno mb defbutton2 if i answer idyes continue create new dl queue entry with all properties of parent e g already received sources but with the filename of the selected listview item c search file temp file parent temp file set file name sel file get file name temp file set str tag value ft filename sel file get file name the app downloadqueue add search to download temp file b paused m cattabs get cur sel update parent and all childs searchlistctrl update sources parent csearchresultswnd downloadselected bpaused cwaitcursor curwait getfirstselecteditemposition iindex getnextselecteditem iindex csearchfile sel_file csearchfile getitemdata iindex csearchfile sel_file getlistparent sel_file getlistparent sel_file iscomplete getsourcecount cstring strmsg strmsg getresstring ids_askdlincomplete sel_file getfilename ianswer afxmessagebox strmsg mb_iconquestion mb_yesno mb_defbutton2 ianswer csearchfile tempfile tempfile setfilename sel_file getfilename tempfile setstrtagvalue ft_filename sel_file getfilename theapp addsearchtodownload tempfile bpaused m_cattabs getcursel updatesources bool c search results wnd can delete search uint32 n searchid const return searchselect get item count 0 csearchresultswnd candeletesearch nsearchid getitemcount bool c search results wnd can delete all searches const return searchselect get item count 0 csearchresultswnd candeleteallsearches getitemcount void c search results wnd delete search uint32 n searchid kademlia c search manager stop search n searchid false tcitem item item mask tcif param item l param 1 for int i 0 i searchselect get item count i if searchselect get item i item item l param 1 item l param null const s search params item l param dw searchid n searchid break if item l param 1 item l param null const s search params item l param dw searchid n searchid return delete search results if canceld n searchid m ned2ksearchid cancel ed2k search if n searchid m ned2ksearchid m pwndparams m ctlmore enable window false the app searchlist remove results n searchid clean up stored states scrollingpos etc for this search searchlistctrl clear result view state n searchid delete search tab int i cur sel searchselect get cur sel searchselect delete item i delete s search params item l param int i tab items searchselect get item count if i tab items 0 select next search tab if i cur sel cb err i cur sel 0 else if i cur sel i tab items i cur sel i tab items 1 void searchselect set cur sel i cur sel returns cb err if error or no prev selection i cur sel searchselect get cur sel get the real current selection if i cur sel cb err if still error i cur sel searchselect set cur sel 0 if i cur sel cb err item mask tcif param item l param null if searchselect get item i cur sel item item l param null searchselect highlight item i cur sel false show results const s search params item l param else searchlistctrl delete all items show search selector false searchlistctrl no tabs csearchresultswnd deletesearch nsearchid csearchmanager stopsearch nsearchid tcif_param lparam getitemcount getitem lparam lparam ssearchparams lparam dwsearchid nsearchid lparam lparam ssearchparams lparam dwsearchid nsearchid nsearchid m_ned2ksearchid canceled2ksearch nsearchid m_ned2ksearchid m_pwndparams m_ctlmore enablewindow theapp removeresults nsearchid clearresultviewstate nsearchid icursel getcursel deleteitem ssearchparams lparam itabitems getitemcount itabitems icursel cb_err icursel icursel itabitems icursel itabitems setcursel icursel cb_err icursel getcursel icursel cb_err icursel setcursel icursel cb_err tcif_param lparam getitem icursel lparam highlightitem icursel showresults ssearchparams lparam deleteallitems showsearchselector notabs void c search results wnd delete all searches cancel ed2k search for int i 0 i searchselect get item count i tcitem item item mask tcif param item l param 1 if searchselect get item i item item l param 1 item l param null kademlia c search manager stop search const s search params item l param dw searchid false delete s search params item l param the app searchlist clear searchlistctrl delete all items show search selector false searchselect delete all items c wnd p wnd focus get focus m pwndparams m ctlmore enable window false m pwndparams m ctlcancel enable window false m pwndparams m ctlstart enable window true if p wnd focus p wnd focus m hwnd m pwndparams m ctlmore m hwnd p wnd focus m hwnd m pwndparams m ctlcancel m hwnd m pwndparams m ctlstart set focus csearchresultswnd deleteallsearches canceled2ksearch getitemcount tcif_param lparam getitem lparam lparam csearchmanager stopsearch ssearchparams lparam dwsearchid ssearchparams lparam theapp deleteallitems showsearchselector deleteallitems cwnd pwndfocus getfocus m_pwndparams m_ctlmore enablewindow m_pwndparams m_ctlcancel enablewindow m_pwndparams m_ctlstart enablewindow pwndfocus pwndfocus m_hwnd m_pwndparams m_ctlmore m_hwnd pwndfocus m_hwnd m_pwndparams m_ctlcancel m_hwnd m_pwndparams m_ctlstart setfocus bool c search results wnd create new tab s search params p params int i tab items searchselect get item count for int i 0 i i tab items i tcitem tci tci mask tcif param if searchselect get item i tci tci l param null const s search params tci l param dw searchid p params dw searchid return false add new tab tcitem newitem if p params str expression is empty p params str expression t newitem mask tcif param tcif text tcif image newitem l param lparam p params c string label p params str special title is empty p params str expression p params str special title t 0 newitem psz text const cast lptstr lpctstr label newitem cch text max 0 if p params b client shared files newitem i image sri client else if p params e type search type kademlia newitem i image sri kad actice else if p params e type search type ed2k global newitem i image sri global active else assert p params e type search type ed2k server newitem i image sri server active int itemnr searchselect insert item int max newitem if searchselect is window visible show search selector true searchselect set cur sel itemnr searchlistctrl show results p params dw searchid return true csearchresultswnd createnewtab ssearchparams pparams itabitems getitemcount itabitems tcif_param getitem lparam ssearchparams lparam dwsearchid pparams dwsearchid pparams strexpression isempty pparams strexpression _t tcif_param tcif_text tcif_image lparam pparams cstring pparams strspecialtitle isempty pparams strexpression pparams strspecialtitle _t psztext const_cast cchtextmax pparams bclientsharedfiles iimage sriclient pparams etype searchtypekademlia iimage srikadactice pparams etype searchtypeed2kglobal iimage sriglobalactive pparams etype searchtypeed2kserver iimage sriserveractive insertitem int_max iswindowvisible showsearchselector setcursel showresults pparams dwsearchid void c search results wnd show search selector bool visible windowplacement wp search win pos windowplacement wp select win pos searchselect get window placement wp select win pos searchlistctrl get window placement wp search win pos if visible wp search win pos rc normal position top wp select win pos rc normal position bottom else wp search win pos rc normal position top wp select win pos rc normal position top searchselect show window visible sw show sw hide remove anchor searchlistctrl searchlistctrl set window placement wp search win pos add anchor searchlistctrl top left bottom right get dlg item idc clearall show window visible sw show sw hide csearchresultswnd showsearchselector wpsearchwinpos wpselectwinpos getwindowplacement wpselectwinpos getwindowplacement wpsearchwinpos wpsearchwinpos rcnormalposition wpselectwinpos rcnormalposition wpsearchwinpos rcnormalposition wpselectwinpos rcnormalposition showwindow sw_show sw_hide removeanchor setwindowplacement wpsearchwinpos addanchor top_left bottom_right getdlgitem idc_clearall showwindow sw_show sw_hide void c search results wnd update cat tabs int oldsel m cattabs get cur sel m cattabs delete all items for int ix 0 ix the prefs get cat count ix c string label ix 0 get res string ids all the prefs get category ix title label replace t t m cattabs insert item ix label if oldsel m cattabs get item count oldsel 1 oldsel 0 m cattabs set cur sel oldsel int flag flag m cattabs get item count 1 sw show sw hide get dlg item idc cattab2 show window flag get dlg item idc static dltoof show window flag csearchresultswnd updatecattabs m_cattabs getcursel m_cattabs deleteallitems theprefs getcatcount cstring getresstring ids_all theprefs getcategory _t _t m_cattabs insertitem m_cattabs getitemcount m_cattabs setcursel m_cattabs getitemcount sw_show sw_hide getdlgitem idc_cattab2 showwindow getdlgitem idc_static_dltoof showwindow void c search results wnd on initial update c resizable form view on initial update init window styles this the app searchlist set output wnd searchlistctrl searchlistctrl init the app searchlist searchlistctrl set name t search list ctrl set all icons localize searchprogress set step 1 global search timer 0 globsearch false add anchor idc searchlst ico top left add anchor idc results lbl top left add anchor idc sdownload bottom left add anchor idc searchlist top left bottom right add anchor idc progress1 bottom left bottom right add anchor idc clearall top right add anchor idc open params wnd top right add anchor searchselect m hwnd top left top right add anchor idc static dltoof bottom left add anchor idc cattab2 bottom left bottom right show search selector false if the app m fontsymbol m hobject get dlg item idc static dltoof set font the app m fontsymbol get dlg item idc static dltoof set window text get ex style ws ex layoutrtl t 3 t 4 show a right arrow csearchresultswnd oninitialupdate cresizableformview oninitialupdate initwindowstyles theapp setoutputwnd theapp setname _t searchlistctrl setallicons setstep global_search_timer addanchor idc_searchlst_ico top_left addanchor idc_results_lbl top_left addanchor idc_sdownload bottom_left addanchor idc_searchlist top_left bottom_right addanchor idc_progress1 bottom_left bottom_right addanchor idc_clearall top_right addanchor idc_open_params_wnd top_right addanchor m_hwnd top_left top_right addanchor idc_static_dltoof bottom_left addanchor idc_cattab2 bottom_left bottom_right showsearchselector theapp m_fontsymbol m_hobject getdlgitem idc_static_dltoof setfont theapp m_fontsymbol getdlgitem idc_static_dltoof setwindowtext getexstyle ws_ex_layoutrtl _t _t bool c search results wnd start new search s search params p params e search type e search type p params e type if e search type search type ed2k server e search type search type ed2k global if the app serverconnect is connected afx message box get res string ids err notconnected mb iconwarning delete p params return false try if do new ed2k search p params delete p params return false catch c msg box exception ex afx message box ex m strmsg ex m utype ex m uhelpid ex delete delete p params return false search started return true if e search type search type kademlia if kademlia c kademlia is running kademlia c kademlia is connected afx message box get res string ids err notconnectedkad mb iconwarning delete p params return false try if do new kad search p params delete p params return false catch c msg box exception ex afx message box ex m strmsg ex m utype ex m uhelpid ex delete delete p params return false search started return true assert 0 delete p params return false csearchresultswnd startnewsearch ssearchparams pparams esearchtype esearchtype pparams etype esearchtype searchtypeed2kserver esearchtype searchtypeed2kglobal theapp isconnected afxmessagebox getresstring ids_err_notconnected mb_iconwarning pparams donewed2ksearch pparams pparams cmsgboxexception afxmessagebox m_strmsg m_utype m_uhelpid pparams searchstarted esearchtype searchtypekademlia ckademlia isrunning ckademlia isconnected afxmessagebox getresstring ids_err_notconnectedkad mb_iconwarning pparams donewkadsearch pparams pparams cmsgboxexception afxmessagebox m_strmsg m_utype m_uhelpid pparams searchstarted pparams void c search results wnd search started c wnd p wnd focus get focus m pwndparams m ctlstart enable window false if p wnd focus p wnd focus m hwnd m pwndparams m ctlstart m hwnd m pwndparams m ctlname set focus m pwndparams m ctlcancel enable window true csearchresultswnd searchstarted cwnd pwndfocus getfocus m_pwndparams m_ctlstart enablewindow pwndfocus pwndfocus m_hwnd m_pwndparams m_ctlstart m_hwnd m_pwndparams m_ctlname setfocus m_pwndparams m_ctlcancel enablewindow void c search results wnd search canceled uint u searchid set inactive search results icon u searchid int i cur sel searchselect get cur sel if i cur sel 1 tcitem item item mask tcif param if searchselect get item i cur sel item item l param null u searchid const s search params item l param dw searchid c wnd p wnd focus get focus m pwndparams m ctlcancel enable window false if p wnd focus p wnd focus m hwnd m pwndparams m ctlcancel m hwnd m pwndparams m ctlname set focus m pwndparams m ctlstart enable window true csearchresultswnd searchcanceled usearchid setinactivesearchresultsicon usearchid icursel getcursel icursel tcif_param getitem icursel lparam usearchid ssearchparams lparam dwsearchid cwnd pwndfocus getfocus m_pwndparams m_ctlcancel enablewindow pwndfocus pwndfocus m_hwnd m_pwndparams m_ctlcancel m_hwnd m_pwndparams m_ctlname setfocus m_pwndparams m_ctlstart enablewindow c string c search results wnd create web query s search params p params c string query switch p params e type case search type file donkey query t http www filedonkey com search html query t pattern encodeurl query param p params str expression if p params str file type ed2kftstr audio query t media audio else if p params str file type ed2kftstr video query t media video else if p params str file type ed2kftstr program query t media pro query t requestby emule if p params ull min size 0 query append format t min size i64u p params ull min size if p params ull max size 0 query append format t max size i64u p params ull max size break default return t return query cstring csearchresultswnd createwebquery ssearchparams pparams cstring pparams etype searchtypefiledonkey _t _t encodeurlqueryparam pparams strexpression pparams strfiletype ed2kftstr_audio _t pparams strfiletype ed2kftstr_video _t pparams strfiletype ed2kftstr_program _t _t pparams ullminsize appendformat _t min_size pparams ullminsize pparams ullmaxsize appendformat _t max_size pparams ullmaxsize _t void c search results wnd show results const s search params p params restoring the params works and is nice during development testing but pretty annoying in practice todo maybe it should be done explicitly via a context menu function or such if get async key state vk control 0 m pwndparams set parameters p params if p params e type search type ed2k server m pwndparams m ctlcancel enable window p params dw searchid m ned2ksearchid is local ed2k search running else if p params e type search type ed2k global m pwndparams m ctlcancel enable window p params dw searchid m ned2ksearchid is local ed2k search running is global ed2k search running else if p params e type search type kademlia m pwndparams m ctlcancel enable window kademlia c search manager is searching p params dw searchid searchlistctrl show results p params dw searchid csearchresultswnd showresults ssearchparams pparams getasynckeystate vk_control m_pwndparams setparameters pparams pparams etype searchtypeed2kserver m_pwndparams m_ctlcancel enablewindow pparams dwsearchid m_ned2ksearchid islocaled2ksearchrunning pparams etype searchtypeed2kglobal m_pwndparams m_ctlcancel enablewindow pparams dwsearchid m_ned2ksearchid islocaled2ksearchrunning isglobaled2ksearchrunning pparams etype searchtypekademlia m_pwndparams m_ctlcancel enablewindow csearchmanager issearching pparams dwsearchid showresults pparams dwsearchid void c search results wnd set all icons if icon search verify destroy icon icon search icon search the app load icon t search results 16 16 c static get dlg item idc searchlst ico set icon icon search c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t searchmethod serveractive 16 16 iml add c temp icon loader t searchmethod globalactive 16 16 iml add c temp icon loader t searchmethod kademliaactive 16 16 iml add c temp icon loader t stats clients 16 16 iml add c temp icon loader t searchmethod server 16 16 iml add c temp icon loader t searchmethod global 16 16 iml add c temp icon loader t searchmethod kademlia 16 16 searchselect set image list iml m imlsearchresults delete image list m imlsearchresults attach iml detach searchselect set padding c size 10 3 csearchresultswnd setallicons icon_search destroyicon icon_search icon_search theapp loadicon _t searchresults cstatic getdlgitem idc_searchlst_ico seticon icon_search cimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t searchmethod_serveractive ctempiconloader _t searchmethod_globalactive ctempiconloader _t searchmethod_kademliaactive ctempiconloader _t statsclients ctempiconloader _t searchmethod_server ctempiconloader _t searchmethod_global ctempiconloader _t searchmethod_kademlia setimagelist m_imlsearchresults deleteimagelist m_imlsearchresults setpadding csize void c search results wnd set search results icon uint u searchid int i image int i tab items searchselect get item count for int i 0 i i tab items i tcitem tci tci mask tcif param if searchselect get item i tci tci l param null const s search params tci l param dw searchid u searchid tci mask tcif image tci i image i image searchselect set item i tci break csearchresultswnd setsearchresultsicon usearchid iimage itabitems getitemcount itabitems tcif_param getitem lparam ssearchparams lparam dwsearchid usearchid tcif_image iimage iimage setitem void c search results wnd set active search results icon uint u searchid s search params p params get search results params u searchid if p params int i image if p params e type search type kademlia i image sri kad actice else if p params e type search type ed2k global i image sri global active else i image sri server active set search results icon u searchid i image csearchresultswnd setactivesearchresultsicon usearchid ssearchparams pparams getsearchresultsparams usearchid pparams iimage pparams etype searchtypekademlia iimage srikadactice pparams etype searchtypeed2kglobal iimage sriglobalactive iimage sriserveractive setsearchresultsicon usearchid iimage void c search results wnd set inactive search results icon uint u searchid s search params p params get search results params u searchid if p params int i image if p params e type search type kademlia i image sri kad else if p params e type search type ed2k global i image sri global else i image sri server set search results icon u searchid i image csearchresultswnd setinactivesearchresultsicon usearchid ssearchparams pparams getsearchresultsparams usearchid pparams iimage pparams etype searchtypekademlia iimage srikad pparams etype searchtypeed2kglobal iimage sriglobal iimage sriserver setsearchresultsicon usearchid iimage s search params c search results wnd get search results params uint u searchid const int i tab items searchselect get item count for int i 0 i i tab items i tcitem tci tci mask tcif param if searchselect get item i tci tci l param null const s search params tci l param dw searchid u searchid return s search params tci l param return null ssearchparams csearchresultswnd getsearchresultsparams usearchid itabitems getitemcount itabitems tcif_param getitem lparam ssearchparams lparam dwsearchid usearchid ssearchparams lparam void c search results wnd do data exchange c data exchange pdx c resizable form view do data exchange pdx ddx control pdx idc searchlist searchlistctrl ddx control pdx idc progress1 searchprogress ddx control pdx idc tab1 searchselect ddx control pdx idc cattab2 m cattabs csearchresultswnd dodataexchange cdataexchange cresizableformview dodataexchange ddx_control idc_searchlist ddx_control idc_progress1 ddx_control idc_tab1 ddx_control idc_cattab2 m_cattabs void c search results wnd on dbl clk search list nmhdr pnmhdr lresult p result on bn clicked download selected p result 0 csearchresultswnd ondblclksearchlist presult onbnclickeddownloadselected presult void c search results wnd on sel change tab nmhdr pnmhdr lresult p result c wait cursor cur wait this may take a while int cur sel searchselect get cur sel if cur sel 1 return tcitem item item mask tcif param if searchselect get item cur sel item item l param null searchselect highlight item cur sel false show results const s search params item l param p result 0 csearchresultswnd onselchangetab presult cwaitcursor curwait cur_sel getcursel cur_sel tcif_param getitem cur_sel lparam highlightitem cur_sel showresults ssearchparams lparam presult lresult c search results wnd on close tab wparam w param lparam l param tcitem item item mask tcif param if searchselect get item int w param item item l param null int n searchid const s search params item l param dw searchid if canceld uint n searchid m ned2ksearchid cancel ed2k search delete search n searchid return true csearchresultswnd onclosetab wparam lparam tcif_param getitem wparam lparam nsearchid ssearchparams lparam dwsearchid nsearchid m_ned2ksearchid canceled2ksearch deletesearch nsearchid lresult c search results wnd on dbl click tab wparam w param lparam l param tcitem item item mask tcif param if searchselect get item int w param item item l param null m pwndparams set parameters const s search params item l param return true csearchresultswnd ondblclicktab wparam lparam tcif_param getitem wparam lparam m_pwndparams setparameters ssearchparams lparam void c search results wnd on destroy int i tab items searchselect get item count for int i 0 i i tab items i tcitem tci tci mask tcif param if searchselect get item i tci tci l param null delete s search params tci l param c resizable form view on destroy csearchresultswnd ondestroy itabitems getitemcount itabitems tcif_param getitem lparam ssearchparams lparam cresizableformview ondestroy void c search results wnd on sys color change c resizable form view on sys color change set all icons searchlistctrl create menues csearchresultswnd onsyscolorchange cresizableformview onsyscolorchange setallicons createmenues void c search results wnd on timer uint nid event c resizable form view on timer nid event if m utimerlocalserver 0 nid event m utimerlocalserver if the prefs get debug server searches level 0 debug t timeout waiting on search results of local server n the local server did not answer within the timeout verify kill timer m utimerlocalserver m utimerlocalserver 0 start the global search if globsearch if global search timer 0 verify global search timer set timer timer global search 750 0 null else cancel ed2k search else if nid event global search timer if the app serverconnect is connected c server p connected server the app serverconnect get current server if p connected server p connected server the app serverlist get server by address p connected server get address p connected server get port c server toask null while servercount the app serverlist get server count 1 servercount searchprogress step it toask the app serverlist get next search server if toask null break if toask p connected server toask null continue if toask get failed count the prefs get dead server retries toask null continue break if toask if toask supports large filesudp toask getudp flags srv udpflg ext getfiles c safe mem file data 50 uint32 n tag count 1 data writeu int32 n tag count c tag tag flags ct server udpsearch flags srvcap udp newtags largefiles tag flags write new ed2k tag data packet p ext search packet new packet op globsearchreq3 searchpacket size uint32 data get length data seek to begin data read p ext search packet p buffer uint32 data get length memcpy p ext search packet p buffer uint32 data get length searchpacket p buffer searchpacket size the stats add up data overhead server p ext search packet size the app serverconnect sendudp packet p ext search packet toask true if the prefs get debug serverudp level 0 debug t sending s to server 21s 3u of 3u n t op globsearchreq3 ipstr toask get address toask get port servercount the app serverlist get server count else if toask getudp flags srv udpflg ext getfiles if m b64bitsearchpacket toask supports large filesudp searchpacket opcode op globsearchreq2 if the prefs get debug serverudp level 0 debug t sending s to server 21s 3u of 3u n t op globsearchreq2 ipstr toask get address toask get port servercount the app serverlist get server count the stats add up data overhead server searchpacket size the app serverconnect sendudp packet searchpacket toask false else if the prefs get debug serverudp level 0 debug t skipped udp search on server 21s 3u of 3u no large file support n ipstr toask get address toask get port servercount the app serverlist get server count else if m b64bitsearchpacket toask supports large filesudp searchpacket opcode op globsearchreq if the prefs get debug serverudp level 0 debug t sending s to server 21s 3u of 3u n t op globsearchreq1 ipstr toask get address toask get port servercount the app serverlist get server count the stats add up data overhead server searchpacket size the app serverconnect sendudp packet searchpacket toask false else if the prefs get debug serverudp level 0 debug t skipped udp search on server 21s 3u of 3u no large file support n ipstr toask get address toask get port servercount the app serverlist get server count else cancel ed2k search else cancel ed2k search else assert 0 csearchresultswnd ontimer nidevent cresizableformview ontimer nidevent m_utimerlocalserver nidevent m_utimerlocalserver theprefs getdebugserversearcheslevel _t killtimer m_utimerlocalserver m_utimerlocalserver global_search_timer global_search_timer settimer timerglobalsearch canceled2ksearch nidevent global_search_timer theapp isconnected cserver pconnectedserver theapp getcurrentserver pconnectedserver pconnectedserver theapp getserverbyaddress pconnectedserver getaddress pconnectedserver getport cserver theapp getservercount stepit theapp getnextsearchserver pconnectedserver getfailedcount theprefs getdeadserverretries supportslargefilesudp getudpflags srv_udpflg_ext_getfiles csafememfile ntagcount writeuint32 ntagcount ctag tagflags ct_server_udpsearch_flags srvcap_udp_newtags_largefiles tagflags writenewed2ktag pextsearchpacket op_globsearchreq3 getlength seektobegin pextsearchpacket pbuffer getlength pextsearchpacket pbuffer getlength pbuffer thestats addupdataoverheadserver pextsearchpacket theapp sendudppacket pextsearchpacket theprefs getdebugserverudplevel _t _t op__globsearchreq3 getaddress getport theapp getservercount getudpflags srv_udpflg_ext_getfiles m_b64bitsearchpacket supportslargefilesudp op_globsearchreq2 theprefs getdebugserverudplevel _t _t op__globsearchreq2 getaddress getport theapp getservercount thestats addupdataoverheadserver theapp sendudppacket theprefs getdebugserverudplevel _t getaddress getport theapp getservercount m_b64bitsearchpacket supportslargefilesudp op_globsearchreq theprefs getdebugserverudplevel _t _t op__globsearchreq1 getaddress getport theapp getservercount thestats addupdataoverheadserver theapp sendudppacket theprefs getdebugserverudplevel _t getaddress getport theapp getservercount canceled2ksearch canceled2ksearch void c search results wnd on bn clicked download selected start download s download selected csearchresultswnd onbnclickeddownloadselected downloadselected void c search results wnd on bn clicked clear all delete all searches csearchresultswnd onbnclickedclearall deleteallsearches void c search results wnd on size uint n type int cx int cy c resizable form view on size n type cx cy csearchresultswnd onsize ntype cresizableformview onsize ntype void c search results wnd on close do not pass the wm close to the base class since we have a rich edit control and an attached auto complete control the wm close will get generated by the rich edit control when user presses esc while the auto complete is open super on close csearchresultswnd onclose wm_close wm_close __super onclose bool c search results wnd on help info helpinfo p help info the app show help emule faq search return true csearchresultswnd onhelpinfo phelpinfo theapp showhelp emule_faq_search lresult c search results wnd on idle update cmdui wparam w param lparam l param get dlg item idc open params wnd show window the app emuledlg searchwnd is search params wnd visible sw hide sw show return 0 csearchresultswnd onidleupdatecmdui wparam lparam getdlgitem idc_open_params_wnd showwindow theapp issearchparamswndvisible sw_hide sw_show void c search results wnd on bn clicked open params wnd the app emuledlg searchwnd open parameters wnd csearchresultswnd onbnclickedopenparamswnd theapp openparameterswnd void c search results wnd on sys command uint nid lparam l param if nid sc keymenu if l param emule hotmenu accel the app emuledlg send message wm command idc hotmenu else the app emuledlg send message wm syscommand nid l param return super on sys command nid l param csearchresultswnd onsyscommand lparam sc_keymenu lparam emule_hotmenu_accel theapp sendmessage wm_command idc_hotmenu theapp sendmessage wm_syscommand lparam __super onsyscommand lparam c list ctrl item walk this searchlist null m nresultsid 0 set general purpose find true m tooltip new c tool tip ctrlx clistctrlitemwalk m_nresultsid setgeneralpurposefind m_tooltip ctooltipctrlx c search list ctrl c search list ctrl position pos m mapsortselectionstates get start position while pos null int n key c sort selection state p value m mapsortselectionstates get next assoc pos n key p value delete p value m mapsortselectionstates remove all delete m tooltip csearchlistctrl csearchlistctrl m_mapsortselectionstates getstartposition nkey csortselectionstate pvalue m_mapsortselectionstates getnextassoc nkey pvalue pvalue m_mapsortselectionstates removeall m_tooltip void c search list ctrl init c search list in searchlist set name t search list ctrl c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 set image list il dummy image list lvsil small assert get style lvs shareimagelists 0 il dummy image list detach modify style lvs singlesel 0 set style c tool tip ctrl tooltip get tool tips if tooltip m tooltip subclass window tooltip tooltip modify style 0 tts noprefix tooltip set delay time ttdt autopop 20000 tooltip set delay time ttdt initial the prefs get tool tip delay 1000 searchlist in searchlist insert column 0 get res string ids dl filename lvcfmt left 250 insert column 1 get res string ids dl size lvcfmt left 70 insert column 2 get res string ids searchavail the prefs is ext controls enabled t get res string ids dl sources t t lvcfmt left 50 insert column 3 get res string ids complsources lvcfmt left 50 insert column 4 get res string ids type lvcfmt left 65 insert column 5 get res string ids fileid lvcfmt left 220 insert column 6 get res string ids artist lvcfmt left 100 insert column 7 get res string ids album lvcfmt left 100 insert column 8 get res string ids title lvcfmt left 100 insert column 9 get res string ids length lvcfmt left 50 insert column 10 get res string ids bitrate lvcfmt left 50 insert column 11 get res string ids codec lvcfmt left 50 insert column 12 get res string ids folder lvcfmt left 220 insert column 13 get res string ids known lvcfmt left 50 set all icons create menues load settings set highlight colors barry use preferred sort order from preferences if get sort item 1 don t force a sorting if 1 is specified so we can better see how the search results are arriving set sort arrow sort items sort proc get sort item get sort ascending 0 100 csearchlistctrl csearchlist in_searchlist setname _t searchlistctrl cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask setimagelist ildummyimagelist lvsil_small getstyle lvs_shareimagelists ildummyimagelist modifystyle lvs_singlesel setstyle ctooltipctrl gettooltips m_tooltip subclasswindow modifystyle tts_noprefix setdelaytime ttdt_autopop setdelaytime ttdt_initial theprefs gettooltipdelay in_searchlist insertcolumn getresstring ids_dl_filename lvcfmt_left insertcolumn getresstring ids_dl_size lvcfmt_left insertcolumn getresstring ids_searchavail theprefs isextcontrolsenabled _t getresstring ids_dl_sources _t _t lvcfmt_left insertcolumn getresstring ids_complsources lvcfmt_left insertcolumn getresstring ids_type lvcfmt_left insertcolumn getresstring ids_fileid lvcfmt_left insertcolumn getresstring ids_artist lvcfmt_left insertcolumn getresstring ids_album lvcfmt_left insertcolumn getresstring ids_title lvcfmt_left insertcolumn getresstring ids_length lvcfmt_left insertcolumn getresstring ids_bitrate lvcfmt_left insertcolumn getresstring ids_codec lvcfmt_left insertcolumn getresstring ids_folder lvcfmt_left insertcolumn getresstring ids_known lvcfmt_left setallicons createmenues loadsettings sethighlightcolors getsortitem setsortarrow sortitems sortproc getsortitem getsortascending void c search list ctrl create menues if m searchfilemenu verify m searchfilemenu destroy menu m searchfilemenu create popup menu m searchfilemenu add menu title get res string ids file true m searchfilemenu append menu mf string mp resume get res string ids download t resume if the prefs is ext controls enabled m searchfilemenu append menu mf string mp resumepaused get res string ids download t get res string ids paused t if the prefs is ext controls enabled m searchfilemenu append menu mf string mp detail get res string ids showdetails t file info m searchfilemenu append menu mf string mp cmt get res string ids cmt add t filecomments m searchfilemenu append menu mf separator m searchfilemenu append menu mf string mp geted2klink get res string ids dl link1 t ed2k link m searchfilemenu append menu mf string mp gethtmled2klink get res string ids dl link2 t ed2k link m searchfilemenu append menu mf string mp removeselected get res string ids removeselected t delete selected m searchfilemenu append menu mf separator m searchfilemenu append menu mf string mp remove get res string ids removesearchstring t delete m searchfilemenu append menu mf string mp removeall get res string ids removeallsearch t clear complete m searchfilemenu append menu mf separator m searchfilemenu append menu mf string mp find get res string ids find t search m searchfilemenu append menu mf string mp searchrelated get res string ids searchrelated t kad file search csearchlistctrl createmenues m_searchfilemenu m_searchfilemenu destroymenu m_searchfilemenu createpopupmenu m_searchfilemenu addmenutitle getresstring ids_file m_searchfilemenu appendmenu mf_string mp_resume getresstring ids_download _t theprefs isextcontrolsenabled m_searchfilemenu appendmenu mf_string mp_resumepaused getresstring ids_download _t getresstring ids_paused _t theprefs isextcontrolsenabled m_searchfilemenu appendmenu mf_string mp_detail getresstring ids_showdetails _t fileinfo m_searchfilemenu appendmenu mf_string mp_cmt getresstring ids_cmt_add _t m_searchfilemenu appendmenu mf_separator m_searchfilemenu appendmenu mf_string mp_geted2klink getresstring ids_dl_link1 _t ed2klink m_searchfilemenu appendmenu mf_string mp_gethtmled2klink getresstring ids_dl_link2 _t ed2klink m_searchfilemenu appendmenu mf_string mp_removeselected getresstring ids_removeselected _t deleteselected m_searchfilemenu appendmenu mf_separator m_searchfilemenu appendmenu mf_string mp_remove getresstring ids_removesearchstring _t m_searchfilemenu appendmenu mf_string mp_removeall getresstring ids_removeallsearch _t clearcomplete m_searchfilemenu appendmenu mf_separator m_searchfilemenu appendmenu mf_string mp_find getresstring ids_find _t m_searchfilemenu appendmenu mf_string mp_searchrelated getresstring ids_searchrelated _t kadfilesearch void c search list ctrl update sources const c search file toupdate lvfindinfo find find flags lvfi param find l param lparam toupdate int index find item find if index 1 c string str buffer uint32 n sources toupdate get source count int i clients toupdate get clients count if the prefs is ext controls enabled i clients 0 str buffer format t u u n sources i clients else str buffer format t u n sources set item text index 2 str buffer set item text index 3 get complete sources display string toupdate n sources if toupdate is list expanded for position pos the app searchlist list get head position pos null const c search file cur file the app searchlist list get next pos if cur file get list parent toupdate lvfindinfo find find flags lvfi param find l param lparam cur file int index2 find item find if index2 1 update index2 else insert item lvif param lvif text index 1 cur file get file name 0 0 0 lparam cur file update index csearchlistctrl updatesources csearchfile lvfi_param lparam finditem cstring strbuffer nsources getsourcecount iclients getclientscount theprefs isextcontrolsenabled iclients strbuffer _t nsources iclients strbuffer _t nsources setitemtext strbuffer setitemtext getcompletesourcesdisplaystring nsources islistexpanded theapp getheadposition csearchfile cur_file theapp getnext cur_file getlistparent lvfi_param lparam cur_file finditem insertitem lvif_param lvif_text cur_file getfilename cur_file void c search list ctrl add result const c search file toshow update tab counter for the given searchfile c closable tab ctrl searchselect the app emuledlg searchwnd get search selector int i tab items searchselect get item count if i tab items 0 tcitem tabitem tabitem mask tcif param tabitem l param 1 for int tab counter 0 tab counter i tab items tab counter if searchselect get item tab counter tabitem tabitem l param null if const s search params tabitem l param dw searchid toshow get searchid tchar sz text max search expression len 1 tabitem psz text sz text tabitem cch text max arrsize sz text tabitem mask tcif text if searchselect get item tab counter tabitem todo searching for the last is wrong if the search expression contains and characters we ll truncate the string lptstr psz tcsrchr sz text t if psz if psz sz text psz psz t 0 c string source str source str format t s u sz text searchlist get found files toshow get searchid tabitem psz text const cast lptstr lpctstr source str searchselect set item tab counter tabitem if searchselect get cur sel tab counter searchselect highlight item tab counter break if toshow get searchid m nresultsid return todo here we have a problem since this listview control is owner drawn the listview items may no longer contain the actual information which is displayed the usage of the find command may therefore deal with wrong item contents which are stored in the listview items right here in this function int itemnr insert item lvif text lvif param get item count toshow get file name 0 0 0 lparam toshow set item text itemnr 1 cast itox bytes toshow get file size false false c string str buffer uint32 n sources toshow get source count int i clients toshow get clients count if the prefs is ext controls enabled i clients 0 str buffer format t u u n sources i clients else str buffer format t u n sources set item text itemnr 2 str buffer set item text itemnr 3 get complete sources display string toshow n sources set item text itemnr 4 toshow get file type display str set item text itemnr 5 md4str toshow get file hash set item text itemnr 6 toshow get str tag value ft media artist set item text itemnr 7 toshow get str tag value ft media album set item text itemnr 8 toshow get str tag value ft media title uint32 n media length toshow get int tag value ft media length tchar cbuffer 80 if n media length c string str media length sec to time length n media length str media length sntprintf cbuffer arrsize cbuffer t s str media length else cbuffer 0 t 0 set item text itemnr 9 cbuffer uint32 n bitrate toshow get int tag value ft media bitrate if n bitrate sntprintf cbuffer arrsize cbuffer t u s n bitrate get res string ids kbitssec else cbuffer 0 t 0 set item text itemnr 10 cbuffer set item text itemnr 11 toshow get str tag value ft media codec if toshow get directory set item text itemnr 12 toshow get directory if toshow m eknown c search file shared set item text itemnr 13 get res string ids shared else if toshow m eknown c search file downloading set item text itemnr 13 get res string ids downloading else if toshow m eknown c search file downloaded set item text itemnr 13 get res string ids downloaded csearchlistctrl addresult csearchfile cclosabletabctrl theapp getsearchselector itabitems getitemcount itabitems tcif_param lparam tabcounter tabcounter itabitems tabcounter getitem tabcounter lparam ssearchparams lparam dwsearchid getsearchid sztext max_search_expression_len psztext sztext cchtextmax sztext tcif_text getitem tabcounter _tcsrchr sztext _t sztext _t cstring sourcestr sourcestr _t sztext getfoundfiles getsearchid psztext const_cast sourcestr setitem tabcounter getcursel tabcounter highlightitem tabcounter getsearchid m_nresultsid insertitem lvif_text lvif_param getitemcount getfilename setitemtext castitoxbytes getfilesize cstring strbuffer nsources getsourcecount iclients getclientscount theprefs isextcontrolsenabled iclients strbuffer _t nsources iclients strbuffer _t nsources setitemtext strbuffer setitemtext getcompletesourcesdisplaystring nsources setitemtext getfiletypedisplaystr setitemtext getfilehash setitemtext getstrtagvalue ft_media_artist setitemtext getstrtagvalue ft_media_album setitemtext getstrtagvalue ft_media_title nmedialength getinttagvalue ft_media_length nmedialength cstring strmedialength sectotimelength nmedialength strmedialength _sntprintf _t strmedialength _t setitemtext nbitrate getinttagvalue ft_media_bitrate nbitrate _sntprintf _t nbitrate getresstring ids_kbitssec _t setitemtext setitemtext getstrtagvalue ft_media_codec getdirectory setitemtext getdirectory m_eknown csearchfile setitemtext getresstring ids_shared m_eknown csearchfile setitemtext getresstring ids_downloading m_eknown csearchfile setitemtext getresstring ids_downloaded void c search list ctrl remove result const c search file toremove lvfindinfo find find flags lvfi param find l param lparam toremove int i item find item find if i item 1 delete item i item csearchlistctrl removeresult csearchfile lvfi_param lparam iitem finditem iitem deleteitem iitem void c search list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res for int icol 0 icol p header ctrl get item count icol switch icol case 0 str res get res string ids dl filename break case 1 str res get res string ids dl size break case 2 str res get res string ids searchavail the prefs is ext controls enabled t get res string ids dl sources t t break case 3 str res get res string ids complsources break case 4 str res get res string ids type break case 5 str res get res string ids fileid break case 6 str res get res string ids artist break case 7 str res get res string ids album break case 8 str res get res string ids title break case 9 str res get res string ids length break case 10 str res get res string ids bitrate break case 11 str res get res string ids codec break case 12 str res get res string ids folder break case 13 str res get res string ids known break hdi psz text const cast lptstr lpctstr str res p header ctrl set item icol hdi create menues csearchlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres pheaderctrl getitemcount strres getresstring ids_dl_filename strres getresstring ids_dl_size strres getresstring ids_searchavail theprefs isextcontrolsenabled _t getresstring ids_dl_sources _t _t strres getresstring ids_complsources strres getresstring ids_type strres getresstring ids_fileid strres getresstring ids_artist strres getresstring ids_album strres getresstring ids_title strres getresstring ids_length strres getresstring ids_bitrate strres getresstring ids_codec strres getresstring ids_folder strres getresstring ids_known psztext const_cast strres pheaderctrl setitem createmenues void c search list ctrl show results uint32 n resultsid if m nresultsid 0 n resultsid m nresultsid store the current state c sort selection state p cur state new c sort selection state position pos get first selected item position while pos null p cur state m aselecteditems add get next selected item pos p cur state m nsortitem get sort item p cur state m bsortascending get sort ascending p cur state m nscrollposition get top index m mapsortselectionstates set at m nresultsid p cur state delete all items recover stored state c sort selection state p new state null if n resultsid 0 n resultsid m nresultsid m mapsortselectionstates lookup n resultsid p new state m mapsortselectionstates remove key n resultsid sort order the prefs set column sort item c preferences table search p new state m nsortitem the prefs set column sort ascending c preferences table search p new state m bsortascending set sort arrow p new state m nsortitem p new state m bsortascending sort items sort proc p new state m nsortitem p new state m bsortascending 0 100 fill in the items m nresultsid n resultsid searchlist show results m nresultsid set stored selectionstates for int i 0 i p new state m aselecteditems get count i set item state p new state m aselecteditems i lvis selected lvis selected point point if p new state m nscrollposition 0 get item position p new state m nscrollposition 1 point point x 0 scroll c size point delete p new state else m nresultsid n resultsid searchlist show results m nresultsid csearchlistctrl showresults nresultsid m_nresultsid nresultsid m_nresultsid csortselectionstate pcurstate csortselectionstate getfirstselecteditemposition pcurstate m_aselecteditems getnextselecteditem pcurstate m_nsortitem getsortitem pcurstate m_bsortascending getsortascending pcurstate m_nscrollposition gettopindex m_mapsortselectionstates setat m_nresultsid pcurstate deleteallitems csortselectionstate pnewstate nresultsid nresultsid m_nresultsid m_mapsortselectionstates nresultsid pnewstate m_mapsortselectionstates removekey nresultsid theprefs setcolumnsortitem cpreferences tablesearch pnewstate m_nsortitem theprefs setcolumnsortascending cpreferences tablesearch pnewstate m_bsortascending setsortarrow pnewstate m_nsortitem pnewstate m_bsortascending sortitems sortproc pnewstate m_nsortitem pnewstate m_bsortascending m_nresultsid nresultsid showresults m_nresultsid pnewstate m_aselecteditems getcount setitemstate pnewstate m_aselecteditems lvis_selected lvis_selected pnewstate m_nscrollposition getitemposition pnewstate m_nscrollposition csize pnewstate m_nresultsid nresultsid showresults m_nresultsid void c search list ctrl clear result view state uint32 n resultsid just clean up our stored states for this search c sort selection state p state null if m mapsortselectionstates lookup n resultsid p state m mapsortselectionstates remove key n resultsid delete p state csearchlistctrl clearresultviewstate nresultsid csortselectionstate pstate m_mapsortselectionstates nresultsid pstate m_mapsortselectionstates removekey nresultsid pstate void c search list ctrl update search c search file toupdate if toupdate the app emuledlg is running return lvfindinfo find find flags lvfi param find l param lparam toupdate int index find item find if index 1 update index csearchlistctrl updatesearch csearchfile theapp isrunning lvfi_param lparam finditem colorref c search list ctrl get search item color const c search file src const c known file p file the app downloadqueue get file byid src get file hash if p file if p file is part file src set known type c search file downloading if c part file p file get status ps paused return m crsearchresultdownloadstopped return m crsearchresultdownloading else src set known type c search file shared return m crsearchresultshareing else if the app sharedfiles get file byid src get file hash src set known type c search file shared return m crsearchresultshareing else if the app knownfiles find known file byid src get file hash src set known type c search file downloaded return m crsearchresultknown else if the app knownfiles is cancelled file byid src get file hash src set known type c search file cancelled return m crsearchresultcancelled unknown file show shades of a color int srccnt src get source count if srccnt 0 srccnt return m crshades srccnt avblyshadecount avblyshadecount 1 srccnt csearchlistctrl getsearchitemcolor csearchfile cknownfile pfile theapp getfilebyid getfilehash pfile pfile ispartfile setknowntype csearchfile cpartfile pfile getstatus ps_paused m_crsearchresultdownloadstopped m_crsearchresultdownloading setknowntype csearchfile m_crsearchresultshareing theapp getfilebyid getfilehash setknowntype csearchfile m_crsearchresultshareing theapp findknownfilebyid getfilehash setknowntype csearchfile m_crsearchresultknown theapp iscancelledfilebyid getfilehash setknowntype csearchfile m_crsearchresultcancelled getsourcecount m_crshades c string c search list ctrl get complete sources display string const c search file p file uint u sources bool pb complete const uint u complete sources p file get int tag value ft complete sources int i complete p file is complete u sources u complete sources if we have no complete info at all but the file size is partsize we though know that the file is complete otherwise it would not be shared if i complete 0 p file get file size uint64 partsize i complete 1 if this search result is from a remote client s shared file list we know the complete count if p file get directory null u complete sources 1 c string str if i complete 0 0 unknown str t if pb complete pb complete true treat unknown as complete else if i complete 0 0 we know it s complete if u sources u complete sources str format t u u complete sources 100 u sources if the prefs is ext controls enabled str append format t u u complete sources else we know it s complete but we don t know the degree for files partsize in kad searches str get res string ids yes if pb complete pb complete true else 0 we know it s not complete str t 0 if the prefs is ext controls enabled str append format t 0 if pb complete pb complete false return str cstring csearchlistctrl getcompletesourcesdisplaystring csearchfile pfile usources pbcomplete ucompletesources pfile getinttagvalue ft_complete_sources icomplete pfile iscomplete usources ucompletesources icomplete pfile getfilesize icomplete pfile getdirectory ucompletesources cstring icomplete _t pbcomplete pbcomplete icomplete usources ucompletesources _t ucompletesources usources theprefs isextcontrolsenabled appendformat _t ucompletesources getresstring ids_yes pbcomplete pbcomplete _t theprefs isextcontrolsenabled appendformat _t pbcomplete pbcomplete void c search list ctrl expand collapse item int i item int i action if i item 1 return c search file searchfile c search file get item data i item if searchfile get list parent null searchfile searchfile get list parent lvfindinfo find find flags lvfi param find l param lparam searchfile i item find item find if i item 1 return if searchfile return if searchfile is list expanded if i action collapse only only expand when more than one child more than the original entry itself if searchfile get list child count 2 return go through the whole list to find out the sources for this file set redraw false for position pos the app searchlist list get head position pos null const c search file cur file the app searchlist list get next pos if cur file get list parent searchfile searchfile set list expanded true insert item lvif param lvif text i item 1 cur file get file name 0 0 0 lparam cur file set redraw true else if i action expand collapse i action collapse only if get item state i item lvis selected lvis focused lvis selected lvis focused set item state i item lvis selected lvis focused lvis selected lvis focused set selection mark i item hide sources searchfile update i item csearchlistctrl expandcollapseitem iitem iaction iitem csearchfile csearchfile getitemdata iitem getlistparent getlistparent lvfi_param lparam iitem finditem iitem islistexpanded iaction collapse_only getlistchildcount setredraw theapp getheadposition csearchfile cur_file theapp getnext cur_file getlistparent setlistexpanded insertitem lvif_param lvif_text iitem cur_file getfilename cur_file setredraw iaction expand_collapse iaction collapse_only getitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setitemstate iitem lvis_selected lvis_focused lvis_selected lvis_focused setselectionmark iitem hidesources iitem void c search list ctrl hide sources c search file to collapse set redraw false int pre 0 int post 0 for int i 0 i get item count i const c search file item c search file get item data i if item get list parent to collapse pre delete item i post if pre post 0 to collapse set list expanded false set redraw true csearchlistctrl hidesources csearchfile tocollapse setredraw getitemcount csearchfile csearchfile getitemdata getlistparent tocollapse deleteitem tocollapse setlistexpanded setredraw void c search list ctrl set style if the prefs is double click enabled set extended style lvs ex fullrowselect lvs ex infotip else set extended style lvs ex oneclickactivate lvs ex fullrowselect lvs ex infotip csearchlistctrl setstyle theprefs isdoubleclickenabled setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip setextendedstyle lvs_ex_oneclickactivate lvs_ex_fullrowselect lvs_ex_infotip void c search list ctrl set highlight colors default colors blue user does not know that file shades of blue are used to indicate availability of file red user already has the file it is currently downloading or it is currently shared red means user can not add this file green user knows the file it was already download once but is currently not in share colorref cr search result avbly base rgb 0 0 255 m crsearchresultdownloading rgb 255 0 0 m crsearchresultdownloadstopped rgb 255 0 0 m crsearchresultshareing rgb 255 0 0 m crsearchresultknown rgb 0 128 0 m crsearchresultcancelled rgb 0 128 0 the app load skin color t searchresultslvfg downloading m crsearchresultdownloading if the app load skin color t searchresultslvfg downloadstopped m crsearchresultdownloadstopped m crsearchresultdownloadstopped m crsearchresultdownloading the app load skin color t searchresultslvfg sharing m crsearchresultshareing the app load skin color t searchresultslvfg known m crsearchresultknown the app load skin color t searchresultslvfg avblybase cr search result avbly base precalculate sources shades colorref normfgc get text color float rdelta float getr value cr search result avbly base getr value normfgc avblyshadecount float gdelta float getg value cr search result avbly base getg value normfgc avblyshadecount float bdelta float getb value cr search result avbly base getb value normfgc avblyshadecount for int shades 0 shades avblyshadecount shades m crshades shades rgb getr value normfgc rdelta shades getg value normfgc gdelta shades getb value normfgc bdelta shades csearchlistctrl sethighlightcolors crsearchresultavblybase m_crsearchresultdownloading m_crsearchresultdownloadstopped m_crsearchresultshareing m_crsearchresultknown m_crsearchresultcancelled theapp loadskincolor _t searchresultslvfg_downloading m_crsearchresultdownloading theapp loadskincolor _t searchresultslvfg_downloadstopped m_crsearchresultdownloadstopped m_crsearchresultdownloadstopped m_crsearchresultdownloading theapp loadskincolor _t searchresultslvfg_sharing m_crsearchresultshareing theapp loadskincolor _t searchresultslvfg_known m_crsearchresultknown theapp loadskincolor _t searchresultslvfg_avblybase crsearchresultavblybase gettextcolor getrvalue crsearchresultavblybase getrvalue getgvalue crsearchresultavblybase getgvalue getbvalue crsearchresultavblybase getbvalue m_crshades getrvalue getgvalue getbvalue void c search list ctrl set all icons m imagelist delete image list m imagelist create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 m imagelist set bk color clr none m imagelist add c temp icon loader t empty m imagelist add c temp icon loader t rating notrated m imagelist add c temp icon loader t rating fake m imagelist add c temp icon loader t rating poor m imagelist add c temp icon loader t rating fair m imagelist add c temp icon loader t rating good m imagelist add c temp icon loader t rating excellent m imagelist set overlay image m imagelist add c temp icon loader t file comments ovl 1 csearchlistctrl setallicons m_imagelist deleteimagelist m_imagelist theapp m_idfltimagelistcolorflags ilc_mask m_imagelist setbkcolor clr_none m_imagelist ctempiconloader _t m_imagelist ctempiconloader _t rating_notrated m_imagelist ctempiconloader _t rating_fake m_imagelist ctempiconloader _t rating_poor m_imagelist ctempiconloader _t rating_fair m_imagelist ctempiconloader _t rating_good m_imagelist ctempiconloader _t rating_excellent m_imagelist setoverlayimage m_imagelist ctempiconloader _t filecommentsovl void c search list ctrl draw source parent cdc dc int n column lprect lp rect const c search file src if src return if lp rect left lp rect right c string buffer switch n column case 0 file name uint u offset 22 if the prefs show rating indicator src has comment src has rating u offset 16 lp rect left u offset dc draw text src get file name src get file name get length lp rect dlc dt text lp rect left u offset break case 1 file size buffer cast itox bytes src get file size false false dc draw text buffer buffer get length lp rect dlc dt text dt right break case 2 avail buffer format t u src get source count if the prefs is ext controls enabled int i clients src get clients count if i clients 0 buffer append format t u i clients dc draw text buffer buffer get length lp rect dlc dt text dt right break case 3 complete sources bool b complete false buffer get complete sources display string src src get source count b complete colorref cr old text color 0 if b complete cr old text color dc set text color rgb 255 0 0 dc draw text buffer buffer get length lp rect dlc dt text dt right if b complete dc set text color cr old text color break case 4 file type dc draw text src get file type display str src get file type display str get length lp rect dlc dt text break case 5 file hash buffer md4str src get file hash dc draw text buffer buffer get length lp rect dlc dt text break case 6 buffer src get str tag value ft media artist dc draw text buffer buffer get length lp rect dlc dt text break case 7 buffer src get str tag value ft media album dc draw text buffer buffer get length lp rect dlc dt text break case 8 buffer src get str tag value ft media title dc draw text buffer buffer get length lp rect dlc dt text break case 9 uint32 n media length src get int tag value ft media length if n media length sec to time length n media length buffer dc draw text buffer buffer get length lp rect dlc dt text dt right break case 10 uint32 n bitrate src get int tag value ft media bitrate if n bitrate buffer format t u s n bitrate get res string ids kbitssec dc draw text buffer buffer get length lp rect dlc dt text dt right break case 11 buffer src get str tag value ft media codec dc draw text buffer buffer get length lp rect dlc dt text break case 12 dir if src get directory buffer src get directory dc draw text buffer buffer get length lp rect dlc dt text break case 13 if src m eknown c search file shared buffer get res string ids shared else if src m eknown c search file downloading buffer get res string ids downloading else if src m eknown c search file downloaded buffer get res string ids downloaded else if src m eknown c search file cancelled buffer get res string ids cancelled else buffer empty dc draw text buffer buffer get length lp rect dlc dt text break csearchlistctrl drawsourceparent ncolumn lprect csearchfile lprect lprect cstring ncolumn uoffset theprefs showratingindicator hascomment hasrating uoffset lprect uoffset drawtext getfilename getfilename getlength lprect dlc_dt_text lprect uoffset castitoxbytes getfilesize drawtext getlength lprect dlc_dt_text dt_right _t getsourcecount theprefs isextcontrolsenabled iclients getclientscount iclients appendformat _t iclients drawtext getlength lprect dlc_dt_text dt_right bcomplete getcompletesourcesdisplaystring getsourcecount bcomplete croldtextcolor bcomplete croldtextcolor settextcolor drawtext getlength lprect dlc_dt_text dt_right bcomplete settextcolor croldtextcolor drawtext getfiletypedisplaystr getfiletypedisplaystr getlength lprect dlc_dt_text getfilehash drawtext getlength lprect dlc_dt_text getstrtagvalue ft_media_artist drawtext getlength lprect dlc_dt_text getstrtagvalue ft_media_album drawtext getlength lprect dlc_dt_text getstrtagvalue ft_media_title drawtext getlength lprect dlc_dt_text nmedialength getinttagvalue ft_media_length nmedialength sectotimelength nmedialength drawtext getlength lprect dlc_dt_text dt_right nbitrate getinttagvalue ft_media_bitrate nbitrate _t nbitrate getresstring ids_kbitssec drawtext getlength lprect dlc_dt_text dt_right getstrtagvalue ft_media_codec drawtext getlength lprect dlc_dt_text getdirectory getdirectory drawtext getlength lprect dlc_dt_text m_eknown csearchfile getresstring ids_shared m_eknown csearchfile getresstring ids_downloading m_eknown csearchfile getresstring ids_downloaded m_eknown csearchfile getresstring ids_cancelled drawtext getlength lprect dlc_dt_text void c search list ctrl draw source child cdc dc int n column lprect lp rect const c search file src if src return if lp rect left lp rect right c string buffer switch n column case 0 file name uint u offset 30 if the prefs show rating indicator src has comment src has rating u offset 16 lp rect left u offset dc draw text src get file name src get file name get length lp rect dlc dt text lp rect left u offset break case 1 file size if the prefs get debug search result detail level 1 if src get file size src get list parent get file size buffer cast itox bytes src get file size false false colorref cr old text color dc set text color rgb 255 0 0 dc draw text buffer buffer get length lp rect dlc dt text dt right dc set text color cr old text color break case 2 avail number of same filenames buffer format t u src get list child count dc draw text buffer buffer get length lp rect dlc dt text dt right break case 3 complete sources if the prefs get debug search result detail level 1 if the prefs is ext controls enabled buffer get complete sources display string src src get source count dc draw text buffer buffer get length lp rect dlc dt text dt right break case 4 file type break case 5 file hash break case 6 buffer src get str tag value ft media artist dc draw text buffer buffer get length lp rect dlc dt text break case 7 buffer src get str tag value ft media album dc draw text buffer buffer get length lp rect dlc dt text break case 8 buffer src get str tag value ft media title dc draw text buffer buffer get length lp rect dlc dt text break case 9 uint32 n media length src get int tag value ft media length if n media length sec to time length n media length buffer dc draw text buffer buffer get length lp rect dlc dt text dt right break case 10 uint32 n bitrate src get int tag value ft media bitrate if n bitrate buffer format t u s n bitrate get res string ids kbitssec dc draw text buffer buffer get length lp rect dlc dt text dt right break case 11 buffer src get str tag value ft media codec dc draw text buffer buffer get length lp rect dlc dt text break case 12 dir if src get directory buffer src get directory dc draw text buffer buffer get length lp rect dlc dt text break case 13 if src m eknown c search file shared buffer get res string ids shared else if src m eknown c search file downloading buffer get res string ids downloading else if src m eknown c search file downloaded buffer get res string ids downloaded else if src m eknown c search file cancelled buffer get res string ids cancelled else buffer empty dc draw text buffer buffer get length lp rect dlc dt text break csearchlistctrl drawsourcechild ncolumn lprect csearchfile lprect lprect cstring ncolumn uoffset theprefs showratingindicator hascomment hasrating uoffset lprect uoffset drawtext getfilename getfilename getlength lprect dlc_dt_text lprect uoffset theprefs getdebugsearchresultdetaillevel getfilesize getlistparent getfilesize castitoxbytes getfilesize croldtextcolor settextcolor drawtext getlength lprect dlc_dt_text dt_right settextcolor croldtextcolor _t getlistchildcount drawtext getlength lprect dlc_dt_text dt_right theprefs getdebugsearchresultdetaillevel theprefs isextcontrolsenabled getcompletesourcesdisplaystring getsourcecount drawtext getlength lprect dlc_dt_text dt_right getstrtagvalue ft_media_artist drawtext getlength lprect dlc_dt_text getstrtagvalue ft_media_album drawtext getlength lprect dlc_dt_text getstrtagvalue ft_media_title drawtext getlength lprect dlc_dt_text nmedialength getinttagvalue ft_media_length nmedialength sectotimelength nmedialength drawtext getlength lprect dlc_dt_text dt_right nbitrate getinttagvalue ft_media_bitrate nbitrate _t nbitrate getresstring ids_kbitssec drawtext getlength lprect dlc_dt_text dt_right getstrtagvalue ft_media_codec drawtext getlength lprect dlc_dt_text getdirectory getdirectory drawtext getlength lprect dlc_dt_text m_eknown csearchfile getresstring ids_shared m_eknown csearchfile getresstring ids_downloading m_eknown csearchfile getresstring ids_downloaded m_eknown csearchfile getresstring ids_cancelled drawtext getlength lprect dlc_dt_text int c search list ctrl compare const c search file item1 const c search file item2 lparam l param sort switch l param sort case 0 filename asc return compare locale string no case item1 get file name item2 get file name case 100 filename desc return compare locale string no case item2 get file name item1 get file name case 1 size asc return compare unsigned64 item1 get file size item2 get file size case 101 size desc return compare unsigned64 item2 get file size item1 get file size case 2 sources asc return compare unsigned item1 get int tag value ft sources item2 get int tag value ft sources case 102 sources desc return compare unsigned item2 get int tag value ft sources item1 get int tag value ft sources case 3 complete sources asc if item1 get int tag value ft sources 0 item2 get int tag value ft sources 0 item1 is kademlia item2 is kademlia return 0 should never happen just a sanity check return compare unsigned item1 get int tag value ft complete sources 100 item1 get int tag value ft sources item2 get int tag value ft complete sources 100 item2 get int tag value ft sources case 103 complete sources desc if item1 get int tag value ft sources 0 item2 get int tag value ft sources 0 item1 is kademlia item2 is kademlia return 0 should never happen just a sanity check return compare unsigned item2 get int tag value ft complete sources 100 item2 get int tag value ft sources item1 get int tag value ft complete sources 100 item1 get int tag value ft sources case 4 type asc return item1 get file type display str compare item2 get file type display str case 104 type desc return item2 get file type display str compare item1 get file type display str case 5 filehash asc return memcmp item1 get file hash item2 get file hash 16 case 105 filehash desc return memcmp item2 get file hash item1 get file hash 16 case 6 return compare opt locale string no case item1 get str tag value ft media artist item2 get str tag value ft media artist case 106 return compare opt locale string no case item1 get str tag value ft media artist item2 get str tag value ft media artist case 7 return compare opt locale string no case item1 get str tag value ft media album item2 get str tag value ft media album case 107 return compare opt locale string no case item1 get str tag value ft media album item2 get str tag value ft media album case 8 return compare opt locale string no case item1 get str tag value ft media title item2 get str tag value ft media title case 108 return compare opt locale string no case item1 get str tag value ft media title item2 get str tag value ft media title case 9 return compare unsigned item1 get int tag value ft media length item2 get int tag value ft media length case 109 return compare unsigned item1 get int tag value ft media length item2 get int tag value ft media length case 10 return compare unsigned item1 get int tag value ft media bitrate item2 get int tag value ft media bitrate case 110 return compare unsigned item1 get int tag value ft media bitrate item2 get int tag value ft media bitrate case 11 return compare opt locale string no case item1 get str tag value ft media codec item2 get str tag value ft media codec case 111 return compare opt locale string no case item1 get str tag value ft media codec item2 get str tag value ft media codec case 12 path asc return compare opt locale string no case item1 get directory item2 get directory case 112 path desc return compare opt locale string no case item1 get directory item2 get directory case 13 return item1 get known type item2 get known type case 113 return item1 get known type item2 get known type default return 0 csearchlistctrl csearchfile csearchfile lparamsort lparamsort comparelocalestringnocase getfilename getfilename comparelocalestringnocase getfilename getfilename compareunsigned64 getfilesize getfilesize compareunsigned64 getfilesize getfilesize compareunsigned getinttagvalue ft_sources getinttagvalue ft_sources compareunsigned getinttagvalue ft_sources getinttagvalue ft_sources getinttagvalue ft_sources getinttagvalue ft_sources iskademlia iskademlia compareunsigned getinttagvalue ft_complete_sources getinttagvalue ft_sources getinttagvalue ft_complete_sources getinttagvalue ft_sources getinttagvalue ft_sources getinttagvalue ft_sources iskademlia iskademlia compareunsigned getinttagvalue ft_complete_sources getinttagvalue ft_sources getinttagvalue ft_complete_sources getinttagvalue ft_sources getfiletypedisplaystr getfiletypedisplaystr getfiletypedisplaystr getfiletypedisplaystr getfilehash getfilehash getfilehash getfilehash compareoptlocalestringnocase getstrtagvalue ft_media_artist getstrtagvalue ft_media_artist compareoptlocalestringnocase getstrtagvalue ft_media_artist getstrtagvalue ft_media_artist compareoptlocalestringnocase getstrtagvalue ft_media_album getstrtagvalue ft_media_album compareoptlocalestringnocase getstrtagvalue ft_media_album getstrtagvalue ft_media_album compareoptlocalestringnocase getstrtagvalue ft_media_title getstrtagvalue ft_media_title compareoptlocalestringnocase getstrtagvalue ft_media_title getstrtagvalue ft_media_title compareunsigned getinttagvalue ft_media_length getinttagvalue ft_media_length compareunsigned getinttagvalue ft_media_length getinttagvalue ft_media_length compareunsigned getinttagvalue ft_media_bitrate getinttagvalue ft_media_bitrate compareunsigned getinttagvalue ft_media_bitrate getinttagvalue ft_media_bitrate compareoptlocalestringnocase getstrtagvalue ft_media_codec getstrtagvalue ft_media_codec compareoptlocalestringnocase getstrtagvalue ft_media_codec getstrtagvalue ft_media_codec compareoptlocalestringnocase getdirectory getdirectory compareoptlocalestringnocase getdirectory getdirectory getknowntype getknowntype getknowntype getknowntype int c search list ctrl compare child const c search file item1 const c search file item2 lparam l param sort switch l param sort case 0 filename asc return compare locale string no case item1 get file name item2 get file name case 100 filename desc return compare locale string no case item2 get file name item1 get file name default always sort by descending availability return compare unsigned item2 get int tag value ft sources item1 get int tag value ft sources csearchlistctrl comparechild csearchfile csearchfile lparamsort lparamsort comparelocalestringnocase getfilename getfilename comparelocalestringnocase getfilename getfilename compareunsigned getinttagvalue ft_sources getinttagvalue ft_sources int c search list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort const c search file item1 c search file l param1 const c search file item2 c search file l param2 int org sort l param sort int sort mod 1 if l param sort 100 sort mod 1 l param sort 100 int comp if item1 get list parent null item2 get list parent null if item1 item2 get list parent return 1 comp compare item1 item2 m list parent l param sort sort mod else if item2 get list parent null item1 get list parent null if item1 m list parent item2 return 1 comp compare item1 get list parent item2 l param sort sort mod else if item1 get list parent null comp compare item1 item2 l param sort sort mod else comp compare item1 get list parent item2 get list parent l param sort if comp 0 return sort mod comp if item1 get list parent null item2 get list parent null item2 get list parent null item1 get list parent null if item1 get list parent null return 1 else return 1 comp compare child item1 item2 l param sort int dw next sort call secondary sortorder if this one results in equal note yes i know this call is evil oo wise but better than changing a lot more code while we have only one instance anyway might be fixed later if comp 0 dw next sort the app emuledlg searchwnd m pwndresults searchlistctrl get next sort order org sort 1 comp sort proc l param1 l param2 dw next sort return comp csearchlistctrl sortproc lparam1 lparam2 lparamsort csearchfile csearchfile lparam1 csearchfile csearchfile lparam2 orgsort lparamsort sortmod lparamsort sortmod lparamsort getlistparent getlistparent getlistparent m_list_parent lparamsort sortmod getlistparent getlistparent m_list_parent getlistparent lparamsort sortmod getlistparent lparamsort sortmod getlistparent getlistparent lparamsort sortmod getlistparent getlistparent getlistparent getlistparent getlistparent comparechild lparamsort dwnextsort dwnextsort theapp m_pwndresults getnextsortorder orgsort sortproc lparam1 lparam2 dwnextsort bool c search list ctrl on command wparam w param lparam l param w param loword w param if w param mp find on find start return true c typed ptr list c ptr list c search file selected list position pos get first selected item position while pos null int index get next selected item pos if index 0 selected list add tail c search file get item data index if selected list get count 0 c search file file selected list get head switch w param case mp geted2klink c wait cursor cur wait c string clpbrd position pos selected list get head position while pos null file selected list get next pos if clpbrd is empty clpbrd t r n clpbrd createed2k link file the app copy text to clipboard clpbrd return true case mp gethtmled2klink c wait cursor cur wait c string clpbrd position pos selected list get head position while pos null file selected list get next pos if clpbrd is empty clpbrd t br r n clpbrd createhtmled2k link file the app copy text to clipboard clpbrd return true case mp resume case mp resumepaused case ida enter the app emuledlg searchwnd download selected w param mp resumepaused return true case mp removeselected case mpg delete c wait cursor cur wait set redraw false position pos selected list get head position while pos null file selected list get next pos hide sources file the app searchlist remove result file auto select item set redraw true return true case mp detail case mpg altenter c search result file detail sheet sheet selected list 0 this sheet do modal return true case mp cmt c search result file detail sheet sheet selected list idd commentlst this sheet do modal return true case mp preview if file if file get previews get size 0 already have previews new preview dlg set file file else c up down client newclient new c up down client null file get client port file get clientid file get client serverip file get client server port true if the app clientlist attach to already known newclient null the app clientlist add client newclient newclient send preview request file add to res later add log line true t preview requested please wait return true case mp searchrelated just a shortcut for the user typing into the searchfield related filehash if selected list get count 1 file selected list get head the app emuledlg searchwnd search related files file return true default if w param mp weburl w param mp weburl 256 the web services runurl file w param return true break switch w param case mp removeall c wait cursor cur wait the app emuledlg searchwnd delete all searches break case mp remove c wait cursor cur wait the app emuledlg searchwnd delete search m nresultsid break return false csearchlistctrl oncommand wparam lparam wparam wparam wparam mp_find onfindstart ctypedptrlist cptrlist csearchfile selectedlist getfirstselecteditemposition getnextselecteditem selectedlist addtail csearchfile getitemdata selectedlist getcount csearchfile selectedlist gethead wparam mp_geted2klink cwaitcursor curwait cstring selectedlist getheadposition selectedlist getnext isempty _t createed2klink theapp copytexttoclipboard mp_gethtmled2klink cwaitcursor curwait cstring selectedlist getheadposition selectedlist getnext isempty _t createhtmled2klink theapp copytexttoclipboard mp_resume mp_resumepaused ida_enter theapp downloadselected wparam mp_resumepaused mp_removeselected mpg_delete cwaitcursor curwait setredraw selectedlist getheadposition selectedlist getnext hidesources theapp removeresult autoselectitem setredraw mp_detail mpg_altenter csearchresultfiledetailsheet selectedlist domodal mp_cmt csearchresultfiledetailsheet selectedlist idd_commentlst domodal mp_preview getpreviews getsize previewdlg setfile cupdownclient cupdownclient getclientport getclientid getclientserverip getclientserverport theapp attachtoalreadyknown theapp addclient sendpreviewrequest addlogline _t mp_searchrelated selectedlist getcount selectedlist gethead theapp searchrelatedfiles wparam mp_weburl wparam mp_weburl thewebservices wparam wparam mp_removeall cwaitcursor curwait theapp deleteallsearches mp_remove cwaitcursor curwait theapp deletesearch m_nresultsid void c search list ctrl draw item lpdrawitemstruct lp draw item struct johntodo display comment icon when available if the app emuledlg is running return if lp draw item struct item data return cdc odc cdc from handle lp draw item struct hdc bool b ctrl focused get focus this get style lvs showselalways if lp draw item struct item state ods selected if b ctrl focused odc set bk color m crhighlight else odc set bk color m crnohighlight else odc set bk color get bk color c search file content c search file lp draw item struct item data c memdc dc odc lp draw item struct rc item c font p old font dc select object get font c rect cur rec lp draw item struct rc item colorref cr old text color dc set text color g blowcolordesktop lp draw item struct item state ods selected 0 get search item color content m crhighlighttext int i old bk mode if m crwindowtextbk clr none def window proc wm erasebkgnd wparam hdc dc 0 i old bk mode dc set bk mode transparent else i old bk mode opaque bool not last lp draw item struct itemid 1 uint get item count bool not first lp draw item struct itemid 0 int tree start 0 int tree end 0 offset was 4 now it s the standard 2 spaces int i offset dc get text extent t 1 cx 2 c header ctrl p header ctrl get header ctrl int i count p header ctrl get item count cur rec right cur rec left cur rec right i offset cur rec left i offset icon int ofs if content get list parent null ofs 14 indent child items else ofs 6 if the prefs show rating indicator content has comment content has rating m imagelist draw dc content user rating 1 c point cur rec left ofs 18 cur rec top ild normal int i image the app get file type system image idx content get file name imagelist draw the app get system image list i image dc cur rec left ofs cur rec top ild normal ild transparent parent entries if content get list parent null for int i current 0 i current i count i current int i column p header ctrl order to index i current if is column hidden i column int cx c list ctrl get column width i column if i column 0 int i next left cur rec left cx set up tree vars cur rec left cur rec right i offset cur rec right cur rec left min 8 cx tree start cur rec left 1 tree end cur rec right normal column stuff cur rec left cur rec right 1 cur rec right tree start cx i offset draw source parent dc 0 cur rec content cur rec left i next left else cur rec right cx draw source parent dc i column cur rec content cur rec left cx else for int i current 0 i current i count i current int i column p header ctrl order to index i current if is column hidden i column int cx c list ctrl get column width i column if i column 0 int i next left cur rec left cx set up tree vars cur rec left cur rec right i offset cur rec right cur rec left min 8 cx tree start cur rec left 1 tree end cur rec right normal column stuff cur rec left cur rec right 1 cur rec right tree start cx i offset draw source child dc 0 cur rec content cur rec left i next left else cur rec right cx draw source child dc i column cur rec content cur rec left cx draw rectangle around selected item s if content get list parent null lp draw item struct item state ods selected rect outline rec lp draw item struct rc item outline rec top outline rec bottom dc frame rect outline rec c brush get bk color outline rec top outline rec bottom outline rec left outline rec right if not first get item state lp draw item struct itemid 1 lvis selected const c search file prev c search file get item data lp draw item struct itemid 1 if prev get list parent null outline rec top if not last get item state lp draw item struct itemid 1 lvis selected const c search file next c search file get item data lp draw item struct itemid 1 if next get list parent null outline rec bottom if b ctrl focused dc frame rect outline rec c brush m crfocusline else dc frame rect outline rec c brush m crnofocusline draw focus rectangle around non highlightable items when they have the focus else if get focus this lp draw item struct item state ods focus ods focus rect focus rec focus rec top lp draw item struct rc item top focus rec bottom lp draw item struct rc item bottom focus rec left lp draw item struct rc item left 1 focus rec right lp draw item struct rc item right 1 dc frame rect focus rec c brush m crnofocusline draw tree last so it draws over selected and focus looks better if tree start tree end set new bounds rect tree rect tree rect top lp draw item struct rc item top tree rect bottom lp draw item struct rc item bottom tree rect left tree start tree rect right tree end dc set bounds rect tree rect dcb disable gather some information bool has next not last const c search file get item data lp draw item struct itemid 1 get list parent null bool is open root has next content get list parent null bool is child content get list parent null might as well calculate these now int tree center tree start 4 int middle cur rec top cur rec bottom 1 2 set up a new pen for drawing the tree colorref cr line g blowcolordesktop lp draw item struct item state ods selected 0 rgb 128 128 128 m crhighlighttext c pen pn oldpn pn create pen ps solid 1 cr line oldpn dc select object pn if is child draw the line to the status bar dc move to tree end 10 middle dc line to tree start 4 middle draw the line to the child node if has next dc move to tree center middle dc line to tree center cur rec bottom 1 else if is open root content get list parent null content get list child count 1 draw box rect circle rec circle rec top middle 5 circle rec bottom middle 4 circle rec left tree center 4 circle rec right tree center 5 dc frame rect circle rec c brush cr line c pen pen black pen black create pen ps solid 1 g blowcolordesktop lp draw item struct item state ods selected 0 m crwindowtext m crhighlighttext c pen p old pen2 p old pen2 dc select object pen black dc move to tree center 2 middle 1 dc line to tree center 3 middle 1 if content is list expanded dc move to tree center middle 3 dc line to tree center middle 2 dc select object p old pen2 draw the line to the child node if has next dc move to tree center middle 4 dc line to tree center cur rec bottom 1 draw the line back up to parent node if not first is child dc move to tree center middle dc line to tree center cur rec top 1 put the old pen back dc select object oldpn pn delete object put the original objects back if m crwindowtextbk clr none dc set bk mode i old bk mode dc select object p old font dc set text color cr old text color csearchlistctrl drawitem lpdrawitemstruct theapp isrunning lpdrawitemstruct itemdata fromhandle lpdrawitemstruct bctrlfocused getfocus getstyle lvs_showselalways lpdrawitemstruct itemstate ods_selected bctrlfocused setbkcolor m_crhighlight setbkcolor m_crnohighlight setbkcolor getbkcolor csearchfile csearchfile lpdrawitemstruct itemdata cmemdc lpdrawitemstruct rcitem cfont poldfont selectobject getfont crect cur_rec lpdrawitemstruct rcitem croldtextcolor settextcolor g_blowcolordesktop lpdrawitemstruct itemstate ods_selected getsearchitemcolor m_crhighlighttext ioldbkmode m_crwindowtextbk clr_none defwindowproc wm_erasebkgnd ioldbkmode setbkmode ioldbkmode notlast lpdrawitemstruct getitemcount notfirst lpdrawitemstruct tree_start tree_end ioffset gettextextent _t cheaderctrl pheaderctrl getheaderctrl icount pheaderctrl getitemcount cur_rec cur_rec cur_rec ioffset cur_rec ioffset getlistparent theprefs showratingindicator hascomment hasrating m_imagelist userrating cpoint cur_rec cur_rec ild_normal iimage theapp getfiletypesystemimageidx getfilename imagelist_draw theapp getsystemimagelist iimage cur_rec cur_rec ild_normal ild_transparent getlistparent icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent iscolumnhidden icolumn clistctrl getcolumnwidth icolumn icolumn inextleft cur_rec cur_rec cur_rec ioffset cur_rec cur_rec tree_start cur_rec tree_end cur_rec cur_rec cur_rec cur_rec tree_start ioffset drawsourceparent cur_rec cur_rec inextleft cur_rec drawsourceparent icolumn cur_rec cur_rec icurrent icurrent icount icurrent icolumn pheaderctrl ordertoindex icurrent iscolumnhidden icolumn clistctrl getcolumnwidth icolumn icolumn inextleft cur_rec cur_rec cur_rec ioffset cur_rec cur_rec tree_start cur_rec tree_end cur_rec cur_rec cur_rec cur_rec tree_start ioffset drawsourcechild cur_rec cur_rec inextleft cur_rec drawsourcechild icolumn cur_rec cur_rec getlistparent lpdrawitemstruct itemstate ods_selected outline_rec lpdrawitemstruct rcitem outline_rec outline_rec framerect outline_rec cbrush getbkcolor outline_rec outline_rec outline_rec outline_rec notfirst getitemstate lpdrawitemstruct lvis_selected csearchfile csearchfile getitemdata lpdrawitemstruct getlistparent outline_rec notlast getitemstate lpdrawitemstruct lvis_selected csearchfile csearchfile getitemdata lpdrawitemstruct getlistparent outline_rec bctrlfocused framerect outline_rec cbrush m_crfocusline framerect outline_rec cbrush m_crnofocusline getfocus lpdrawitemstruct itemstate ods_focus ods_focus focus_rec focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem focus_rec lpdrawitemstruct rcitem framerect focus_rec cbrush m_crnofocusline tree_start tree_end tree_rect tree_rect lpdrawitemstruct rcitem tree_rect lpdrawitemstruct rcitem tree_rect tree_start tree_rect tree_end setboundsrect tree_rect dcb_disable hasnext notlast csearchfile getitemdata lpdrawitemstruct getlistparent isopenroot hasnext getlistparent ischild getlistparent treecenter tree_start cur_rec cur_rec crline g_blowcolordesktop lpdrawitemstruct itemstate ods_selected m_crhighlighttext cpen createpen ps_solid crline selectobject ischild moveto tree_end lineto tree_start hasnext moveto treecenter lineto treecenter cur_rec isopenroot getlistparent getlistchildcount circle_rec circle_rec circle_rec circle_rec treecenter circle_rec treecenter framerect circle_rec cbrush crline cpen penblack penblack createpen ps_solid g_blowcolordesktop lpdrawitemstruct itemstate ods_selected m_crwindowtext m_crhighlighttext cpen poldpen2 poldpen2 selectobject penblack moveto treecenter lineto treecenter islistexpanded moveto treecenter lineto treecenter selectobject poldpen2 hasnext moveto treecenter lineto treecenter cur_rec notfirst ischild moveto treecenter lineto treecenter cur_rec selectobject deleteobject m_crwindowtextbk clr_none setbkmode ioldbkmode selectobject poldfont settextcolor croldtextcolor void c search list ctrl on sys color change c mule list ctrl on sys color change set highlight colors csearchlistctrl onsyscolorchange cmulelistctrl onsyscolorchange sethighlightcolors void c search list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr barry store sort order in preferences determine ascending based on whether already sorted on this column bool sort ascending get sort item pnm list view i sub item true get sort ascending sort table update sort history pnm list view i sub item sort ascending 0 100 set sort arrow pnm list view i sub item sort ascending sort items sort proc pnm list view i sub item sort ascending 0 100 p result 0 csearchlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview sortascending getsortitem pnmlistview isubitem getsortascending updatesorthistory pnmlistview isubitem sortascending setsortarrow pnmlistview isubitem sortascending sortitems sortproc pnmlistview isubitem sortascending presult void c search list ctrl on context menu c wnd p wnd c point point int i selected 0 int i to download 0 int i to preview 0 position pos get first selected item position while pos null const c search file p file c search file get item data get next selected item pos if p file i selected if p file is preview possible i to preview if the app downloadqueue is file existing p file get file hash false i to download m searchfilemenu enable menu item mp resume i to download 0 mf enabled mf grayed if the prefs is ext controls enabled m searchfilemenu enable menu item mp resumepaused i to download 0 mf enabled mf grayed if the prefs is ext controls enabled m searchfilemenu enable menu item mp detail i selected 1 mf enabled mf grayed m searchfilemenu enable menu item mp cmt i selected 0 mf enabled mf grayed m searchfilemenu enable menu item mp geted2klink i selected 0 mf enabled mf grayed m searchfilemenu enable menu item mp gethtmled2klink i selected 0 mf enabled mf grayed m searchfilemenu enable menu item mp removeselected i selected 0 mf enabled mf grayed m searchfilemenu enable menu item mp remove the app emuledlg searchwnd can delete search m nresultsid mf enabled mf grayed m searchfilemenu enable menu item mp removeall the app emuledlg searchwnd can delete all searches mf enabled mf grayed m searchfilemenu enable menu item mp searchrelated i selected 1 the app emuledlg searchwnd can search related files mf enabled mf grayed uint u inserted menu item 0 if i to preview 1 if m searchfilemenu insert menu mp find mf string mf enabled mp preview get res string ids dl preview t preview u inserted menu item mp preview m searchfilemenu enable menu item mp find get item count 0 mf enabled mf grayed c title menu web menu web menu create menu web menu add menu title null true int i web menu entries the web services get file menu entries web menu uint flag2 i web menu entries 0 i selected 1 mf grayed mf string m searchfilemenu append menu mf popup flag2 uint ptr web menu m hmenu get res string ids webservices t web if i to download 0 m searchfilemenu set default item the prefs add new files paused the prefs is ext controls enabled mp resume mp resumepaused else m searchfilemenu set default item uint 1 get popup menu pos this point m searchfilemenu track popup menu tpm leftalign tpm rightbutton point x point y this if u inserted menu item verify m searchfilemenu remove menu u inserted menu item mf bycommand m searchfilemenu remove menu m searchfilemenu get menu item count 1 mf byposition verify web menu destroy menu csearchlistctrl oncontextmenu cwnd pwnd cpoint iselected itodownload itopreview getfirstselecteditemposition csearchfile pfile csearchfile getitemdata getnextselecteditem pfile iselected pfile ispreviewpossible itopreview theapp isfileexisting pfile getfilehash itodownload m_searchfilemenu enablemenuitem mp_resume itodownload mf_enabled mf_grayed theprefs isextcontrolsenabled m_searchfilemenu enablemenuitem mp_resumepaused itodownload mf_enabled mf_grayed theprefs isextcontrolsenabled m_searchfilemenu enablemenuitem mp_detail iselected mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_cmt iselected mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_geted2klink iselected mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_gethtmled2klink iselected mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_removeselected iselected mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_remove theapp candeletesearch m_nresultsid mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_removeall theapp candeleteallsearches mf_enabled mf_grayed m_searchfilemenu enablemenuitem mp_searchrelated iselected theapp cansearchrelatedfiles mf_enabled mf_grayed uinsertedmenuitem itopreview m_searchfilemenu insertmenu mp_find mf_string mf_enabled mp_preview getresstring ids_dl_preview _t uinsertedmenuitem mp_preview m_searchfilemenu enablemenuitem mp_find getitemcount mf_enabled mf_grayed ctitlemenu webmenu webmenu createmenu webmenu addmenutitle iwebmenuentries thewebservices getfilemenuentries webmenu iwebmenuentries iselected mf_grayed mf_string m_searchfilemenu appendmenu mf_popup uint_ptr webmenu m_hmenu getresstring ids_webservices _t itodownload m_searchfilemenu setdefaultitem theprefs addnewfilespaused theprefs isextcontrolsenabled mp_resume mp_resumepaused m_searchfilemenu setdefaultitem getpopupmenupos m_searchfilemenu trackpopupmenu tpm_leftalign tpm_rightbutton uinsertedmenuitem m_searchfilemenu removemenu uinsertedmenuitem mf_bycommand m_searchfilemenu removemenu m_searchfilemenu getmenuitemcount mf_byposition webmenu destroymenu void c search list ctrl on lvn deleteallitems nmhdr pnmhdr lresult p result to suppress subsequent lvn deleteitem notification messages return true p result true csearchlistctrl onlvndeleteallitems presult lvn_deleteitem presult void c search list ctrl on lvn get info tip nmhdr pnmhdr lresult p result lpnmlvgetinfotip p get info tip reinterpret cast lpnmlvgetinfotip pnmhdr if p get info tip i sub item 0 lvhittestinfo hti 0 get cursor pos hti pt screen to client hti pt bool b over main item sub item hit test hti 1 hti i item p get info tip i item hti i sub item 0 those tooltips are very nice for debugging testing but pretty annoying for general usage enable tooltips only if shift ctrl is currently pressed bool b show info tip get selected count 1 get key state vk shift 0x8000 get key state vk control 0x8000 if b show info tip if b over main item don show the default label tip for the main item if the mouse is not over the main item if p get info tip dw flags lvgit unfolded 0 p get info tip cch text max 0 p get info tip psz text 0 0 p get info tip psz text 0 0 return if get selected count 1 const c search file file c search file get item data p get info tip i item if file p get info tip psz text p get info tip cch text max 0 c string str info const c array c tag c tag tags file get tags for int i 0 i tags get size i const c tag tag tags i if tag c string str tag switch tag get nameid case ft filename str tag format t s s get res string ids sw name tag get str break case ft filesize str tag format t s s get res string ids dl size cast itox bytes tag get int64 false false break case ft filetype str tag format t s s get res string ids type tag get str break case ft fileformat str tag format t s s get res string ids searchextention tag get str break case ft sources str tag format t s u get res string ids searchavail tag get int break case 0x13 remote client s upload file priority tested with hybrid 0 47 if tag get int 0 str tag get res string ids priority t get res string ids prionormal else if tag get int 2 str tag get res string ids priority t get res string ids priohigh else if tag get int 2 str tag get res string ids priority t get res string ids priolow ifdef debug else str tag format t s d unknown get res string ids priority tag get int endif break default bool b unk tag false if tag get name str tag format t s tag get name str tag str tag left 1 make upper str tag mid 1 else extern c string get name const c tag p tag c string str tag name get name tag if str tag name is empty str tag format t s str tag name else ifdef debug str tag format t unknown tag 02x tag get nameid else b unk tag true endif if b unk tag if tag is str str tag tag get str else if tag is int if tag get nameid ft media length c string str temp sec to time length tag get int str temp str tag str temp else tchar sz buff 16 itot tag get int sz buff 10 str tag sz buff else if tag is float tchar sz buff 32 sntprintf sz buff arrsize sz buff t f tag get float str tag sz buff else ifdef debug c string str buff str buff format t unknown value type 02x tag get type str tag str buff else str tag empty endif if str tag is empty if str info is empty str info t n str info str tag if str info get length p get info tip cch text max break ifdef use debug device if file get clients count bool b first true if file get clientid file get client port uint32 u clientip file get clientid uint32 u serverip file get client serverip c string str source if b first b first false str source t sources str source append format t u u u u u server u u u u u uint8 u clientip uint8 u clientip 8 uint8 u clientip 16 uint8 u clientip 24 file get client port uint8 u serverip uint8 u serverip 8 uint8 u serverip 16 uint8 u serverip 24 file get client server port if str info is empty str info t n str info str source const c simple array c search file s client a clients file get clients for int i 0 i a clients get size i uint32 u clientip a clients i m nip uint32 u serverip a clients i m nserverip c string str source if b first b first false str source t sources str source append format t u u u u u server u u u u u uint8 u clientip uint8 u clientip 8 uint8 u clientip 16 uint8 u clientip 24 a clients i m nport uint8 u serverip uint8 u serverip 8 uint8 u serverip 16 uint8 u serverip 24 a clients i m nserverport if str info is empty str info t n str info str source if str info get length p get info tip cch text max break if file get servers get size const c simple array c search file s server a servers file get servers for int i 0 i a servers get size i uint32 u serverip a servers i m nip c string str server if i 0 str server format t servers str server append format t u u u u u avail u uint8 u serverip uint8 u serverip 8 uint8 u serverip 16 uint8 u serverip 24 a servers i m nport a servers i m uavail if str info is empty str info t n str info str server if str info get length p get info tip cch text max break endif tcsncpy p get info tip psz text str info p get info tip cch text max p get info tip psz text p get info tip cch text max 1 t 0 else int i selected 0 ulonglong ul total size 0 position pos get first selected item position while pos const c search file p file c search file get item data get next selected item pos if p file i selected ul total size uint64 p file get file size if i selected 0 c string str info str info format t s u r n s s get res string ids files i selected get res string ids dl size cast itox bytes ul total size tcsncpy p get info tip psz text str info p get info tip cch text max p get info tip psz text p get info tip cch text max 1 t 0 p result 0 csearchlistctrl onlvngetinfotip presult pgetinfotip reinterpret_cast pgetinfotip isubitem getcursorpos screentoclient bovermainitem subitemhittest iitem pgetinfotip iitem isubitem bshowinfotip getselectedcount getkeystate vk_shift getkeystate vk_control bshowinfotip bovermainitem pgetinfotip dwflags lvgit_unfolded pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip psztext getselectedcount csearchfile csearchfile getitemdata pgetinfotip iitem pgetinfotip psztext pgetinfotip cchtextmax cstring strinfo carray ctag ctag gettags getsize ctag cstring strtag getnameid ft_filename strtag _t getresstring ids_sw_name getstr ft_filesize strtag _t getresstring ids_dl_size castitoxbytes getint64 ft_filetype strtag _t getresstring ids_type getstr ft_fileformat strtag _t getresstring ids_searchextention getstr ft_sources strtag _t getresstring ids_searchavail getint getint strtag getresstring ids_priority _t getresstring ids_prionormal getint strtag getresstring ids_priority _t getresstring ids_priohigh getint strtag getresstring ids_priority _t getresstring ids_priolow _debug strtag _t getresstring ids_priority getint bunktag getname strtag _t getname strtag strtag makeupper strtag cstring getname ctag ptag cstring strtagname getname strtagname isempty strtag _t strtagname _debug strtag _t getnameid bunktag bunktag isstr strtag getstr isint getnameid ft_media_length cstring strtemp sectotimelength getint strtemp strtag strtemp szbuff _itot getint szbuff strtag szbuff isfloat szbuff _sntprintf szbuff szbuff _t getfloat strtag szbuff _debug cstring strbuff strbuff _t gettype strtag strbuff strtag strtag isempty strinfo isempty strinfo _t strinfo strtag strinfo getlength pgetinfotip cchtextmax use_debug_device getclientscount bfirst getclientid getclientport uclientip getclientid userverip getclientserverip cstring strsource bfirst bfirst strsource _t strsource appendformat _t uclientip uclientip uclientip uclientip getclientport userverip userverip userverip userverip getclientserverport strinfo isempty strinfo _t strinfo strsource csimplearray csearchfile sclient aclients getclients aclients getsize uclientip aclients m_nip userverip aclients m_nserverip cstring strsource bfirst bfirst strsource _t strsource appendformat _t uclientip uclientip uclientip uclientip aclients m_nport userverip userverip userverip userverip aclients m_nserverport strinfo isempty strinfo _t strinfo strsource strinfo getlength pgetinfotip cchtextmax getservers getsize csimplearray csearchfile sserver aservers getservers aservers getsize userverip aservers m_nip cstring strserver strserver _t strserver appendformat _t userverip userverip userverip userverip aservers m_nport aservers m_uavail strinfo isempty strinfo _t strinfo strserver strinfo getlength pgetinfotip cchtextmax _tcsncpy pgetinfotip psztext strinfo pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip cchtextmax _t iselected ultotalsize getfirstselecteditemposition csearchfile pfile csearchfile getitemdata getnextselecteditem pfile iselected ultotalsize pfile getfilesize iselected cstring strinfo strinfo _t getresstring ids_files iselected getresstring ids_dl_size castitoxbytes ultotalsize _tcsncpy pgetinfotip psztext strinfo pgetinfotip cchtextmax pgetinfotip psztext pgetinfotip cchtextmax _t presult void c search list ctrl on click nmhdr pnmhdr lresult p result point point get cursor pos point c point p point screen to client p lpnmitemactivate pnmia reinterpret cast lpnmitemactivate pnmhdr if p x 10 expand collapse item pnmia i item expand collapse csearchlistctrl onclick presult getcursorpos cpoint screentoclient reinterpret_cast expandcollapseitem iitem expand_collapse void c search list ctrl on dbl click nmhdr pnmhdr lresult p result point point get cursor pos point c point p point screen to client p if p x 10 if get key state vk menu 0x8000 int i sel get next item 1 lvis selected lvis focused if i sel 1 const c search file file c search file get item data i sel if file c typed ptr list c ptr list c search file a files a files add tail file c search result file detail sheet sheet a files 0 this sheet do modal else the app emuledlg searchwnd download selected csearchlistctrl ondblclick presult getcursorpos cpoint screentoclient getkeystate vk_menu isel getnextitem lvis_selected lvis_focused isel csearchfile csearchfile getitemdata isel ctypedptrlist cptrlist csearchfile afiles afiles addtail csearchresultfiledetailsheet afiles domodal theapp downloadselected void c search list ctrl on key down uint n char uint n rep cnt uint n flags if n char c get key state vk control 0x8000 ctrl c copy listview items to clipboard send message wm command mp geted2klink return c mule list ctrl on key down n char n rep cnt n flags csearchlistctrl onkeydown nchar nrepcnt nflags nchar getkeystate vk_control sendmessage wm_command mp_geted2klink cmulelistctrl onkeydown nchar nrepcnt nflags void c search list ctrl on lvn keydown nmhdr pnmhdr lresult p result lpnmlvkeydown plv key down reinterpret cast lpnmlvkeydown pnmhdr bool b alt key get async key state vk menu 0 int i action expand collapse if plv key down wv key vk add b alt key plv key down wv key vk right i action expand only else if plv key down wv key vk subtract b alt key plv key down wv key vk left i action collapse only if i action expand collapse expand collapse item get next item 1 lvis selected lvis focused i action p result 0 csearchlistctrl onlvnkeydown presult plvkeydown reinterpret_cast baltkey getasynckeystate vk_menu iaction expand_collapse plvkeydown wvkey vk_add baltkey plvkeydown wvkey vk_right iaction expand_only plvkeydown wvkey vk_subtract baltkey plvkeydown wvkey vk_left iaction collapse_only iaction expand_collapse expandcollapseitem getnextitem lvis_selected lvis_focused iaction presult c editx c editx m dwlastdblclick 0 m dwthirdclicktime 0 ceditx ceditx m_dwlastdblclick m_dwthirdclicktime void c editx update metrics m dwthirdclicktime get double click time 2 m dwthirdclicktime m dwthirdclicktime 10 100 ceditx updatemetrics m_dwthirdclicktime getdoubleclicktime m_dwthirdclicktime m_dwthirdclicktime void c editx pre subclass window update metrics c edit pre subclass window ceditx presubclasswindow updatemetrics cedit presubclasswindow void c editx onl button down uint n flags c point point check for triple click if we already had a double click check if the current click is inside the threshold if get current message time m dwlastdblclick m dwthirdclicktime set sel 0 1 don t reset m dwlastdblclick if there is another click within the threshold time the selection would be vanish again else c edit onl button down n flags point m dwlastdblclick 0 ceditx onlbuttondown nflags cpoint getcurrentmessage m_dwlastdblclick m_dwthirdclicktime setsel m_dwlastdblclick cedit onlbuttondown nflags m_dwlastdblclick void c editx onl button dbl clk uint n flags c point point c edit onl button dbl clk n flags point m dwlastdblclick get current message time ceditx onlbuttondblclk nflags cpoint cedit onlbuttondblclk nflags m_dwlastdblclick getcurrentmessage int c editx on create lpcreatestruct lp create struct if c edit on create lp create struct 1 return 1 update metrics return 0 ceditx oncreate lpcreatestruct cedit oncreate lpcreatestruct updatemetrics void c editx on setting change uint u flags lpctstr lpsz section update metrics c edit on setting change u flags lpsz section ceditx onsettingchange uflags lpszsection updatemetrics cedit onsettingchange uflags lpszsection c editable list ctrl c editable list ctrl m pctrledit null m pctrlcombobox null m irow 0 m icol 1 m ieditrow 1 m ieditcol 1 ceditablelistctrl ceditablelistctrl m_pctrledit m_pctrlcombobox m_irow m_icol m_ieditrow m_ieditcol void c editable list ctrl commit edit ctrl if m ieditcol 1 m ieditrow 1 if m pctrledit m pctrledit is window visible c string str item m pctrledit get window text str item str item trim left str item trim right set item text m ieditrow m ieditcol str item m ieditrow 1 m ieditcol 1 else if m pctrlcombobox m pctrlcombobox is window visible c string str item m pctrlcombobox getlb text m pctrlcombobox get cur sel str item str item trim left str item trim right set item text m ieditrow m ieditcol str item m ieditrow 1 m ieditcol 1 ceditablelistctrl commiteditctrl m_ieditcol m_ieditrow m_pctrledit m_pctrledit iswindowvisible cstring stritem m_pctrledit getwindowtext stritem stritem trimleft stritem trimright setitemtext m_ieditrow m_ieditcol stritem m_ieditrow m_ieditcol m_pctrlcombobox m_pctrlcombobox iswindowvisible cstring stritem m_pctrlcombobox getlbtext m_pctrlcombobox getcursel stritem stritem trimleft stritem trimright setitemtext m_ieditrow m_ieditcol stritem m_ieditrow m_ieditcol bool c editable list ctrl pre translate message msg p msg if p msg message wm keydown p msg w param vk tab commit edit ctrl m ieditrow 1 m ieditcol 1 if get key state vk shift 0x8000 m icol if m icol 1 m icol max cols 1 m irow while m irow 0 get item data m irow 1 m irow if m irow 0 m icol 1 m irow 0 cycle to prev sibling control c wnd p wnd get window gw hwndprev assert p wnd if p wnd p wnd set focus return c list ctrl pre translate message p msg else m icol if m icol max cols m icol 1 m irow while m irow get item count get item data m irow 1 m irow reset bottom position if m irow get item count 1 m irow get item count 1 cycle to next sibling control c wnd p wnd get next window assert p wnd if p wnd p wnd set focus return c list ctrl pre translate message p msg verify scroll pos reset top position reset bottom position switch m icol case 0 break case 1 show edit ctrl break return true return c list ctrl pre translate message p msg ceditablelistctrl pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_tab commiteditctrl m_ieditrow m_ieditcol getkeystate vk_shift m_icol m_icol m_icol max_cols m_irow m_irow getitemdata m_irow m_irow m_irow m_icol m_irow cwnd pwnd getwindow gw_hwndprev pwnd pwnd pwnd setfocus clistctrl pretranslatemessage pmsg m_icol m_icol max_cols m_icol m_irow m_irow getitemcount getitemdata m_irow m_irow resetbottomposition m_irow getitemcount m_irow getitemcount cwnd pwnd getnextwindow pwnd pwnd pwnd setfocus clistctrl pretranslatemessage pmsg verifyscrollpos resettopposition resetbottomposition m_icol showeditctrl clistctrl pretranslatemessage pmsg void c editable list ctrl show edit ctrl if m irow get item count return if get item data m irow 1 if m pctrledit m pctrledit show window sw hide return c rect rect get sub item rect m irow m icol lvir label rect if m pctrledit null m pctrledit new c edit m pctrledit create ws child ws visible ws clipsiblings ws tabstop ws border es left es autohscroll rect this lv edit ctrl id m pctrledit set font get font m pctrledit show window sw show else m pctrledit set window pos null rect left rect top rect width rect height swp showwindow tchar sz item 256 0 lvitem item item mask lvif text item i item m irow item i sub item m icol item cch text max arrsize sz item item psz text sz item get item item m pctrledit set window text sz item m pctrledit set sel 0 1 if m pctrlcombobox m pctrlcombobox show window sw hide m pctrledit set focus m ieditrow m irow m ieditcol m icol ceditablelistctrl showeditctrl m_irow getitemcount getitemdata m_irow m_pctrledit m_pctrledit showwindow sw_hide crect getsubitemrect m_irow m_icol lvir_label m_pctrledit m_pctrledit cedit m_pctrledit ws_child ws_visible ws_clipsiblings ws_tabstop ws_border es_left es_autohscroll lv_edit_ctrl_id m_pctrledit setfont getfont m_pctrledit showwindow sw_show m_pctrledit setwindowpos swp_showwindow szitem lvif_text iitem m_irow isubitem m_icol cchtextmax szitem psztext szitem getitem m_pctrledit setwindowtext szitem m_pctrledit setsel m_pctrlcombobox m_pctrlcombobox showwindow sw_hide m_pctrledit setfocus m_ieditrow m_irow m_ieditcol m_icol void c editable list ctrl show combo box ctrl c rect rect get sub item rect m irow m icol lvir label rect rect bottom 100 if m pctrlcombobox m pctrlcombobox new c combo box m pctrlcombobox create ws child ws visible ws tabstop ws clipsiblings ws border cbs dropdown ws vscroll ws hscroll rect this 1002 m pctrlcombobox show window sw show m pctrlcombobox set horizontal extent 800 m pctrlcombobox send message cb setdroppedwidth 600 0 else m pctrlcombobox set window pos null rect left rect top rect width rect height swp showwindow m pctrlcombobox set cur sel 0 if m pctrledit m pctrledit show window sw hide m pctrlcombobox set focus ceditablelistctrl showcomboboxctrl crect getsubitemrect m_irow m_icol lvir_label m_pctrlcombobox m_pctrlcombobox ccombobox m_pctrlcombobox ws_child ws_visible ws_tabstop ws_clipsiblings ws_border cbs_dropdown ws_vscroll ws_hscroll m_pctrlcombobox showwindow sw_show m_pctrlcombobox sethorizontalextent m_pctrlcombobox sendmessage cb_setdroppedwidth m_pctrlcombobox setwindowpos swp_showwindow m_pctrlcombobox setcursel m_pctrledit m_pctrledit showwindow sw_hide m_pctrlcombobox setfocus void c editable list ctrl reset top position c wnd p wnd null if m pctrlcombobox p wnd m pctrlcombobox else if m pctrledit p wnd m pctrledit if p wnd c rect rc this get window rect rc this c rect rect if get sub item rect m irow m icol lvir label rect return client to screen rect c point pt rect left rect top if rc this pt in rect pt send message wm vscroll sb lineup 0 ceditablelistctrl resettopposition cwnd pwnd m_pctrlcombobox pwnd m_pctrlcombobox m_pctrledit pwnd m_pctrledit pwnd crect rcthis getwindowrect rcthis crect getsubitemrect m_irow m_icol lvir_label clienttoscreen cpoint rcthis ptinrect sendmessage wm_vscroll sb_lineup void c editable list ctrl reset bottom position c wnd p wnd null if m pctrlcombobox p wnd m pctrlcombobox else if m pctrledit p wnd m pctrledit if p wnd c rect rc this get window rect rc this c rect rect if get sub item rect m irow m icol lvir label rect return client to screen rect c point pt rect right rect bottom if rc this pt in rect pt send message wm vscroll sb linedown 0 ceditablelistctrl resetbottomposition cwnd pwnd m_pctrlcombobox pwnd m_pctrlcombobox m_pctrledit pwnd m_pctrledit pwnd crect rcthis getwindowrect rcthis crect getsubitemrect m_irow m_icol lvir_label clienttoscreen cpoint rcthis ptinrect sendmessage wm_vscroll sb_linedown void c editable list ctrl verify scroll pos int n top row val get top index int n bottom val n top row val get count per page if m irow n top row val 1 m irow n bottom val 1 else if m irow n top row val for int j 0 j m irow n top row val j send message wm vscroll sb lineup 0 if m irow n bottom val for int j 0 j m irow n top row val j send message wm vscroll sb linedown 0 ceditablelistctrl verifyscrollpos ntoprowval gettopindex nbottomval ntoprowval getcountperpage m_irow ntoprowval m_irow nbottomval m_irow ntoprowval m_irow ntoprowval sendmessage wm_vscroll sb_lineup m_irow nbottomval m_irow ntoprowval sendmessage wm_vscroll sb_linedown bool c editable list ctrl on notify wparam w param lparam l param lresult p result switch nmhdr l param code case hdn begintrackw case hdn begintracka if m pctrledit m pctrledit is window visible m pctrledit show window sw hide if m pctrlcombobox m pctrlcombobox is window visible m pctrlcombobox show window sw hide p result 0 break return c list ctrl on notify w param l param p result ceditablelistctrl onnotify wparam lparam presult lparam hdn_begintrackw hdn_begintracka m_pctrledit m_pctrledit iswindowvisible m_pctrledit showwindow sw_hide m_pctrlcombobox m_pctrlcombobox iswindowvisible m_pctrlcombobox showwindow sw_hide presult clistctrl onnotify wparam lparam presult void c editable list ctrl onv scroll uint nsb code uint n pos c scroll bar p scroll bar if nsb code sb linedown nsb code sb lineup if nsb code sb endscroll if m pctrledit show edit ctrl else if m pctrledit commit edit ctrl m ieditrow 1 m ieditcol 1 m pctrledit show window sw hide if m pctrlcombobox m pctrlcombobox show window sw hide c list ctrl onv scroll nsb code n pos p scroll bar ceditablelistctrl onvscroll nsbcode npos cscrollbar pscrollbar nsbcode sb_linedown nsbcode sb_lineup nsbcode sb_endscroll m_pctrledit showeditctrl m_pctrledit commiteditctrl m_ieditrow m_ieditcol m_pctrledit showwindow sw_hide m_pctrlcombobox m_pctrlcombobox showwindow sw_hide clistctrl onvscroll nsbcode npos pscrollbar void c editable list ctrl onh scroll uint nsb code uint n pos c scroll bar p scroll bar if m pctrledit m pctrledit is window visible m pctrledit show window sw hide if m pctrlcombobox m pctrlcombobox is window visible m pctrlcombobox show window sw hide c list ctrl onh scroll nsb code n pos p scroll bar ceditablelistctrl onhscroll nsbcode npos cscrollbar pscrollbar m_pctrledit m_pctrledit iswindowvisible m_pctrledit showwindow sw_hide m_pctrlcombobox m_pctrlcombobox iswindowvisible m_pctrlcombobox showwindow sw_hide clistctrl onhscroll nsbcode npos pscrollbar void c editable list ctrl on columnclick nmhdr pnmhdr lresult p result if m pctrledit m pctrledit is window visible m pctrledit show window sw hide if m pctrlcombobox m pctrlcombobox is window visible m pctrlcombobox show window sw hide p result 0 ceditablelistctrl oncolumnclick presult m_pctrledit m_pctrledit iswindowvisible m_pctrledit showwindow sw_hide m_pctrlcombobox m_pctrlcombobox iswindowvisible m_pctrlcombobox showwindow sw_hide presult void c editable list ctrl on destroy delete m pctrledit delete m pctrlcombobox c list ctrl on destroy ceditablelistctrl ondestroy m_pctrledit m_pctrlcombobox clistctrl ondestroy void c editable list ctrl on en kill focus commit edit ctrl m ieditrow 1 m ieditcol 1 if m pctrledit m pctrledit show window sw hide ceditablelistctrl onenkillfocus commiteditctrl m_ieditrow m_ieditcol m_pctrledit m_pctrledit showwindow sw_hide void c editable list ctrl onl button down uint n flags c point point c list ctrl onl button down n flags point lvhittestinfo hti 0 hti pt point if sub item hit test hti 1 return int i item hti i item int i sub item hti i sub item if i item 1 i sub item 1 return c rect rect get sub item rect i item i sub item lvir label rect client to screen rect c point pt rect right rect bottom c rect rc get window rect rc if rc pt in rect pt send message wm vscroll sb linedown 0 pt x rect left pt y rect top if rc pt in rect pt send message wm vscroll sb lineup 0 m irow i item m icol i sub item switch m icol case 0 m icol 1 show edit ctrl break case 1 show edit ctrl break ceditablelistctrl onlbuttondown nflags cpoint clistctrl onlbuttondown nflags subitemhittest iitem iitem isubitem isubitem iitem isubitem crect getsubitemrect iitem isubitem lvir_label clienttoscreen cpoint crect getwindowrect ptinrect sendmessage wm_vscroll sb_linedown ptinrect sendmessage wm_vscroll sb_lineup m_irow iitem m_icol isubitem m_icol m_icol showeditctrl showeditctrl void c editable list ctrl on set focus c wnd p old wnd c list ctrl on set focus p old wnd switch m icol case 0 break case 1 if p old wnd m pctrledit show edit ctrl break ceditablelistctrl onsetfocus cwnd poldwnd clistctrl onsetfocus poldwnd m_icol poldwnd m_pctrledit showeditctrl void c editable list ctrl onnm customdraw nmhdr pnmhdr lresult p result lpnmlvcustomdraw pnmcd reinterpret cast lpnmlvcustomdraw pnmhdr if pnmcd nmcd dw draw stage cdds prepaint p result cdrf notifyitemdraw return if pnmcd nmcd dw draw stage cdds itemprepaint dword dw item data pnmcd nmcd l iteml param if dw item data 1 pnmcd clr text rgb 128 128 128 pnmcd clr text bk 0xff000000 else pnmcd clr text 0xff000000 pnmcd clr text bk 0xff000000 p result cdrf dodefault ceditablelistctrl onnmcustomdraw presult reinterpret_cast dwdrawstage cdds_prepaint presult cdrf_notifyitemdraw dwdrawstage cdds_itemprepaint dwitemdata litemlparam dwitemdata clrtext clrtextbk clrtext clrtextbk presult cdrf_dodefault void c editable list ctrl on lvn end scroll nmhdr pnmhdr lresult p result lpnmlvscroll p state changed reinterpret cast lpnmlvscroll pnmhdr if m pctrledit show edit ctrl p result 0 ceditablelistctrl onlvnendscroll presult pstatechanged reinterpret_cast m_pctrledit showeditctrl presult void c editable list ctrl on lvn begin scroll nmhdr pnmhdr lresult p result lpnmlvscroll p state changed reinterpret cast lpnmlvscroll pnmhdr if m pctrledit commit edit ctrl m ieditrow 1 m ieditcol 1 m pctrledit show window sw hide p result 0 ceditablelistctrl onlvnbeginscroll presult pstatechanged reinterpret_cast m_pctrledit commiteditctrl m_ieditrow m_ieditcol m_pctrledit showwindow sw_hide presult c list view walker property sheet p list ctrl m upshinvokepage u psh invoke page position pos a files get head position while pos m aitems add a files get next pos m psh dw flags psh hashelp m wndmediainfo m psp dw flags psp hashelp m wndmediainfo m psp dw flags psp useiconid m wndmediainfo m psp psz icon t mediainfo m wndmediainfo set files m aitems add page m wndmediainfo m wndmetadata m psp dw flags psp hashelp m wndmetadata m psp dw flags psp useiconid m wndmetadata m psp psz icon t metadata if m aitems get size 1 the prefs is ext controls enabled m wndmetadata set files m aitems add page m wndmetadata m wndfilelink m psp dw flags psp hashelp m wndfilelink m psp dw flags psp useiconid m wndfilelink m psp psz icon t ed2klink m wndfilelink set files m aitems add page m wndfilelink m wndfilecomments m psp dw flags psp hashelp m wndfilecomments m psp dw flags psp useiconid m wndfilecomments m psp psz icon t file comments m wndfilecomments set files m aitems add page m wndfilecomments lpctstr p psh start page m ppshstartpage if m upshinvokepage 0 p psh start page makeintresource m upshinvokepage for int i 0 i m pages get size i c property page p page get page i if p page m psp psz template p psh start page m psh n start page i break clistviewwalkerpropertysheet plistctrl m_upshinvokepage upshinvokepage afiles getheadposition m_aitems afiles getnext m_psh dwflags psh_hashelp m_wndmediainfo m_psp dwflags psp_hashelp m_wndmediainfo m_psp dwflags psp_useiconid m_wndmediainfo m_psp pszicon _t m_wndmediainfo setfiles m_aitems addpage m_wndmediainfo m_wndmetadata m_psp dwflags psp_hashelp m_wndmetadata m_psp dwflags psp_useiconid m_wndmetadata m_psp pszicon _t m_aitems getsize theprefs isextcontrolsenabled m_wndmetadata setfiles m_aitems addpage m_wndmetadata m_wndfilelink m_psp dwflags psp_hashelp m_wndfilelink m_psp dwflags psp_useiconid m_wndfilelink m_psp pszicon _t m_wndfilelink setfiles m_aitems addpage m_wndfilelink m_wndfilecomments m_psp dwflags psp_hashelp m_wndfilecomments m_psp dwflags psp_useiconid m_wndfilecomments m_psp pszicon _t filecomments m_wndfilecomments setfiles m_aitems addpage m_wndfilecomments ppshstartpage m_ppshstartpage m_upshinvokepage ppshstartpage m_upshinvokepage m_pages getsize cpropertypage ppage getpage ppage m_psp psztemplate ppshstartpage m_psh nstartpage c shared file details sheet c shared file details sheet csharedfiledetailssheet csharedfiledetailssheet void c shared file details sheet update title if m aitems get size 1 set window text get res string ids details t static downcast c known file m aitems 0 get file name else set window text get res string ids details csharedfiledetailssheet updatetitle m_aitems getsize setwindowtext getresstring ids_details _t static_downcast cknownfile m_aitems getfilename setwindowtext getresstring ids_details bool c shared file details sheet on command wparam w param lparam l param if w param id apply now c shared files ctrl p shared files ctrl dynamic downcast c shared files ctrl m plistctrl get list ctrl if p shared files ctrl for int i 0 i m aitems get size i so and why does this not work while the sheet is open p shared files ctrl update file dynamic downcast c known file m aitems i return c list view walker property sheet on command w param l param csharedfiledetailssheet oncommand wparam lparam wparam id_apply_now csharedfilesctrl psharedfilesctrl dynamic_downcast csharedfilesctrl m_plistctrl getlistctrl psharedfilesctrl m_aitems getsize psharedfilesctrl updatefile dynamic_downcast cknownfile m_aitems clistviewwalkerpropertysheet oncommand wparam lparam bool c shared file details sheet on init dialog enable stacked tabs false bool b result c list view walker property sheet on init dialog high color tab update image list this init window styles this enable save restore t shared file details sheet call this after on init dialog update title return b result csharedfiledetailssheet oninitdialog enablestackedtabs bresult clistviewwalkerpropertysheet oninitdialog highcolortab updateimagelist initwindowstyles enablesaverestore _t sharedfiledetailssheet oninitdialog updatetitle bresult void c shared file details sheet on destroy if m upshinvokepage 0 m ppshstartpage get page get active index m psp psz template c list view walker property sheet on destroy csharedfiledetailssheet ondestroy m_upshinvokepage m_ppshstartpage getpage getactiveindex m_psp psztemplate clistviewwalkerpropertysheet ondestroy lresult c shared file details sheet on data changed wparam lparam update title return 1 csharedfiledetailssheet ondatachanged updatetitle c publish keyword list c publish keyword list reset next keyword set next publish time 0 cpublishkeywordlist cpublishkeywordlist resetnextkeyword setnextpublishtime c publish keyword list c publish keyword list remove all keywords cpublishkeywordlist cpublishkeywordlist removeallkeywords void c publish keyword list add keywords c known file p file const kademlia word list wordlist p file get kad keywords assert wordlist size 0 kademlia word list const iterator it for it wordlist begin it wordlist end it const c stringw str keyword it c publish keyword p pub kw find keyword str keyword if p pub kw null p pub kw new c publish keyword str keyword m lstkeywords add tail p pub kw set next publish time 0 if p pub kw add ref p file p pub kw get next publish time min2s 30 user may be adding and removing files so if this is a keyword that has already been published we reduce the time but still give the user enough time to finish what they are doing if this is a hot node the load list will prevent from republishing p pub kw set next publish time min2s 30 cpublishkeywordlist addkeywords cknownfile pfile wordlist pfile getkadkeywords wordlist const_iterator cstringw strkeyword cpublishkeyword ppubkw findkeyword strkeyword ppubkw ppubkw cpublishkeyword strkeyword m_lstkeywords addtail ppubkw setnextpublishtime ppubkw addref pfile ppubkw getnextpublishtime ppubkw setnextpublishtime void c publish keyword list remove keywords c known file p file const kademlia word list wordlist p file get kad keywords assert wordlist size 0 kademlia word list const iterator it for it wordlist begin it wordlist end it const c stringw str keyword it position pos c publish keyword p pub kw find keyword str keyword pos if p pub kw null if p pub kw remove ref p file 0 if pos m posnextkeyword void m lstkeywords get next m posnextkeyword m lstkeywords remove at pos delete p pub kw set next publish time 0 cpublishkeywordlist removekeywords cknownfile pfile wordlist pfile getkadkeywords wordlist const_iterator cstringw strkeyword cpublishkeyword ppubkw findkeyword strkeyword ppubkw ppubkw removeref pfile m_posnextkeyword m_lstkeywords getnext m_posnextkeyword m_lstkeywords removeat ppubkw setnextpublishtime void c publish keyword list remove all keywords position pos m lstkeywords get head position while pos delete m lstkeywords get next pos m lstkeywords remove all reset next keyword set next publish time 0 cpublishkeywordlist removeallkeywords m_lstkeywords getheadposition m_lstkeywords getnext m_lstkeywords removeall resetnextkeyword setnextpublishtime void c publish keyword list remove all keyword references position pos m lstkeywords get head position while pos m lstkeywords get next pos remove all references cpublishkeywordlist removeallkeywordreferences m_lstkeywords getheadposition m_lstkeywords getnext removeallreferences void c publish keyword list purge unreferenced keywords position pos m lstkeywords get head position while pos position pos last pos c publish keyword p pub kw m lstkeywords get next pos if p pub kw get ref count 0 if pos last m posnextkeyword void m lstkeywords get next m posnextkeyword m lstkeywords remove at pos last delete p pub kw set next publish time 0 cpublishkeywordlist purgeunreferencedkeywords m_lstkeywords getheadposition poslast cpublishkeyword ppubkw m_lstkeywords getnext ppubkw getrefcount poslast m_posnextkeyword m_lstkeywords getnext m_posnextkeyword m_lstkeywords removeat poslast ppubkw setnextpublishtime c publish keyword c publish keyword list get next keyword if m posnextkeyword null m posnextkeyword m lstkeywords get head position if m posnextkeyword null return null return m lstkeywords get next m posnextkeyword cpublishkeyword cpublishkeywordlist getnextkeyword m_posnextkeyword m_posnextkeyword m_lstkeywords getheadposition m_posnextkeyword m_lstkeywords getnext m_posnextkeyword void c publish keyword list reset next keyword m posnextkeyword m lstkeywords get head position cpublishkeywordlist resetnextkeyword m_posnextkeyword m_lstkeywords getheadposition bool add ref c known file p file if m afiles find p file 1 assert 0 return false return m afiles add p file addref cknownfile pfile m_afiles pfile m_afiles pfile int remove ref c known file p file m afiles remove p file return m afiles get size removeref cknownfile pfile m_afiles pfile m_afiles getsize void remove all references m afiles remove all removeallreferences m_afiles removeall void rotate references int i rotate size if m afiles get size i rotate size c known file pp rotated c known file malloc m afiles m nallocsize sizeof m afiles get data if pp rotated null memcpy pp rotated m afiles get data i rotate size m afiles get size i rotate size sizeof m afiles get data memcpy pp rotated m afiles get size i rotate size m afiles get data i rotate size sizeof m afiles get data free m afiles get data m afiles m at pp rotated rotatereferences irotatesize m_afiles getsize irotatesize cknownfile pprotated cknownfile m_afiles m_nallocsize m_afiles getdata pprotated pprotated m_afiles getdata irotatesize m_afiles getsize irotatesize m_afiles getdata pprotated m_afiles getsize irotatesize m_afiles getdata irotatesize m_afiles getdata m_afiles getdata m_afiles m_at pprotated csha csha reset verify reset csha csha reset verify bool csha verify implementation if sha asm m ncount0 offsetof csha m ncount 0 sha asm m ncount1 offsetof csha m ncount 1 assert 0 return false if sha asm m nhash0 offsetof csha m nhash 0 sha asm m nhash1 offsetof csha m nhash 1 sha asm m nhash2 offsetof csha m nhash 2 sha asm m nhash3 offsetof csha m nhash 3 sha asm m nhash4 offsetof csha m nhash 4 assert 0 return false if sha asm m nbuffer offsetof csha m nbuffer assert 0 return false return true verifyimplementation sha_asm_m_ncount0 m_ncount sha_asm_m_ncount1 m_ncount sha_asm_m_nhash0 m_nhash sha_asm_m_nhash1 m_nhash sha_asm_m_nhash2 m_nhash sha_asm_m_nhash3 m_nhash sha_asm_m_nhash4 m_nhash sha_asm_m_nbuffer m_nbuffer void csha reset m ncount 0 m ncount 1 0 m nhash 0 0x67452301 m nhash 1 0xefcdab89 m nhash 2 0x98badcfe m nhash 3 0x10325476 m nhash 4 0xc3d2e1f0 m_ncount m_ncount m_nhash m_nhash m_nhash m_nhash m_nhash void csha add lpcvoid p data dword n length sha add p5 this p data n length pdata nlength sha_add_p5 pdata nlength void csha finish caich hash r hash finish get hash r hash caichhash rhash gethash rhash void csha get hash caich hash r hash assert r hash get hash size sizeof sha1 get hash sha1 r hash get raw hash gethash caichhash rhash rhash gethashsize gethash rhash getrawhash void csha finish unsigned int bits 2 index 0 save number of bits asm mov ecx this mov eax ecx asm m ncount mov edx ecx asm m ncount 4 shld edx eax 3 shl eax 3 bswap edx bswap eax mov bits edx mov bits 4 eax pad out to 56 mod 64 index unsigned int m ncount 0 0x3f sha add p5 this sha padding index 56 56 index 120 index append length before padding sha add p5 this bits 8 _asm asm_m_ncount asm_m_ncount m_ncount sha_add_p5 sha_padding sha_add_p5 void csha get hash sha1 p hash extract the hash value as bytes in case the hash buffer is misaligned for 32 bit words for int i 0 i sha1 digest size i p hash b i unsigned char m nhash i 2 8 i 3 gethash phash sha1_digest_size phash m_nhash c string csha get hash string bool burn sha1 p hash get hash p hash return hash to string p hash burn cstring gethashstring phash gethash phash hashtostring phash c string csha hash to string const sha1 p hash in bool burn static lpctstr psz base64 t abcdefghijklmnopqrstuvwxyz234567 c string str hash lptstr psz hash str hash get buffer burn 9 32 32 if burn psz hash u psz hash r psz hash n psz hash psz hash s psz hash h psz hash a psz hash 1 psz hash lpbyte p hash lpbyte p hash in int n shift 7 for int n char 32 n char n char byte n bits 0 for int n bit 0 n bit 5 n bit if n bit n bits 1 n bits p hash n shift 1 if n shift n shift 7 p hash psz hash psz base64 n bits str hash release buffer burn 9 32 32 return str hash cstring hashtostring phashin pszbase64 _t cstring strhash pszhash strhash getbuffer pszhash pszhash pszhash pszhash pszhash pszhash pszhash pszhash pszhash phash phashin nshift nchar nchar nchar nbits nbit nbit nbit nbit nbits nbits phash nshift nshift nshift phash pszhash pszbase64 nbits strhash releasebuffer strhash c string csha hash to hex string const sha1 p hash in bool burn static lpctstr psz hex t 0123456789abcdef lpbyte p hash lpbyte p hash in c string str hash lptstr psz hash str hash get buffer 40 for int n byte 0 n byte 20 n byte p hash psz hash psz hex p hash 4 psz hash psz hex p hash 15 str hash release buffer 40 if burn str hash t urn sha1 str hash return str hash cstring hashtohexstring phashin pszhex _t phash phashin cstring strhash pszhash strhash getbuffer nbyte nbyte nbyte phash pszhash pszhex phash pszhash pszhex phash strhash releasebuffer strhash _t strhash strhash bool csha hash from string lpctstr psz hash sha1 p hash in if psz hash tcslen psz hash 32 return false invalid hash if tcsnicmp psz hash t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 32 0 return false bad hash sha1 hash lpbyte p hash lpbyte hash dword n bits 0 int n count 0 for int n chars 32 n chars psz hash if psz hash a psz hash z n bits psz hash a else if psz hash a psz hash z n bits psz hash a else if psz hash 2 psz hash 7 n bits psz hash 2 26 else return false n count 5 if n count 8 p hash byte n bits n count 8 n count 8 n bits 5 p hash in hash return true hashfromstring pszhash phashin pszhash _tcslen pszhash _tcsnicmp pszhash _t phash nbits ncount nchars nchars pszhash pszhash pszhash nbits pszhash pszhash pszhash nbits pszhash pszhash pszhash nbits pszhash ncount ncount phash nbits ncount ncount nbits phashin bool csha hash fromurn lpctstr psz hash sha1 p hash in if psz hash null return false int n len tcslen psz hash if n len 41 tcsnicmp psz hash t urn sha1 9 0 return hash from string psz hash 9 p hash in else if n len 37 tcsnicmp psz hash t sha1 5 0 return hash from string psz hash 5 p hash in else if n len 85 tcsnicmp psz hash t urn bitprint 13 0 13 32 1 39 return hash from string psz hash 13 p hash in else if n len 81 tcsnicmp psz hash t bitprint 9 0 return hash from string psz hash 9 p hash in return false hashfromurn pszhash phashin pszhash nlen _tcslen pszhash nlen _tcsnicmp pszhash _t hashfromstring pszhash phashin nlen _tcsnicmp pszhash _t hashfromstring pszhash phashin nlen _tcsnicmp pszhash _t hashfromstring pszhash phashin nlen _tcsnicmp pszhash _t hashfromstring pszhash phashin bool csha is null sha1 p hash sha1 blank zero memory blank sizeof sha1 if p hash blank return true return false isnull phash zeromemory phash cht rich edit ctrl cht rich edit ctrl m brichedit true m bautoscroll true m bnopaint false m benerrspace false m brestoreformat false memset m cfdefault 0 sizeof m cfdefault m bforcearrowcursor false m harrowcursor load cursor null idc arrow chtricheditctrl chtricheditctrl m_brichedit m_bautoscroll m_bnopaint m_benerrspace m_brestoreformat m_cfdefault m_cfdefault m_bforcearrowcursor m_harrowcursor loadcursor idc_arrow cht rich edit ctrl cht rich edit ctrl chtricheditctrl chtricheditctrl void cht rich edit ctrl init lpctstr psz title lpctstr psz skin key set profile skin key psz skin key set title psz title verify send message em setundolimit 0 0 0 int i max log buff the prefs get max log buff if afx data b win95 limit text i max log buff 0xffff 0xffff i max log buff else limit text i max log buff i max log buff 128 1024 m ilimittext get limit text verify get selection char format m cfdefault prevent the re control to change the font height within single log lines may happen with some unicode chars dword dw lang opts send message em getlangoptions send message em setlangoptions 0 dw lang opts imf autofont imf autofontsizeadjust send message em seteditstyle ses emulatesysedit ses emulatesysedit chtricheditctrl psztitle pszskinkey setprofileskinkey pszskinkey settitle psztitle sendmessage em_setundolimit imaxlogbuff theprefs getmaxlogbuff afxdata bwin95 limittext imaxlogbuff imaxlogbuff limittext imaxlogbuff imaxlogbuff m_ilimittext getlimittext getselectioncharformat m_cfdefault dwlangopts sendmessage em_getlangoptions sendmessage em_setlangoptions dwlangopts imf_autofont imf_autofontsizeadjust sendmessage em_seteditstyle ses_emulatesysedit ses_emulatesysedit void cht rich edit ctrl set profile skin key lpctstr psz skin key m strskinkey psz skin key chtricheditctrl setprofileskinkey pszskinkey m_strskinkey pszskinkey void cht rich edit ctrl set title lpctstr psz title m strtitle psz title chtricheditctrl settitle psztitle m_strtitle psztitle void cht rich edit ctrl localize chtricheditctrl void cht rich edit ctrl apply skin if m strskinkey is empty colorref cr if the app load skin color m strskinkey t bk cr set background color false cr else set background color true get sys color color window chtricheditctrl applyskin m_strskinkey isempty theapp loadskincolor m_strskinkey _t setbackgroundcolor setbackgroundcolor getsyscolor color_window void cht rich edit ctrl add entry lpctstr psz msg c string str line psz msg str line t n if m hwnd null m astrbuff add str line else flush buffer add line str line str line get length chtricheditctrl addentry pszmsg cstring strline pszmsg strline _t m_hwnd m_astrbuff strline flushbuffer addline strline strline getlength void cht rich edit ctrl add lpctstr psz msg int i len if m hwnd null c string str line psz msg m astrbuff add str line else flush buffer add line psz msg i len chtricheditctrl pszmsg ilen m_hwnd cstring strline pszmsg m_astrbuff strline flushbuffer addline pszmsg ilen void cht rich edit ctrl add typed lpctstr psz msg int i len uint e msg type if m hwnd null c string str line str line tchar e msg type logmsgtypemask str line psz msg m astrbuff add str line else flush buffer add line psz msg i len false get log line color e msg type logmsgtypemask chtricheditctrl addtyped pszmsg ilen emsgtype m_hwnd cstring strline strline emsgtype strline pszmsg m_astrbuff strline flushbuffer addline pszmsg ilen getloglinecolor emsgtype void cht rich edit ctrl reset m astrbuff remove all set redraw false set window text t set redraw if m brichedit invalidate chtricheditctrl m_astrbuff removeall setredraw setwindowtext _t setredraw m_brichedit c string cht rich edit ctrl get last log entry c string str log int i last line get line count 2 if i last line 0 get line i last line str log get buffer 1024 1024 str log release buffer return str log cstring chtricheditctrl getlastlogentry cstring strlog ilastline getlinecount ilastline getline ilastline strlog getbuffer strlog releasebuffer strlog c string cht rich edit ctrl get all log entries c string str log get window text str log return str log cstring chtricheditctrl getalllogentries cstring strlog getwindowtext strlog strlog bool cht rich edit ctrl save log lpctstr psz def name bool b result false c file dialog dlg false t log psz def name psz def name lpctstr m strtitle ofn hidereadonly ofn overwriteprompt t log files log log this 0 if dlg do modal idok file fp tfsopen dlg get path name t wb sh denywr if fp write unicode byte order mark 0xfeff fputwc 0xfeff fp c string str text get window text str text fwrite str text sizeof tchar str text get length fp if ferror fp c string str error str error format t failed to write log file s s dlg get path name strerror errno afx message box str error mb iconerror else b result true fclose fp else c string str error str error format t failed to create log file s s dlg get path name strerror errno afx message box str error mb iconerror return b result chtricheditctrl savelog pszdefname bresult cfiledialog _t pszdefname pszdefname m_strtitle ofn_hidereadonly ofn_overwriteprompt _t domodal _tfsopen getpathname _t _sh_denywr cstring strtext getwindowtext strtext strtext strtext getlength cstring strerror strerror _t getpathname afxmessagebox strerror mb_iconerror bresult cstring strerror strerror _t getpathname afxmessagebox strerror mb_iconerror bresult void cht rich edit ctrl append text const c string s text lpctstr psz s text lpctstr psz start psz while psz t 0 bool b found scheme false for int i 0 i arrsize apszschemes i if tcsncmp psz apszschemes i psz scheme apszschemes i i len 0 output everything before the url if psz psz start 0 c string str psz start psz psz start add line str str get length search next space or eol int i len tcscspn psz t n r t if i len 0 add line psz 1 true psz tcslen psz else c string str psz i len add line str str get length true psz i len psz start psz b found scheme true break if b found scheme psz tcsinc psz if psz start t 0 add line psz start 1 chtricheditctrl appendtext cstring stext stext pszstart _t bfoundscheme _apszschemes _tcsncmp _apszschemes pszscheme _apszschemes ilen pszstart cstring pszstart pszstart addline getlength ilen _tcscspn _t ilen addline _tcslen cstring ilen addline getlength ilen pszstart bfoundscheme bfoundscheme _tcsinc pszstart _t addline pszstart void cht rich edit ctrl append hyper link const c string s text const c string s title const c string s command const c string s directory unreferenced parameter s text unreferenced parameter s title unreferenced parameter s directory assert s text is empty assert s title is empty assert s directory is empty add line s command s command get length true chtricheditctrl appendhyperlink cstring stext cstring stitle cstring scommand cstring sdirectory unreferenced_parameter stext unreferenced_parameter stitle unreferenced_parameter sdirectory stext isempty stitle isempty sdirectory isempty addline scommand scommand getlength void cht rich edit ctrl append key word const c string str colorref cr append colored text str cr chtricheditctrl appendkeyword cstring appendcoloredtext void cht rich edit ctrl append colored text lpctstr psz text colorref cr add line psz text 1 false cr chtricheditctrl appendcoloredtext psztext addline psztext c string cht rich edit ctrl get text const c string str text get window text str text return str text cstring chtricheditctrl gettext cstring strtext getwindowtext strtext strtext void cht rich edit ctrl scroll to last line bool b force last line at bottom if b force last line at bottom int i first visible get first visible line if i first visible 0 line scroll i first visible wm vscroll does not work correctly under win98 or older version of comctl dll send message wm vscroll sb bottom if afx data b win95 older version of comctl dll seem to need this to properly update the display int i pos get scroll pos sb vert send message wm vscroll makelong sb thumbposition i pos send message wm vscroll sb endscroll chtricheditctrl scrolltolastline bforcelastlineatbottom bforcelastlineatbottom ifirstvisible getfirstvisibleline ifirstvisible linescroll ifirstvisible wm_vscroll sendmessage wm_vscroll sb_bottom afxdata bwin95 ipos getscrollpos sb_vert sendmessage wm_vscroll sb_thumbposition ipos sendmessage wm_vscroll sb_endscroll void cht rich edit ctrl set font c font p font bool b redraw logfont lf 0 p font get log font lf charformat cf 0 cf cb size sizeof cf cf dw mask cfm bold cf dw effects lf lf weight fw bold cfe bold 0 cf dw mask cfm italic cf dw effects lf lf italic cfe italic 0 cf dw mask cfm underline cf dw effects lf lf underline cfe underline 0 cf dw mask cfm strikeout cf dw effects lf lf strike out cfe strikeout 0 cf dw mask cfm size hdc hdc getdc null int i point size mul div lf lf height 72 get device caps hdc logpixelsy cf y height i point size 20 releasedc null hdc cf dw mask cfm face cf b pitch and family lf lf pitch and family tcsncpy cf sz face name lf lf face name arrsize cf sz face name cf sz face name arrsize cf sz face name 1 t 0 although this should work correctly according sdk it may give false results e g the click here text which is shown in the server info window may not be entirely used as a hyperlink cf dw mask cfm charset cf b char set lf lf char set cf y offset 0 verify set default char format cf verify get selection char format m cfdefault if b redraw invalidate update window chtricheditctrl setfont cfont pfont bredraw pfont getlogfont cbsize dwmask cfm_bold dweffects lfweight fw_bold cfe_bold dwmask cfm_italic dweffects lfitalic cfe_italic dwmask cfm_underline dweffects lfunderline cfe_underline dwmask cfm_strikeout dweffects lfstrikeout cfe_strikeout dwmask cfm_size ipointsize muldiv lfheight getdevicecaps yheight ipointsize dwmask cfm_face bpitchandfamily lfpitchandfamily _tcsncpy szfacename lffacename szfacename szfacename szfacename _t dwmask cfm_charset bcharset lfcharset yoffset setdefaultcharformat getselectioncharformat m_cfdefault bredraw updatewindow c font cht rich edit ctrl get font const assert 0 return null cfont chtricheditctrl getfont void cht rich edit ctrl add line lpctstr psz msg int i len bool b link colorref cr int i msg len i len 1 tcslen psz msg i len if i msg len 0 return ifdef debug if psz msg i msg len 1 t n assert i msg len 2 psz msg i msg len 2 t r endif get edit contents dimensions and cursor position long l start char l end char get sel l start char l end char int i size get window text length if l start char i size i size l end char the cursor resides at the end of text scrollinfo si si cb size sizeof si si f mask sif all if m bautoscroll get scroll info sb vert si si n pos int si n max si n page 1 not scrolled away safe add line i size psz msg i len l start char l end char b link cr if m bautoscroll is window visible scroll to last line else reduce flicker by ignoring wm paint m bnopaint true bool b is visible is window visible if b is visible set redraw false remember where we are int i first line m bautoscroll get first visible line 0 select at the end of text and replace the selection this is a very fast way to add text to an edit control safe add line i size psz msg i len l start char l end char b link cr if m bautoscroll l start char l end char l start char l end char 1 set sel l start char l end char restore our previous selection if m bautoscroll line scroll i first line get first visible line else scroll to last line m bnopaint false if b is visible set redraw if m brichedit invalidate else we should add the text anyway reduce flicker by ignoring wm paint m bnopaint true bool b is visible is window visible if b is visible set redraw false remember where we are int i first line m bautoscroll get first visible line 0 very annoying problems with em getscrollpos em setscrollpos depending on the amount of data in the control the control may start to scroll up by itself obviously because of some internal rounding errors using line scroll also gives glitches also depending on the amount of data stored in the control but at least it doesn t start to show some life point pt scroll pos if m bautoscroll send message em getscrollpos 0 lparam pt scroll pos if l start char l end char if we are currently selecting some text we have to find out if the caret is near the beginning of this block or near the end note that this does not always work because of the em charfrompos message returning only 16 bits this will fail if the user has selected a block with a length dividable by 64k note this may cause a lot of terrible crashes within the rich edit control when used for a rich edit control to reproduce the crash click in the re control while it s drawing a line and start a selection if m brichedit c point pt get caret pos pt int i caret pos char from pos pt if abs l start char 0xffff i caret pos abs l end char 0xffff i caret pos i caret pos l start char l start char l end char l end char i caret pos note this will flicker if someone has a good idea how to prevent this let me know select at the end of text and replace the selection this is a very fast way to add text to an edit control safe add line i size psz msg i len l start char l end char b link cr pt scroll pos if m bautoscroll l start char l end char l start char l end char 1 set sel l start char l end char restore our previous selection if m bautoscroll line scroll i first line get first visible line send message em setscrollpos 0 lparam pt scroll pos else scroll to last line m bnopaint false if b is visible set redraw if m brichedit invalidate chtricheditctrl addline pszmsg ilen blink imsglen ilen _tcslen pszmsg ilen imsglen _debug pszmsg imsglen _t imsglen pszmsg imsglen _t lstartchar lendchar getsel lstartchar lendchar isize getwindowtextlength lstartchar isize isize lendchar cbsize fmask sif_all m_bautoscroll getscrollinfo sb_vert npos nmax npage safeaddline isize pszmsg ilen lstartchar lendchar blink m_bautoscroll iswindowvisible scrolltolastline wm_paint m_bnopaint bisvisible iswindowvisible bisvisible setredraw ifirstline m_bautoscroll getfirstvisibleline safeaddline isize pszmsg ilen lstartchar lendchar blink m_bautoscroll lstartchar lendchar lstartchar lendchar setsel lstartchar lendchar m_bautoscroll linescroll ifirstline getfirstvisibleline scrolltolastline m_bnopaint bisvisible setredraw m_brichedit wm_paint m_bnopaint bisvisible iswindowvisible bisvisible setredraw ifirstline m_bautoscroll getfirstvisibleline em_getscrollpos em_setscrollpos linescroll ptscrollpos m_bautoscroll sendmessage em_getscrollpos ptscrollpos lstartchar lendchar em_charfrompos richedit richedit m_brichedit cpoint getcaretpos icaretpos charfrompos lstartchar icaretpos lendchar icaretpos icaretpos lstartchar lstartchar lendchar lendchar icaretpos safeaddline isize pszmsg ilen lstartchar lendchar blink ptscrollpos m_bautoscroll lstartchar lendchar lstartchar lendchar setsel lstartchar lendchar m_bautoscroll linescroll ifirstline getfirstvisibleline sendmessage em_setscrollpos ptscrollpos scrolltolastline m_bnopaint bisvisible setredraw m_brichedit void cht rich edit ctrl select all items set sel 0 1 chtricheditctrl selectallitems setsel void cht rich edit ctrl copy selected items copy chtricheditctrl copyselecteditems void cht rich edit ctrl safe add line int n pos lpctstr psz line int i len long l start char long l end char bool b link colorref cr en errspace and en maxtext are not working for rich edit control at least not same as for standard control need to explicitly check the log buffer limit int i cur size n pos if i cur size i len m ilimittext bool b old no paint m bnopaint m bnopaint true bool b is visible is window visible if b is visible set redraw false while i cur size 0 i cur size i len m ilimittext delete 1st line int i line0 len line length 0 1 add nl character set sel 0 i line0 len replace sel t update any possible available selection l start char i line0 len if l start char 0 l start char 0 l end char i line0 len if l end char 0 l end char 0 i cur size get window text length m bnopaint b old no paint if b is visible m bnopaint set redraw if m brichedit invalidate add string n pos psz line b link cr if m benerrspace bool b old no paint m bnopaint m bnopaint true bool b is visible is window visible if b is visible set redraw false remove the first line as long as we are capable of adding the new line int i safety counter 0 while m benerrspace i safety counter 10 delete the previous partially added line set sel n pos 1 replace sel t delete 1st line int i line0 len line length 0 1 add nl character set sel 0 i line0 len replace sel t update any possible available selection l start char i line0 len if l start char 0 l start char 0 l end char i line0 len if l end char 0 l end char 0 add the new line again n pos get window text length add string n pos psz line b link cr if m benerrspace n pos 0 should never happen if we tried to add the line another time in the 1st line there will be no chance to add the line at all avoid endless loop break i safety counter never ever create an endless loop m bnopaint b old no paint if b is visible m bnopaint set redraw if m brichedit invalidate chtricheditctrl safeaddline npos pszline ilen lstartchar lendchar blink en_errspace en_maxtext icursize npos icursize ilen m_ilimittext boldnopaint m_bnopaint m_bnopaint bisvisible iswindowvisible bisvisible setredraw icursize icursize ilen m_ilimittext iline0len linelength setsel iline0len replacesel _t lstartchar iline0len lstartchar lstartchar lendchar iline0len lendchar lendchar icursize getwindowtextlength m_bnopaint boldnopaint bisvisible m_bnopaint setredraw m_brichedit addstring npos pszline blink m_benerrspace boldnopaint m_bnopaint m_bnopaint bisvisible iswindowvisible bisvisible setredraw isafetycounter m_benerrspace isafetycounter setsel npos replacesel _t iline0len linelength setsel iline0len replacesel _t lstartchar iline0len lstartchar lstartchar lendchar iline0len lendchar lendchar npos getwindowtextlength addstring npos pszline blink m_benerrspace npos isafetycounter m_bnopaint boldnopaint bisvisible m_bnopaint setredraw m_brichedit void cht rich edit ctrl flush buffer if m astrbuff get size 0 flush buffer for int i 0 i m astrbuff get size i const c string rstr line m astrbuff i if rstr line is empty if tuchar rstr line 0 8 add line lpctstr rstr line 1 rstr line get length 1 false get log line color tuchar rstr line 0 else add line lpctstr rstr line rstr line get length m astrbuff remove all chtricheditctrl flushbuffer m_astrbuff getsize m_astrbuff getsize cstring rstrline m_astrbuff rstrline isempty _tuchar rstrline addline rstrline rstrline getlength getloglinecolor _tuchar rstrline addline rstrline rstrline getlength m_astrbuff removeall void cht rich edit ctrl add string int n pos lpctstr psz string bool b link colorref cr bool b restore format false m benerrspace false set sel n pos n pos if b link charformat2 cf memset cf 0 sizeof cf get selection char format cf cf dw mask cfm link cf dw effects cfe link set selection char format cf else if cr clr default charformat cf get selection char format cf cf dw mask cfm color cf dw effects cfe autocolor cf cr text color cr set selection char format cf b restore format true else if m brestoreformat set selection char format m cfdefault replace sel psz string m brestoreformat b restore format chtricheditctrl addstring npos pszstring blink brestoreformat m_benerrspace setsel npos npos blink getselectioncharformat dwmask cfm_link dweffects cfe_link setselectioncharformat clr_default getselectioncharformat dwmask cfm_color dweffects cfe_autocolor crtextcolor setselectioncharformat brestoreformat m_brestoreformat setselectioncharformat m_cfdefault replacesel pszstring m_brestoreformat brestoreformat lresult cht rich edit ctrl window proc uint message wparam w param lparam l param switch message case wm erasebkgnd if m bnopaint return true case wm paint if m bnopaint return true return c rich edit ctrl window proc message w param l param chtricheditctrl windowproc wparam lparam wm_erasebkgnd m_bnopaint wm_paint m_bnopaint cricheditctrl windowproc wparam lparam int cht rich edit ctrl on create lpcreatestruct lp create struct if c rich edit ctrl on create lp create struct 1 return 1 init null return 0 chtricheditctrl oncreate lpcreatestruct cricheditctrl oncreate lpcreatestruct void cht rich edit ctrl on context menu c wnd p wnd c point point long l sel start l sel end get sel l sel start l sel end ugly simulate a left click to get around the text cursor problem when right clicking if point x 1 point y 1 l sel start l sel end c point pt mouse point screen to client pt mouse send message wm lbuttondown mk lbutton makelong pt mouse x pt mouse y send message wm lbuttonup mk lbutton makelong pt mouse x pt mouse y int i text len get window text length c title menu menu menu create popup menu menu add menu title get res string ids logentry menu append menu mf string l sel end l sel start mf enabled mf grayed mp copyselected get res string ids copy menu append menu mf separator menu append menu mf string i text len 0 mf enabled mf grayed mp selectall get res string ids selectall menu append menu mf string i text len 0 mf enabled mf grayed mp removeall get res string ids pw reset menu append menu mf string i text len 0 mf enabled mf grayed mp savelog get res string ids savelog t menu append menu mf separator menu append menu mf string m bautoscroll mf checked mf unchecked mp autoscroll get res string ids autoscroll if point x 1 point y 1 point x 16 point y 32 client to screen point cheap workaround for the text cursor is showing while context menu is open glitch it could be solved properly with the re s com interface but because the according messages are not routed with a unique control id it s not really useable e g if there are more re controls in one window would to envelope each re window to get a unique id m bforcearrowcursor true menu track popup menu tpm leftalign tpm rightbutton point x point y this m bforcearrowcursor false verify menu destroy menu chtricheditctrl oncontextmenu cwnd pwnd cpoint lselstart lselend getsel lselstart lselend lselstart lselend cpoint ptmouse screentoclient ptmouse sendmessage wm_lbuttondown mk_lbutton ptmouse ptmouse sendmessage wm_lbuttonup mk_lbutton ptmouse ptmouse itextlen getwindowtextlength ctitlemenu createpopupmenu addmenutitle getresstring ids_logentry appendmenu mf_string lselend lselstart mf_enabled mf_grayed mp_copyselected getresstring ids_copy appendmenu mf_separator appendmenu mf_string itextlen mf_enabled mf_grayed mp_selectall getresstring ids_selectall appendmenu mf_string itextlen mf_enabled mf_grayed mp_removeall getresstring ids_pw_reset appendmenu mf_string itextlen mf_enabled mf_grayed mp_savelog getresstring ids_savelog _t appendmenu mf_separator appendmenu mf_string m_bautoscroll mf_checked mf_unchecked mp_autoscroll getresstring ids_autoscroll clienttoscreen m_bforcearrowcursor trackpopupmenu tpm_leftalign tpm_rightbutton m_bforcearrowcursor destroymenu bool cht rich edit ctrl on command wparam w param lparam l param switch w param case mp copyselected copy selected items break case mp selectall select all items break case mp removeall reset break case mp savelog save log break case mp autoscroll m bautoscroll m bautoscroll break return true chtricheditctrl oncommand wparam lparam wparam mp_copyselected copyselecteditems mp_selectall selectallitems mp_removeall mp_savelog savelog mp_autoscroll m_bautoscroll m_bautoscroll void cht rich edit ctrl on key down uint n char uint n rep cnt uint n flags if n char a get key state vk control 0x8000 ctrl a select all items select all items else if n char c get key state vk control 0x8000 ctrl c copy listview items to clipboard copy selected items else if n char vk escape dont minimize cht rich edit ctrl return c rich edit ctrl on key down n char n rep cnt n flags chtricheditctrl onkeydown nchar nrepcnt nflags nchar getkeystate vk_control selectallitems nchar getkeystate vk_control copyselecteditems nchar vk_escape chtricheditctrl cricheditctrl onkeydown nchar nrepcnt nflags void cht rich edit ctrl on en errspace m benerrspace true chtricheditctrl onenerrspace m_benerrspace void cht rich edit ctrl on en maxtext m benerrspace true chtricheditctrl onenmaxtext m_benerrspace bool cht rich edit ctrl on en link nmhdr pnmhdr lresult p result bool b msg handled false p result 0 enlink p en link reinterpret cast enlink pnmhdr if p en link p en link msg wm lbuttondown c string str url get text range p en link chrg cp min p en link chrg cp max str url check if that url has a valid url scheme if it does not have pass that notification up to the parent window which may interpret that url in some other way for int i 0 i arrsize apszschemes i if tcsncmp str url apszschemes i psz scheme apszschemes i i len 0 shell execute null null str url null null sw showdefault p result 1 b msg handled true do not route this message to any parent break return b msg handled chtricheditctrl onenlink presult bmsghandled presult penlink reinterpret_cast penlink penlink wm_lbuttondown cstring strurl gettextrange penlink cpmin penlink cpmax strurl _apszschemes _tcsncmp strurl _apszschemes pszscheme _apszschemes ilen shellexecute strurl sw_showdefault presult bmsghandled bmsghandled void cht rich edit ctrl on sys color change c rich edit ctrl on sys color change apply skin chtricheditctrl onsyscolorchange cricheditctrl onsyscolorchange applyskin bool cht rich edit ctrl on set cursor c wnd p wnd uint n hit test uint message cheap workaround for the text cursor is showing while context menu is open glitch it could be solved properly with the re s com interface but because the according messages are not routed with a unique control id it s not really useable e g if there are more re controls in one window would to envelope each re window to get a unique id if m bforcearrowcursor m harrowcursor set cursor m harrowcursor return true return c rich edit ctrl on set cursor p wnd n hit test message chtricheditctrl onsetcursor cwnd pwnd nhittest m_bforcearrowcursor m_harrowcursor setcursor m_harrowcursor cricheditctrl onsetcursor pwnd nhittest c custom auto complete c custom auto complete internal init ccustomautocomplete ccustomautocomplete internalinit c custom auto complete c custom auto complete const c string array p sitemlist internal init set list p sitemlist ccustomautocomplete ccustomautocomplete cstringarray p_sitemlist internalinit setlist p_sitemlist c custom auto complete c custom auto complete if m pac m pac release ccustomautocomplete ccustomautocomplete m_pac m_pac bool c custom auto complete bind hwnd p hwndedit dword p dwoptions lpctstr p lpszformatstring atlassert is window p hwndedit if m fbound m pac return false hresult hr m pac co create instance clsid autocomplete if succeeded hr if p dwoptions c comqi ptr i auto complete2 pac2 m pac if pac2 pac2 set options p dwoptions pac2 release uses conversion if succeeded hr m pac init p hwndedit this null t2cw p lpszformatstring m fbound true return true return false ccustomautocomplete p_hwndedit p_dwoptions p_lpszformatstring iswindow p_hwndedit m_fbound m_pac m_pac cocreateinstance clsid_autocomplete p_dwoptions ccomqiptr iautocomplete2 m_pac setoptions p_dwoptions uses_conversion m_pac p_hwndedit p_lpszformatstring m_fbound void c custom auto complete unbind if m fbound return if m pac m pac release m fbound false ccustomautocomplete m_fbound m_pac m_pac m_fbound bool c custom auto complete set list const c string array p sitemlist atlassert p sitemlist get size 0 clear m aslist append p sitemlist return true ccustomautocomplete setlist cstringarray p_sitemlist p_sitemlist getsize m_aslist p_sitemlist const c string array c custom auto complete get list const return m aslist cstringarray ccustomautocomplete getlist m_aslist int c custom auto complete get item count return int m aslist get count ccustomautocomplete getitemcount m_aslist getcount bool c custom auto complete add item const c string p sitem int i pos if p sitem get length 0 int oldpos find item p sitem if oldpos 1 use a lru list if i pos 1 m aslist add p sitem else m aslist insert at i pos p sitem while m aslist get size m imaxitemcount m aslist remove at m aslist get size 1 return true else if i pos 1 m aslist remove at oldpos if oldpos i pos i pos m aslist insert at i pos p sitem while m aslist get size m imaxitemcount m aslist remove at m aslist get size 1 return true return false ccustomautocomplete additem cstring p_sitem ipos p_sitem getlength finditem p_sitem ipos m_aslist p_sitem m_aslist insertat ipos p_sitem m_aslist getsize m_imaxitemcount m_aslist removeat m_aslist getsize ipos m_aslist removeat ipos ipos m_aslist insertat ipos p_sitem m_aslist getsize m_imaxitemcount m_aslist removeat m_aslist getsize bool c custom auto complete remove item const c string p sitem if p sitem get length 0 int i pos find item p sitem if i pos 1 m aslist remove at i pos return true return false ccustomautocomplete removeitem cstring p_sitem p_sitem getlength ipos finditem p_sitem ipos m_aslist removeat ipos c string c custom auto complete get item int pos if pos m aslist get count return null else return m aslist get at pos cstring ccustomautocomplete getitem m_aslist getcount m_aslist getat bool c custom auto complete clear if m aslist get size 0 m aslist remove all return true return false ccustomautocomplete m_aslist getsize m_aslist removeall bool c custom auto complete disable if m pac m fbound return false return succeeded en disable false ccustomautocomplete m_pac m_fbound endisable bool c custom auto complete enable void if m pac m fbound return false return succeeded en disable true ccustomautocomplete m_pac m_fbound endisable bool c custom auto complete load list lpctstr psz file name file fp tfsopen psz file name t rb sh denywr if fp null return false verify unicode byte order mark 0xfeff word wbom fgetwc fp if wbom 0xfeff fclose fp return false tchar sz item 256 while fgetts sz item arrsize sz item fp null c string str item sz item str item trim t r n add item str item 1 fclose fp return true ccustomautocomplete loadlist pszfilename _tfsopen pszfilename _t _sh_denywr szitem _fgetts szitem szitem cstring stritem szitem stritem _t additem stritem bool c custom auto complete save list lpctstr psz file name file fp tfsopen psz file name t wb sh denywr if fp null return false write unicode byte order mark 0xfeff fputwc 0xfeff fp for int i 0 i m aslist get count i ftprintf fp t s r n m aslist i fclose fp return ferror fp ccustomautocomplete savelist pszfilename _tfsopen pszfilename _t _sh_denywr m_aslist getcount _ftprintf _t m_aslist stdmethodimp ulong c custom auto complete add ref ulong n count interlocked increment reinterpret cast long m nrefcount return n count stdmethodimp_ ccustomautocomplete addref ncount interlockedincrement reinterpret_cast m_nrefcount ncount stdmethodimp ulong c custom auto complete release ulong n count 0 n count ulong interlocked decrement reinterpret cast long m nrefcount if n count 0 delete this return n count stdmethodimp_ ccustomautocomplete ncount ncount interlockeddecrement reinterpret_cast m_nrefcount ncount ncount stdmethodimp c custom auto complete query interface refiid riid void ppv object hresult hr e nointerface if ppv object null ppv object null if iid iunknown riid ppv object static cast i unknown this else if iid ienumstring riid ppv object static cast i enum string this if ppv object null hr s ok lpunknown ppv object add ref else hr e pointer return hr ccustomautocomplete queryinterface ppvobject e_nointerface ppvobject ppvobject iid_iunknown ppvobject static_cast iunknown iid_ienumstring ppvobject static_cast ienumstring ppvobject s_ok ppvobject addref e_pointer stdmethodimp c custom auto complete next ulong celt lpolestr rgelt ulong pcelt fetched uses conversion hresult hr s false if celt celt 1 for ulong i 0 i celt i if m ncurrentelement ulong m aslist get size break rgelt i lpwstr co task mem alloc ulong sizeof wchar m aslist m ncurrentelement get length 1 wcscpy rgelt i t2cw m aslist m ncurrentelement if pcelt fetched pcelt fetched m ncurrentelement if i celt hr s ok return hr ccustomautocomplete pceltfetched uses_conversion s_false m_ncurrentelement m_aslist getsize cotaskmemalloc m_aslist m_ncurrentelement getlength m_aslist m_ncurrentelement pceltfetched pceltfetched m_ncurrentelement s_ok stdmethodimp c custom auto complete skip ulong celt m ncurrentelement celt if m ncurrentelement ulong m aslist get size m ncurrentelement 0 return s ok ccustomautocomplete m_ncurrentelement m_ncurrentelement m_aslist getsize m_ncurrentelement s_ok stdmethodimp c custom auto complete reset void m ncurrentelement 0 return s ok ccustomautocomplete m_ncurrentelement s_ok stdmethodimp c custom auto complete clone i enum string ppenum if ppenum return e pointer c custom auto complete pnew new c custom auto complete pnew add ref ppenum pnew return s ok ccustomautocomplete ienumstring e_pointer ccustomautocomplete ccustomautocomplete addref s_ok void c custom auto complete internal init m ncurrentelement 0 m nrefcount 0 m fbound false m imaxitemcount 30 ccustomautocomplete internalinit m_ncurrentelement m_nrefcount m_fbound m_imaxitemcount hresult c custom auto complete en disable bool p fenable atlassert m pac hresult hr m pac enable p fenable if succeeded hr m fbound p fenable return hr ccustomautocomplete endisable p_fenable m_pac m_pac p_fenable m_fbound p_fenable int c custom auto complete find item const c string rstr for int i 0 i m aslist get count i if m aslist i compare rstr 0 return i return 1 ccustomautocomplete finditem cstring m_aslist getcount m_aslist c dialog c http download dlg idd p parent afx data init c http download dlg afx data init m hinternetsession null m hhttpconnection null m hhttpfile null m babort false m bsafetoclose false m pthread null cdialog chttpdownloaddlg pparent afx_data_init chttpdownloaddlg afx_data_init m_hinternetsession m_hhttpconnection m_hhttpfile m_babort m_bsafetoclose m_pthread void c http download dlg do data exchange c data exchange pdx c dialog do data exchange pdx afx data map c http download dlg ddx control pdx idc status m ctrlstatus ddx control pdx idc transfer rate m ctrltransferrate ddx control pdx idc timeleft m ctrltimeleft ddx control pdx idc progress1 m ctrlprogress ddx control pdx idc filestatus m ctrlfilestatus ddx control pdx idc animate1 m ctrlanimate afx data map chttpdownloaddlg dodataexchange cdataexchange cdialog dodataexchange afx_data_map chttpdownloaddlg ddx_control idc_status m_ctrlstatus ddx_control idc_transfer_rate m_ctrltransferrate ddx_control idc_timeleft m_ctrltimeleft ddx_control idc_progress1 m_ctrlprogress ddx_control idc_filestatus m_ctrlfilestatus ddx_control idc_animate1 m_ctrlanimate afx_data_map bool c http download dlg on init dialog c string cap cap get res string ids cancel get dlg item idcancel set window text cap if m strtitle is empty set window text m strtitle let the parent class do its thing c dialog on init dialog init window styles this setup the animation control m ctrlanimate open idr httpdownload ani validate the url assert m surltodownload get length did you forget to specify the file to download if afx parseurl m surltodownload m dwservicetype m sserver m sobject m nport try sticking http before it m surltodownload t http m surltodownload if afx parseurl m surltodownload m dwservicetype m sserver m sobject m nport trace t failed to parse the url s n m surltodownload end dialog idcancel return true check to see if the file we are downloading to exists and if it does then ask the user if they were it overwritten edited we always want to overwrite old language dlls and server mets c file status fs assert m sfiletodownloadinto get length if c file get status m sfiletodownloadinto fs c string s msg s msg format get res string ids httpdownload ok to overwrite m sfiletodownloadinto if afx message box s msg mb yesno idyes trace t failed to confirm file overwrite download aborted n end dialog idcancel return true try and open the file we will download into if m filetowrite open m sfiletodownloadinto c file mode create c file mode write c file share deny write trace t failed to open the file to download into error d n get last error c string s error s error format t d get last error c string s msg s msg format get res string ids httpdownload fail file open s error afx message box s msg end dialog idcancel return true pull out just the filename component int n slash m sobject reverse find t if n slash 1 n slash m sobject reverse find t if n slash 1 m sobject get length 1 m sfilename m sobject right m sobject get length n slash 1 else m sfilename m sobject set the file status text c string s file status assert m sobject get length assert m sserver get length s file status format get res string ids httpdownload filestatus m sfilename m sserver m ctrlfilestatus set window text s file status set labels set dlg item text idc timelefttext get res string ids esttimeleft set dlg item text idc transfer rate label get res string ids transfer rate label spin off the background thread which will do the actual downloading m pthread afx begin thread downloadthread this thread priority normal 0 create suspended if m pthread null trace t failed to create download thread dialog is aborting n end dialog idcancel return true m pthread m bautodelete false m pthread resume thread return true chttpdownloaddlg oninitdialog cstring getresstring ids_cancel getdlgitem setwindowtext m_strtitle isempty setwindowtext m_strtitle cdialog oninitdialog initwindowstyles m_ctrlanimate idr_httpdownload_ani m_surltodownload getlength afxparseurl m_surltodownload m_dwservicetype m_sserver m_sobject m_nport m_surltodownload _t m_surltodownload afxparseurl m_surltodownload m_dwservicetype m_sserver m_sobject m_nport _t m_surltodownload enddialog cfilestatus m_sfiletodownloadinto getlength cfile getstatus m_sfiletodownloadinto cstring smsg smsg getresstring ids_httpdownload_ok_to_overwrite m_sfiletodownloadinto afxmessagebox smsg mb_yesno _t enddialog m_filetowrite m_sfiletodownloadinto cfile modecreate cfile modewrite cfile sharedenywrite _t getlasterror cstring serror serror _t getlasterror cstring smsg smsg getresstring ids_httpdownload_fail_file_open serror afxmessagebox smsg enddialog nslash m_sobject reversefind _t nslash nslash m_sobject reversefind _t nslash m_sobject getlength m_sfilename m_sobject m_sobject getlength nslash m_sfilename m_sobject cstring sfilestatus m_sobject getlength m_sserver getlength sfilestatus getresstring ids_httpdownload_filestatus m_sfilename m_sserver m_ctrlfilestatus setwindowtext sfilestatus setdlgitemtext idc_timelefttext getresstring ids_esttimeleft setdlgitemtext idc_transfer_rate_label getresstring ids_transfer_rate_label m_pthread afxbeginthread _downloadthread thread_priority_normal create_suspended m_pthread _t enddialog m_pthread m_bautodelete m_pthread resumethread void c http download dlg on destroy wait for the worker thread to exit if m pthread wait for single object m pthread m hthread infinite delete m pthread m pthread null free up the internet handles we may be using if m hhttpfile internet close handle m hhttpfile m hhttpfile null if m hhttpconnection internet close handle m hhttpconnection m hhttpconnection null if m hinternetsession internet close handle m hinternetsession m hinternetsession null let the parent class do its thing c dialog on destroy chttpdownloaddlg ondestroy m_pthread waitforsingleobject m_pthread m_hthread m_pthread m_pthread m_hhttpfile internetclosehandle m_hhttpfile m_hhttpfile m_hhttpconnection internetclosehandle m_hhttpconnection m_hhttpconnection m_hinternetsession internetclosehandle m_hinternetsession m_hinternetsession cdialog ondestroy void c http download dlg on cancel asynchronously free up the internet handles we may be using otherwise we may get some kind of deadlock situation because internet connect may not return for a very long time if m hhttpfile internet close handle m hhttpfile m hhttpfile null if m hhttpconnection internet close handle m hhttpconnection m hhttpconnection null if m hinternetsession internet close handle m hinternetsession m hinternetsession null just set the abort flag to true and disable the cancel button m babort true get dlg item idcancel enable window false set status get res string ids httpdownload aborting transfer chttpdownloaddlg oncancel internetconnect m_hhttpfile internetclosehandle m_hhttpfile m_hhttpfile m_hhttpconnection internetclosehandle m_hhttpconnection m_hhttpconnection m_hinternetsession internetclosehandle m_hinternetsession m_hinternetsession m_babort getdlgitem enablewindow setstatus getresstring ids_httpdownload_aborting_transfer void c http download dlg on close if m bsafetoclose c dialog on close else just set the abort flag to true and disable the cancel button m babort true get dlg item idcancel enable window false set status get res string ids httpdownload aborting transfer chttpdownloaddlg onclose m_bsafetoclose cdialog onclose m_babort getdlgitem enablewindow setstatus getresstring ids_httpdownload_aborting_transfer lresult c http download dlg on thread finished wparam w param lparam l param it s now safe to close since the thread has signaled us m bsafetoclose true stop the animation m ctrlanimate stop sleep 1000 if an error occured display the message box if m babort end dialog idcancel else if w param if m serror is empty log error log statusbar t s m serror end dialog idcancel else end dialog idok return 0l chttpdownloaddlg onthreadfinished wparam lparam m_bsafetoclose m_ctrlanimate m_babort enddialog wparam m_serror isempty logerror log_statusbar _t m_serror enddialog enddialog lpvoid lpv status information dword dw status information length convert from the sdk c world to the c world elandal assumes sizeof void sizeof unsigned long c http download dlg p dlg c http download dlg dw context assert p dlg assert p dlg is kind of runtime class c http download dlg p dlg on status call back h internet dw internet status lpv status information dw status information length lpvstatusinformation dwstatusinformationlength chttpdownloaddlg pdlg chttpdownloaddlg dwcontext pdlg pdlg iskindof runtime_class chttpdownloaddlg pdlg onstatuscallback hinternet dwinternetstatus lpvstatusinformation dwstatusinformationlength lpvoid lpv status information dword dw status information length switch dw internet status case internet status resolving name set status get res string ids httpdownload resolving name lpctstr lpv status information break case internet status name resolved set status get res string ids httpdownload resolved name lpctstr lpv status information break case internet status connecting to server set status get res string ids httpdownload connecting lpctstr lpv status information break case internet status connected to server set status get res string ids httpdownload connected lpctstr lpv status information break case internet status redirect set status get res string ids httpdownload redirecting lpctstr lpv status information break default break lpvstatusinformation dwstatusinformationlength dwinternetstatus internet_status_resolving_name setstatus getresstring ids_httpdownload_resolving_name lpvstatusinformation internet_status_name_resolved setstatus getresstring ids_httpdownload_resolved_name lpvstatusinformation internet_status_connecting_to_server setstatus getresstring ids_httpdownload_connecting lpvstatusinformation internet_status_connected_to_server setstatus getresstring ids_httpdownload_connected lpvstatusinformation internet_status_redirect setstatus getresstring ids_httpdownload_redirecting lpvstatusinformation uint afx cdecl c http download dlg downloadthread lpvoid p param dbg set thread name http download init thread locale convert from the sdk world to the c world c http download dlg p dlg c http download dlg p param assert p dlg assert p dlg is kind of runtime class c http download dlg p dlg download thread return 0 afx_cdecl chttpdownloaddlg _downloadthread pparam dbgsetthreadname httpdownload initthreadlocale chttpdownloaddlg pdlg chttpdownloaddlg pparam pdlg pdlg iskindof runtime_class chttpdownloaddlg pdlg downloadthread void c http download dlg handle thread error with last error c string strid error dword dw last error form the error string to report c string s error if dw last error s error format t d dw last error else s error format t d get last error m serror format strid error s error delete the file being downloaded to if it is present m filetowrite close delete file m sfiletodownloadinto post message wm httpdownload thread finished 1 chttpdownloaddlg handlethreaderrorwithlasterror cstring striderror dwlasterror cstring serror dwlasterror serror _t dwlasterror serror _t getlasterror m_serror striderror serror m_filetowrite deletefile m_sfiletodownloadinto postmessage wm_httpdownload_thread_finished void c http download dlg handle thread error c string strid error m serror strid error post message wm httpdownload thread finished 1 chttpdownloaddlg handlethreaderror cstring striderror m_serror striderror postmessage wm_httpdownload_thread_finished void c http download dlg download thread encoding init create the internet session handle assert m hinternetsession null m hinternetsession internet open afx get app name internet open type preconfig null null 0 if m hinternetsession null trace t failed in call to internet open error d n get last error handle thread error with last error get res string ids httpdownload generic error return should we exit the thread if m babort post message wm httpdownload thread finished return setup the status callback function if internet set status callback m hinternetsession onstatuscallback internet invalid status callback trace t failed in call to internet set status callback error d n get last error handle thread error with last error get res string ids httpdownload generic error return should we exit the thread if m babort post message wm httpdownload thread finished return make the connection to the http server assert m hhttpconnection null if m susername get length elandal assumes sizeof void sizeof unsigned long m hhttpconnection internet connect m hinternetsession m sserver m nport m susername m spassword m dwservicetype 0 dword this else elandal assumes sizeof void sizeof unsigned long m hhttpconnection internet connect m hinternetsession m sserver m nport null null m dwservicetype 0 dword this if m hhttpconnection null trace t failed in call to internet connect error d n get last error handle thread error with last error get res string ids httpdownload fail connect server return should we exit the thread if m babort post message wm httpdownload thread finished return start the animation to signify that the download is taking place play animation issue the request to read the file lpctstr ppsz accept types 2 ppsz accept types 0 t we support accepting any mime file type since this is a simple download of a file ppsz accept types 1 null assert m hhttpfile null elandal assumes sizeof void sizeof unsigned long m hhttpfile http open request m hhttpconnection null m sobject null null ppsz accept types internet flag reload internet flag dont cache internet flag keep connection dword this if m hhttpfile null trace t failed in call to http open request error d n get last error handle thread error with last error get res string ids httpdownload fail connect server return should we exit the thread if m babort post message wm httpdownload thread finished return fill in what encoding we support http add request headers m hhttpfile accept encoding header dword 1l http addreq flag add label used to jump to if we need to resend the request resend issue the request bool b send http send request m hhttpfile null 0 null 0 if b send trace t failed in call to http send request error d n get last error handle thread error with last error get res string ids httpdownload fail connect server return check the http status code tchar sz status code 32 dword dw info size 32 if http query info m hhttpfile http query status code sz status code dw info size null trace t failed in call to http query info for http query status code error d n get last error handle thread error get res string ids httpdownload invalid server response return else long n status code ttol sz status code handle any authentication errors if n status code http status proxy auth req n status code http status denied we have to read all outstanding data on the internet handle before we can resubmit request just discard the data char sz data 51 dword dw size do internet read file m hhttpfile lpvoid sz data 50 dw size while dw size 0 bring up the standard authentication dialog if internet error dlg get safe hwnd m hhttpfile error internet incorrect password flags error ui filter for errors flags error ui flags generate data flags error ui flags change options null error internet force retry goto resend else if n status code http status ok trace t failed to retrieve a http 200 status status code d n n status code handle thread error with last error get res string ids httpdownload invalid http response n status code return check to see if any encodings are supported encoding query tchar sz content encoding 32 dword dw encode string size 32 if http query info m hhttpfile http query content encoding sz content encoding dw encode string size null if tcsicmp sz content encoding t gzip tcsicmp sz content encoding t x gzip b encoded withgzip true update the status control to reflect that we are getting the file information set status get res string ids httpdownload getting file information get the length of the file tchar sz content length 32 dw info size 32 dword dw file size 0 bool b got file size false if http query info m hhttpfile http query content length sz content length dw info size null set the progress control range b got file size true dw file size dword ttol sz content length set progress range dw file size update the status to say that we are now downloading the file set status get res string ids httpdownload retreiveing file now do the actual read of the file dword dw start ticks get tick count dword dw current ticks dw start ticks dword dw bytes read 0 char sz read buf 1024 dword dw bytes to read 1024 dword dw total bytes read 0 dword dw last total bytes 0 dword dw last percentage 0 prepare decoder do if internet read file m hhttpfile sz read buf dw bytes to read dw bytes read trace t failed in call to internet read file error d n get last error handle thread error with last error get res string ids httpdownload error readfile return else if dw bytes read m babort write the data to file try decode data m filetowrite sz read buf dw bytes read catch c file exception e trace t an exception occured while writing to the download file n handle thread error with last error get res string ids httpdownload error readfile e m loserror e delete clean up any encoding data before we return encoding clean up return end catch increment the total number of bytes read dw total bytes read dw bytes read update controls during transfer dw start ticks dw current ticks dw total bytes read dw last total bytes dw last percentage b got file size dw file size while dw bytes read m babort delete the file being downloaded to if it is present and the download was aborted m filetowrite close if m babort delete file m sfiletodownloadinto clean up any encoding data before we return encoding clean up we re finished post message wm httpdownload thread finished chttpdownloaddlg downloadthread encoding_init m_hinternetsession m_hinternetsession internetopen afxgetappname internet_open_type_preconfig m_hinternetsession _t internetopen getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_generic_error m_babort postmessage wm_httpdownload_thread_finished internetsetstatuscallback m_hinternetsession _onstatuscallback internet_invalid_status_callback _t internetsetstatuscallback getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_generic_error m_babort postmessage wm_httpdownload_thread_finished m_hhttpconnection m_susername getlength m_hhttpconnection internetconnect m_hinternetsession m_sserver m_nport m_susername m_spassword m_dwservicetype m_hhttpconnection internetconnect m_hinternetsession m_sserver m_nport m_dwservicetype m_hhttpconnection _t internetconnect getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_fail_connect_server m_babort postmessage wm_httpdownload_thread_finished playanimation ppszaccepttypes ppszaccepttypes _t ppszaccepttypes m_hhttpfile m_hhttpfile httpopenrequest m_hhttpconnection m_sobject ppszaccepttypes internet_flag_reload internet_flag_dont_cache internet_flag_keep_connection m_hhttpfile _t httpopenrequest getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_fail_connect_server m_babort postmessage wm_httpdownload_thread_finished httpaddrequestheaders m_hhttpfile accept_encoding_header http_addreq_flag_add bsend httpsendrequest m_hhttpfile bsend _t httpsendrequest getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_fail_connect_server szstatuscode dwinfosize httpqueryinfo m_hhttpfile http_query_status_code szstatuscode dwinfosize _t httpqueryinfo getlasterror handlethreaderror getresstring ids_httpdownload_invalid_server_response nstatuscode _ttol szstatuscode nstatuscode http_status_proxy_auth_req nstatuscode http_status_denied szdata dwsize internetreadfile m_hhttpfile szdata dwsize dwsize interneterrordlg getsafehwnd m_hhttpfile error_internet_incorrect_password flags_error_ui_filter_for_errors flags_error_ui_flags_generate_data flags_error_ui_flags_change_options error_internet_force_retry nstatuscode http_status_ok _t nstatuscode handlethreaderrorwithlasterror getresstring ids_httpdownload_invalid_http_response nstatuscode encoding_query szcontentencoding dwencodestringsize httpqueryinfo m_hhttpfile http_query_content_encoding szcontentencoding dwencodestringsize _tcsicmp szcontentencoding _t _tcsicmp szcontentencoding _t bencodedwithgzip setstatus getresstring ids_httpdownload_getting_file_information szcontentlength dwinfosize dwfilesize bgotfilesize httpqueryinfo m_hhttpfile http_query_content_length szcontentlength dwinfosize bgotfilesize dwfilesize _ttol szcontentlength setprogressrange dwfilesize setstatus getresstring ids_httpdownload_retreiveing_file dwstartticks gettickcount dwcurrentticks dwstartticks dwbytesread szreadbuf dwbytestoread dwtotalbytesread dwlasttotalbytes dwlastpercentage prepare_decoder internetreadfile m_hhttpfile szreadbuf dwbytestoread dwbytesread _t internetreadfile getlasterror handlethreaderrorwithlasterror getresstring ids_httpdownload_error_readfile dwbytesread m_babort decode_data m_filetowrite szreadbuf dwbytesread cfileexception _t handlethreaderrorwithlasterror getresstring ids_httpdownload_error_readfile m_loserror encoding_clean_up end_catch dwtotalbytesread dwbytesread updatecontrolsduringtransfer dwstartticks dwcurrentticks dwtotalbytesread dwlasttotalbytes dwlastpercentage bgotfilesize dwfilesize dwbytesread m_babort m_filetowrite m_babort deletefile m_sfiletodownloadinto encoding_clean_up postmessage wm_httpdownload_thread_finished void c http download dlg set percentage int n percentage change the caption text c string s percentage s percentage format t d n percentage c string s caption s caption format get res string ids httpdownload percentage s percentage m sfilename set window text s caption chttpdownloaddlg setpercentage npercentage cstring spercentage spercentage _t npercentage cstring scaption scaption getresstring ids_httpdownload_percentage spercentage m_sfilename setwindowtext scaption void c http download dlg set time left dword dw seconds left dword dw bytes read dword dw file size c string s of s of format get res string ids httpdownload of cast itox bytes uint64 dw bytes read false false cast itox bytes uint64 dw file size false false c string s time left s time left format get res string ids httpdownload timeleft cast seconds tohm dw seconds left s of m ctrltimeleft set window text s time left chttpdownloaddlg settimeleft dwsecondsleft dwbytesread dwfilesize cstring sof sof getresstring ids_httpdownload_of castitoxbytes dwbytesread castitoxbytes dwfilesize cstring stimeleft stimeleft getresstring ids_httpdownload_timeleft castsecondstohm dwsecondsleft sof m_ctrltimeleft setwindowtext stimeleft void c http download dlg set progress range dword dw file size m ctrlprogress set range 0 short dw file size 512 1024 chttpdownloaddlg setprogressrange dwfilesize m_ctrlprogress setrange dwfilesize void c http download dlg set status const c string s caption m ctrlstatus set window text s caption chttpdownloaddlg setstatus cstring scaption m_ctrlstatus setwindowtext scaption void c http download dlg set status c string nid const c string lpsz1 c string s status s status format nid lpsz1 set status s status chttpdownloaddlg setstatus cstring cstring cstring sstatus sstatus setstatus sstatus void c http download dlg set transfer rate double kb per second c string s rate s rate format t s cast itox bytes kb per second true true m ctrltransferrate set window text s rate chttpdownloaddlg settransferrate kbpersecond cstring srate srate _t castitoxbytes kbpersecond m_ctrltransferrate setwindowtext srate void c http download dlg play animation m ctrlanimate play 0 uint 1 uint 1 chttpdownloaddlg playanimation m_ctrlanimate void c http download dlg set progress dword dw bytes read m ctrlprogress set pos dw bytes read 1024 chttpdownloaddlg setprogress dwbytesread m_ctrlprogress setpos dwbytesread dword dw last percentage bool b got file size dword dw file size if b got file size update the percentage downloaded in the caption dword dw percentage dword dw total bytes read 100 0 dw file size if dw percentage dw last percentage set percentage dw percentage dw last percentage dw percentage update the progress control bar set progress dw total bytes read update the transfer rate amd estimated time left every second dword dw now ticks get tick count dword dw time taken dw now ticks dw current ticks if dw time taken 1000 double kb per second double dw total bytes read double dw last total bytes double dw time taken set transfer rate kb per second setup for the next time around the loop dw current ticks dw now ticks dw last total bytes dw total bytes read if b got file size update the estimated time left if dw total bytes read dword dw seconds left dword double dw now ticks dw start ticks dw total bytes read dw file size dw total bytes read 1000 set time left dw seconds left dw total bytes read dw file size dwlastpercentage bgotfilesize dwfilesize bgotfilesize dwpercentage dwtotalbytesread dwfilesize dwpercentage dwlastpercentage setpercentage dwpercentage dwlastpercentage dwpercentage setprogress dwtotalbytesread dwnowticks gettickcount dwtimetaken dwnowticks dwcurrentticks dwtimetaken kbpersecond dwtotalbytesread dwlasttotalbytes dwtimetaken settransferrate kbpersecond dwcurrentticks dwnowticks dwlasttotalbytes dwtotalbytesread bgotfilesize dwtotalbytesread dwsecondsleft dwnowticks dwstartticks dwtotalbytesread dwfilesize dwtotalbytesread settimeleft dwsecondsleft dwtotalbytesread dwfilesize c mule status bar ctrl c mule status bar ctrl cmulestatusbarctrl cmulestatusbarctrl c mule status bar ctrl c mule status bar ctrl cmulestatusbarctrl cmulestatusbarctrl void c mule status bar ctrl init void enable tool tips cmulestatusbarctrl enabletooltips int c mule status bar ctrl get pane at position c point point const c rect rect int n parts get parts 0 null for int i 0 i n parts i get rect i rect if rect pt in rect point return i return 1 cmulestatusbarctrl getpaneatposition cpoint crect nparts getparts nparts getrect ptinrect c string c mule status bar ctrl get pane tool tip text e status bar pane i pane const c string str text switch i pane case s bar connected if the app serverconnect the app serverconnect is connected c server cur server the app serverconnect get current server c server srv cur server the app serverlist get server by address cur server get address cur server get port null if srv can t add more info than just the server name unfortunately the mfc tooltip which we use here does not show more than one line of text str text t ed2k get res string ids server t srv get list name str text append format t s s get formatedu int srv get users get res string ids uusers break return str text cstring cmulestatusbarctrl getpanetooltiptext estatusbarpane ipane cstring strtext ipane sbarconnected theapp theapp isconnected cserver cur_server theapp getcurrentserver cserver cur_server theapp getserverbyaddress cur_server getaddress cur_server getport strtext _t getresstring ids_server _t getlistname strtext appendformat _t getformateduint getusers getresstring ids_uusers strtext int c mule status bar ctrl on tool hit test c point point toolinfo pti const int i hit c wnd on tool hit test point pti if i hit 1 pti null pti cb size sizeof afx oldtoolinfo int i pane get pane at position point if i pane 1 c string str tool tip text get pane tool tip text e status bar pane i pane if str tool tip text is empty pti hwnd m hwnd pti u id uint ptr i pane pti u flags ttf idishwnd pti u flags ttf notbutton ttf alwaystip pti lpsz text tcsdup str tool tip text gets freed by mfc get rect i pane pti rect i hit i pane return i hit cmulestatusbarctrl ontoolhittest cpoint ihit cwnd ontoolhittest ihit cbsize afx_oldtoolinfo ipane getpaneatposition ipane cstring strtooltiptext getpanetooltiptext estatusbarpane ipane strtooltiptext isempty m_hwnd uid uint_ptr ipane uflags ttf_idishwnd uflags ttf_notbutton ttf_alwaystip lpsztext _tcsdup strtooltiptext getrect ipane ihit ipane ihit void c mule status bar ctrl onl button dbl clk uint n flags c point point int i pane get pane at position point switch i pane case s bar log afx message box t e mule get res string ids sv log t n n get text s bar log break case s bar users the app emuledlg serverwnd show network info break case s bar up down the app emuledlg set active dialog the app emuledlg statisticswnd break case s bar connected the app emuledlg serverwnd show network info break case s bar chat msg the app emuledlg set active dialog the app emuledlg chatwnd break cmulestatusbarctrl onlbuttondblclk nflags cpoint ipane getpaneatposition ipane sbarlog afxmessagebox _t emule getresstring ids_sv_log _t gettext sbarlog sbarusers theapp shownetworkinfo sbarupdown theapp setactivedialog theapp sbarconnected theapp shownetworkinfo sbarchatmsg theapp setactivedialog theapp c network info dlg c network info dlg c wnd p parent null c resizable dialog c network info dlg idd p parent cnetworkinfodlg cnetworkinfodlg cwnd pparent cresizabledialog cnetworkinfodlg pparent c network info dlg c network info dlg cnetworkinfodlg cnetworkinfodlg bool c network info dlg on init dialog replace rich edit ctrl get dlg item idc network info this get dlg item idc network info label get font c resizable dialog on init dialog init window styles this add anchor idc network info top left bottom right add anchor idok bottom right enable save restore pref ini section set window text get res string ids network info set dlg item text idc network info label get res string ids network info m info send message em setmargins ec leftmargin ec rightmargin makelong 3 3 m info set autourl detect m info set event mask m info get event mask enm link charformat cf def 0 charformat cf bold 0 paraformat pf 0 pf cb size sizeof pf if m info get para format pf pf dw mask pfm tabstops pf c tab count 4 pf rgx tabs 0 900 pf rgx tabs 1 1000 pf rgx tabs 2 1100 pf rgx tabs 3 1200 m info set para format pf cf def cb size sizeof cf def if m info get selection char format cf def cf bold cf def cf bold dw mask cfm bold cf bold dw effects cfe bold create network info m info cf def cf bold true return true cnetworkinfodlg oninitdialog replacericheditctrl getdlgitem idc_network_info getdlgitem idc_network_info_label getfont cresizabledialog oninitdialog initwindowstyles addanchor idc_network_info top_left bottom_right addanchor bottom_right enablesaverestore pref_ini_section setwindowtext getresstring ids_network_info setdlgitemtext idc_network_info_label getresstring ids_network_info m_info sendmessage em_setmargins ec_leftmargin ec_rightmargin m_info setautourldetect m_info seteventmask m_info geteventmask enm_link cfdef cfbold cbsize m_info getparaformat dwmask pfm_tabstops ctabcount rgxtabs rgxtabs rgxtabs rgxtabs m_info setparaformat cfdef cbsize cfdef m_info getselectioncharformat cfdef cfbold cfdef cfbold dwmask cfm_bold cfbold dweffects cfe_bold createnetworkinfo m_info cfdef cfbold void c network info dlg do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc network info m info cnetworkinfodlg dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_network_info m_info lpctstr sz display name null lpctstr sz content type t application octet stream uint ui codepage 0 if p raw data return false c auto ptr c mime body part sp raw attach c mime raw attachment ex p raw attach atltry sp raw attach attach p raw attach new c mime raw attachment ex if sp raw attach return false bool b ret p raw attach initialize p raw data dw data length b copy data sz display name m spmultilanguage ui codepage if b ret b ret p raw attach set encoding scheme n encoding scheme if b ret b ret p raw attach set content type sz content type atltry if b ret if m bodyparts add tail sp raw attach b ret false atlcatchall b ret false return b ret szdisplayname szcontenttype _t uicodepage prawdata cautoptr cmimebodypart sprawattach cmimerawattachmentex prawattach sprawattach prawattach cmimerawattachmentex sprawattach bret prawattach prawdata dwdatalength bcopydata szdisplayname m_spmultilanguage uicodepage bret bret prawattach setencodingscheme nencodingscheme bret bret prawattach setcontenttype szcontenttype _atltry bret m_bodyparts addtail sprawattach bret _atlcatchall bret bret c notifier mail thread c notifier mail thread cnotifiermailthread cnotifiermailthread c notifier mail thread c notifier mail thread cnotifiermailthread cnotifiermailthread bool c notifier mail thread init instance dbg set thread name notifier mail thread if the app emuledlg null the app emuledlg is running sm critsect lock init thread locale co initialize null bool b have valid msg false uint u code page cp utf8 c byte array a encrypted body if m strencryptcertname is empty c com ptr i multi language sp multi language hresult hr sp multi language co create instance uuidof c multi language if hr s ok c stringa str mime messagea str mime messagea content type text plain r n tformat flowed char sz charset atl max enc charset length if atl ver 0x0700 if atl mime charset from code page sz charset u code page sp multi language else if atl mime charset from code page sz charset u code page sp multi language arrsize sz charset endif str mime messagea append format r n tcharset s sz charset str mime messagea r n str mime messagea content transfer encoding 8bit r n str mime messagea r n uint n mime text len 0 lpstr psz mime text null if atl mime convert string sp multi language u code page m strbody psz mime text n mime text len str mime messagea append psz mime text n mime text len if encrypt str mime messagea a encrypted body m strencryptcertname b have valid msg a encrypted body get size 0 c heap ptr char p mime text p mime text attach psz mime text else debug log warning log dontnotify t e mail notification failed to instantiate i multi language s get error message hr 1 else b have valid msg m strbody is empty if b have valid msg csmtp connection smtp if smtp connect m strhostname if the app emuledlg null the app emuledlg is running c mime message ex msg msg set sender name t e mule msg set sender m strsender msg add recipient m strrecipient msg set subject m strsubject if a encrypted body get size 0 msg attach raw void a encrypted body get data a encrypted body get size atlsmtp base64 encode true t smime p7m t application x pkcs7 mime r n tformat flowed r n tsmime type enveloped data else msg add text m strbody 1 1 u code page if smtp send message msg can t use get last error here debug log warning log dontnotify t e mail notification failed to send e mail to s m strrecipient else can t use get last error here debug log warning log dontnotify t e mail notification failed to connect to smtp server s m strhostname co uninitialize sm critsect unlock return false cnotifiermailthread initinstance dbgsetthreadname notifiermailthread theapp theapp isrunning sm_critsect initthreadlocale coinitialize bhavevalidmsg ucodepage cp_utf8 cbytearray aencryptedbody m_strencryptcertname isempty ccomptr imultilanguage spmultilanguage spmultilanguage cocreateinstance __uuidof cmultilanguage s_ok cstringa strmimemessagea strmimemessagea szcharset atl_max_enc_charset_length _atl_ver atlmimecharsetfromcodepage szcharset ucodepage spmultilanguage atlmimecharsetfromcodepage szcharset ucodepage spmultilanguage szcharset strmimemessagea appendformat szcharset strmimemessagea strmimemessagea strmimemessagea nmimetextlen pszmimetext atlmimeconvertstring spmultilanguage ucodepage m_strbody pszmimetext nmimetextlen strmimemessagea pszmimetext nmimetextlen strmimemessagea aencryptedbody m_strencryptcertname bhavevalidmsg aencryptedbody getsize cheapptr pmimetext pmimetext pszmimetext debuglogwarning log_dontnotify _t imultilanguage geterrormessage bhavevalidmsg m_strbody isempty bhavevalidmsg csmtpconnection m_strhostname theapp theapp isrunning cmimemessageex setsendername _t emule setsender m_strsender addrecipient m_strrecipient setsubject m_strsubject aencryptedbody getsize attachraw aencryptedbody getdata aencryptedbody getsize atlsmtp_base64_encode _t _t addtext m_strbody ucodepage sendmessage getlasterror debuglogwarning log_dontnotify _t m_strrecipient getlasterror debuglogwarning log_dontnotify _t m_strhostname couninitialize sm_critsect cmd4 cmd4 reset cmd4 cmd4 reset magic bool cmd4 verify implementation if md4 asm m ncount0 offsetof cmd4 m ncount 0 md4 asm m ncount1 offsetof cmd4 m ncount 1 assert 0 return false if md4 asm m nstate0 offsetof cmd4 m nstate 0 md4 asm m nstate1 offsetof cmd4 m nstate 1 md4 asm m nstate2 offsetof cmd4 m nstate 2 md4 asm m nstate3 offsetof cmd4 m nstate 3 assert 0 return false if md4 asm m nbuffer offsetof cmd4 m nbuffer assert 0 return false return true verifyimplementation md4_asm_m_ncount0 m_ncount md4_asm_m_ncount1 m_ncount md4_asm_m_nstate0 m_nstate md4_asm_m_nstate1 m_nstate md4_asm_m_nstate2 m_nstate md4_asm_m_nstate3 m_nstate md4_asm_m_nbuffer m_nbuffer void cmd4 reset clear counts m ncount 0 m ncount 1 0 load magic initialization constants m nstate 0 0x67452301 m nstate 1 0xefcdab89 m nstate 2 0x98badcfe m nstate 3 0x10325476 m_ncount m_ncount m_nstate m_nstate m_nstate m_nstate void cmd4 add lpcvoid p data dword n length md4 add p5 this p data n length pdata nlength md4_add_p5 pdata nlength void cmd4 finish unsigned int bits 2 index 0 save number of bits bits 1 m ncount 1 3 m ncount 0 29 bits 0 m ncount 0 3 pad out to 56 mod 64 index unsigned int m ncount 0 0x3f md4 add p5 this md4 padding index 56 56 index 120 index append length before padding md4 add p5 this bits 8 m_ncount m_ncount m_ncount m_ncount md4_add_p5 md4_padding md4_add_p5 void cmd4 get hash md4 p hash memcpy p hash b m nstate 16 gethash phash phash m_nstate e result c sec run as user restart secure e result res if the prefs is prefering restricted over user res prepare user if res res ok the app queue log line false get res string ids rau running emuleaccount return res ok else if res res ok need restart res restart as user if res res failed return res res restart as restricted if res res ok the app queue log line false get res string ids runningrestricted return res eresult csecrunasuser restartsecure eresult theprefs ispreferingrestrictedoveruser prepareuser res_ok theapp queuelogline getresstring ids_rau_running res_ok res_ok_need_restart restartasuser res_failed restartasrestricted res_ok theapp queuelogline getresstring ids_runningrestricted e result c sec run as user prepare user uses conversion co initialize null bool b result false if loadapi return res failed try ia ds container ptr p users try ia ds winnt system info ptr pn tsys if co create instance clsid winntsysteminfo null clsctx inproc server iid iadswinntsysteminfo void pn tsys s ok throw c string t failed to create ia ds winnt system info check if we are already running on our e mule account todo check if the current account is an administrator c combstr bstr user name pn tsys get username bstr user name m strcurrentuser bstr user name if m strcurrentuser emuleaccountw m brunningasemule true throw c string t already running as emule secure account everything is fine c combstr bstr comp name pn tsys get computername bstr comp name c stringw cscomp name bstr comp name c combstr bstr domain name pn tsys get domainname bstr domain name m strdomain bstr domain name ads path format l winnt s computer cscomp name if succeeded a ds get object ads path alloc sys string iid iadscontainer void p users throw c string t failed a ds get object i enumvariant ptr p enum a ds build enumerator p users p enum ia ds user ptr p child variant t v child while a ds enumerate next p enum 1 v child null s ok if v child pdisp val query interface iid iadsuser void p child s ok continue if the object in the container is user then get properties c combstr bstr name p child get name bstr name c stringw cs name bstr name find the emule user account if possible if cs name emuleaccountw account found set new random password and save it m strpassword create randompw if succeeded p child set password m strpassword alloc sys string throw c string t failed to set password b result true break catch c string error clean up and abort the app queue debug log line false t run as unpriveleged user exception while preparing user account s error co uninitialize if m brunningasemule return res ok else return res failed if b result create emule user p users b result set directory permissions catch clean up and abort the app queue debug log line false t run as unpriveleged user unexpected fatal error while preparing user account co uninitialize return res failed co uninitialize freeapi if b result return res ok need restart else return res failed eresult csecrunasuser prepareuser uses_conversion coinitialize bresult res_failed iadscontainerptr pusers iadswinntsysteminfoptr pntsys cocreateinstance clsid_winntsysteminfo clsctx_inproc_server iid_iadswinntsysteminfo pntsys s_ok cstring _t iadswinntsysteminfo emule ccombstr bstrusername pntsys get_username bstrusername m_strcurrentuser bstrusername m_strcurrentuser m_brunningasemule cstring _t emule_secure ccombstr bstrcompname pntsys get_computername bstrcompname cstringw cscompname bstrcompname ccombstr bstrdomainname pntsys get_domainname bstrdomainname m_strdomain bstrdomainname adspath cscompname adsgetobject adspath allocsysstring iid_iadscontainer pusers cstring _t adsgetobject ienumvariantptr penum adsbuildenumerator pusers penum iadsuserptr pchild _variant_t vchild adsenumeratenext penum vchild s_ok vchild pdispval queryinterface iid_iadsuser pchild s_ok ccombstr bstrname pchild get_name bstrname cstringw csname bstrname csname m_strpassword createrandompw pchild setpassword m_strpassword allocsysstring cstring _t bresult cstring theapp queuedebuglogline _t couninitialize m_brunningasemule res_ok res_failed bresult createemuleuser pusers bresult setdirectorypermissions theapp queuedebuglogline _t couninitialize res_failed couninitialize bresult res_ok_need_restart res_failed e result c sec run as user restart as user uses conversion if m brunningrestricted m brunningasemule return res ok if loadapi return res failed assert m strpassword is empty bool b result try process information process info 0 tchar sz app path max path get module file name null sz app path max path c string str app name str app name format t s sz app path startupinfow start inf 0 start inf cb sizeof start inf start inf dw flags startf useshowwindow start inf w show window sw normal remove the current mutex so that the restart emule can create its own without problems in the rare case create process with logonw fails this will allow mult instances but if that function fails we have other problems anyway close handle the app m hmutexoneinstance b result create process with logonw emuleaccountw m strdomain m strpassword logon with profile null lpwstr t2cw str app name 0 null null start inf process info close handle process info h process close handle process info h thread catch the app queue debug log line false t run as unpriveleged user error unexpected exception while loading advapi32 dll freeapi return res failed freeapi if b result the app queue debug log line false t run as unpriveleged user error failed to restart e mule as different user error code i get last error if b result return res ok need restart else return res failed eresult csecrunasuser restartasuser uses_conversion m_brunningrestricted m_brunningasemule res_ok res_failed m_strpassword isempty bresult process_information processinfo szapppath max_path getmodulefilename szapppath max_path cstring strappname strappname _t szapppath startinf startinf startinf startinf dwflags startf_useshowwindow startinf wshowwindow sw_normal createprocesswithlogonw closehandle theapp m_hmutexoneinstance bresult createprocesswithlogonw m_strdomain m_strpassword logon_with_profile strappname startinf processinfo closehandle processinfo hprocess closehandle processinfo hthread theapp queuedebuglogline _t res_failed bresult theapp queuedebuglogline _t emule getlasterror bresult res_ok_need_restart res_failed e result c sec run as user restart as restricted if m brunningrestricted m brunningasemule return res ok if loadapi return res failed handle h process token null handle h restricted token null ptoken user pstruct user token null try get our access token from the process if open process token get current process token duplicate token assign primary token read h process token throw c string t failed to retrieve access token from process there is no easy way to check if we have already restircted token when not using the restricted sid list so just check if we set the sandbox inert flag and hope noone else did which isunlikely tho because afaik you would only set it when using create restircted token dword dw len 0 dword dw inert flag if get token information h process token token sand box inert dw inert flag sizeof dw inert flag dw len throw c string t failed to flag status from access token if dw inert flag 0 m brunningrestricted true throw c string t already using a restricted token it seems everything is fine get the user account sid to disable it in our new token dw len 0 while get token information h process token token user pstruct user token dw len dw len if get last error error insufficient buffer pstruct user token null pstruct user token ptoken user heap alloc get process heap heap zero memory dw len continue throw c string t failed to retrieve usersid from access token disabling our primary token would make sense from an security pov but this would cause file acces conflicts in the default settings since we cannot access files we created ourself if they don t have the write flag for the group users so it stays enabled for now and we only reduce privileges create the new token if create restricted token h process token disable max privilege sandbox inert 0 disabled pstruct user token user 0 null 0 null h restricted token throw c string t failed to create restricted token do the starting job process information process info 0 tchar sz app path max path get module file name null sz app path max path c string str app name str app name format t s sz app path startupinfo start inf 0 start inf cb sizeof start inf start inf dw flags startf useshowwindow start inf w show window sw normal remove the current mutex so that the restart emule can create its own without problems in the rare case create process with logonw fails this will allow mult instances but if that function fails we have other problems anyway close handle the app m hmutexoneinstance if create process as user h restricted token null str app name get buffer null null false normal priority class null null start inf process info c string e get error message get last error e 0 throw c string t create process as user failed str app name release buffer close handle process info h process close handle process info h thread cleanup heap free get process heap 0 lpvoid pstruct user token pstruct user token null close handle h restricted token close handle h process token catch c string str error if h process token null close handle h process token if h restricted token null close handle h restricted token if pstruct user token null heap free get process heap 0 lpvoid pstruct user token the app queue debug log line false t secure shell execute exception s str error if m brunningrestricted return res ok else return res failed return res ok need restart eresult csecrunasuser restartasrestricted m_brunningrestricted m_brunningasemule res_ok res_failed hprocesstoken hrestrictedtoken ptoken_user pstructusertoken openprocesstoken getcurrentprocess token_duplicate token_assign_primary token_read hprocesstoken cstring _t sandbox_inert createrestirctedtoken dwlen dwinertflag gettokeninformation hprocesstoken tokensandboxinert dwinertflag dwinertflag dwlen cstring _t accesstoken dwinertflag m_brunningrestricted cstring _t dwlen gettokeninformation hprocesstoken tokenuser pstructusertoken dwlen dwlen getlasterror error_insufficient_buffer pstructusertoken pstructusertoken ptoken_user heapalloc getprocessheap heap_zero_memory dwlen cstring _t accesstoken createrestrictedtoken hprocesstoken disable_max_privilege sandbox_inert pstructusertoken hrestrictedtoken cstring _t process_information processinfo szapppath max_path getmodulefilename szapppath max_path cstring strappname strappname _t szapppath startinf startinf startinf startinf dwflags startf_useshowwindow startinf wshowwindow sw_normal createprocesswithlogonw closehandle theapp m_hmutexoneinstance createprocessasuser hrestrictedtoken strappname getbuffer normal_priority_class startinf processinfo cstring geterrormessage getlasterror cstring _t createprocessasuser strappname releasebuffer closehandle processinfo hprocess closehandle processinfo hthread heapfree getprocessheap pstructusertoken pstructusertoken closehandle hrestrictedtoken closehandle hprocesstoken cstring strerror hprocesstoken closehandle hprocesstoken hrestrictedtoken closehandle hrestrictedtoken pstructusertoken heapfree getprocessheap pstructusertoken theapp queuedebuglogline _t secureshellexecute strerror m_brunningrestricted res_ok res_failed res_ok_need_restart bool c sec run as user set directory permissions define fullaccess ads right generic all shared files list read permission only we odnt check for success here for emule will also run if one dir fails for some reason if there is a dir which is also an incoming dir rights will be overwritten below for position pos the prefs shareddir list get head position pos 0 verify set object permission the prefs shareddir list get next pos dword ads right generic read set special permission for emule account on needed folders bool b succeeded true b succeeded b succeeded set object permission the prefs get app dir fullaccess b succeeded b succeeded set object permission the prefs get config dir fullaccess b succeeded b succeeded set object permission the prefs get incoming dir fullaccess for int i 0 i the prefs get temp dir count i b succeeded b succeeded set object permission the prefs get temp dir i fullaccess int c cats the prefs get cat count for int i 0 i c cats i if c string the prefs get cat path i is empty b succeeded b succeeded set object permission the prefs get cat path i fullaccess if b succeeded the app queue debug log line false t run as unpriveleged user error failed to set directoy permissions return b succeeded csecrunasuser setdirectorypermissions ads_right_generic_all theprefs shareddir_list getheadposition setobjectpermission theprefs shareddir_list getnext ads_right_generic_read bsucceeded bsucceeded bsucceeded setobjectpermission theprefs getappdir bsucceeded bsucceeded setobjectpermission theprefs getconfigdir bsucceeded bsucceeded setobjectpermission theprefs getincomingdir theprefs gettempdircount bsucceeded bsucceeded setobjectpermission theprefs gettempdir ccats theprefs getcatcount ccats cstring theprefs getcatpath isempty bsucceeded bsucceeded setobjectpermission theprefs getcatpath bsucceeded theapp queuedebuglogline _t bsucceeded bool c sec run as user create emule user ia ds container ptr p users i dispatch ptr p disp null if succeeded p users create l user c string emuleaccount alloc sys string p disp return false ia ds user ptr p user if succeeded p disp query interface p user return false variant bool b account disabled false variant bool b is locked false variant bool b pw required true p user put accountdisabled b account disabled p user put isaccountlocked b is locked p user put passwordrequired b pw required p user put description c string t account used to run e mule with additional security alloc sys string p user set info m strpassword create randompw if succeeded p user set password m strpassword alloc sys string return false return true csecrunasuser createemuleuser iadscontainerptr pusers idispatchptr pdisp pusers cstring allocsysstring pdisp iadsuserptr puser pdisp queryinterface puser variant_bool baccountdisabled variant_bool bislocked variant_bool bpwrequired puser put_accountdisabled baccountdisabled puser put_isaccountlocked bislocked puser put_passwordrequired bpwrequired puser put_description cstring _t emule allocsysstring puser setinfo m_strpassword createrandompw puser setpassword m_strpassword allocsysstring bool c sec run as user set object permission c string str dir file dword l granted access uses conversion if m hadvapi32 dll assert false return false if str dir file is empty return true sid name use snu type tchar sz domain null lpvoid p usersid null pacl p newacl null psecurity descriptor psd null bool fapi success try get user sid dword cb domain 0 dword cb usersid 0 fapi success lookup account name null emuleaccount p usersid cb usersid sz domain cb domain snu type if fapi success get last error error insufficient buffer throw c string t run as unpriveleged user error lookup account name failed p usersid m heap alloc cb usersid if p usersid throw c string t run as unpriveleged user error allocating memory failed sz domain tchar m heap alloc cb domain sizeof tchar if sz domain throw c string t run as unpriveleged user error allocating memory failed fapi success lookup account name null emuleaccount p usersid cb usersid sz domain cb domain snu type if fapi success throw c string t run as unpriveleged user error lookup account name 2 failed if c stringw t2w sz domain m strdomain throw c string t run as unpriveleged user logical error domainname mismatch get old acl pacl p oldacl null fapi success get named security info str dir file get buffer se file object dacl security information null null p oldacl null psd str dir file release buffer if fapi success error success throw c string t run as unpriveleged user error get named security info failed calculate size for new acl acl size information acl info acl info ace count 0 assume null dacl acl info acl bytes free 0 acl info acl bytes in use sizeof acl if p oldacl null get acl information p oldacl acl info sizeof acl size information acl size information throw c string t run as unpriveleged user error get acl information failed create new acl dword cb newacl acl info acl bytes in use sizeof access allowed ace get length sid p usersid sizeof dword p newacl pacl m heap alloc cb newacl if p newacl throw c string t run as unpriveleged user error allocating memory failed if initialize acl p newacl cb newacl acl revision2 throw c string t run as unpriveleged user error allocating memory failed copy the entries form the old acl into the new one and enter a new ace in the right order uint32 new ace index 0 uint32 current ace index 0 if acl info ace count for current ace index 0 current ace index acl info ace count current ace index lpvoid p temp ace null if get ace p oldacl current ace index p temp ace throw c string t run as unpriveleged user error get ace failed if access allowed ace p temp ace header ace flags inherited ace break no multiple entries if equal sid p usersid access allowed ace p temp ace sid start continue if add ace p newacl acl revision maxdword p temp ace pace header p temp ace ace size throw c string t run as unpriveleged user error add ace 1 failed new ace index here we add the actually entry if add access allowed ace ex p newacl acl revision2 container inherit ace object inherit ace l granted access p usersid throw c string t run as unpriveleged user error add access allowed ace ex failed copy the rest if acl info ace count for current ace index acl info ace count current ace index lpvoid p temp ace null if get ace p oldacl current ace index p temp ace throw c string t run as unpriveleged user error get ace 2 failed if add ace p newacl acl revision maxdword p temp ace pace header p temp ace ace size throw c string t run as unpriveleged user error add ace 2 failed fapi success set named security info str dir file get buffer se file object dacl security information null null p newacl null str dir file release buffer if fapi success error success throw c string t run as unpriveleged user error set named security info failed fapi success true catch c string error fapi success false the app queue debug log line false error clean up if p usersid null m heap free p usersid if sz domain null m heap free sz domain if p newacl null m heap free p newacl if psd null local free psd finished return fapi success false csecrunasuser setobjectpermission cstring strdirfile lgrantedaccess uses_conversion m_hadvapi32_dll strdirfile isempty sid_name_use snutype szdomain pusersid pnewacl psecurity_descriptor fapisuccess cbdomain cbusersid fapisuccess lookupaccountname pusersid cbusersid szdomain cbdomain snutype fapisuccess getlasterror error_insufficient_buffer cstring _t lookupaccountname pusersid mheapalloc cbusersid pusersid cstring _t szdomain mheapalloc cbdomain szdomain cstring _t fapisuccess lookupaccountname pusersid cbusersid szdomain cbdomain snutype fapisuccess cstring _t lookupaccountname cstringw szdomain m_strdomain cstring _t poldacl fapisuccess getnamedsecurityinfo strdirfile getbuffer se_file_object dacl_security_information poldacl strdirfile releasebuffer fapisuccess error_success cstring _t getnamedsecurityinfo acl_size_information aclinfo aclinfo acecount aclinfo aclbytesfree aclinfo aclbytesinuse poldacl getaclinformation poldacl aclinfo acl_size_information aclsizeinformation cstring _t getaclinformation cbnewacl aclinfo aclbytesinuse access_allowed_ace getlengthsid pusersid pnewacl mheapalloc cbnewacl pnewacl cstring _t initializeacl pnewacl cbnewacl acl_revision2 cstring _t newaceindex currentaceindex aclinfo acecount currentaceindex currentaceindex aclinfo acecount currentaceindex ptempace getace poldacl currentaceindex ptempace cstring _t getace access_allowed_ace ptempace aceflags inherited_ace equalsid pusersid access_allowed_ace ptempace sidstart addace pnewacl acl_revision ptempace pace_header ptempace acesize cstring _t addace newaceindex addaccessallowedaceex pnewacl acl_revision2 container_inherit_ace object_inherit_ace lgrantedaccess pusersid cstring _t addaccessallowedaceex aclinfo acecount currentaceindex aclinfo acecount currentaceindex ptempace getace poldacl currentaceindex ptempace cstring _t getace addace pnewacl acl_revision ptempace pace_header ptempace acesize cstring _t addace fapisuccess setnamedsecurityinfo strdirfile getbuffer se_file_object dacl_security_information pnewacl strdirfile releasebuffer fapisuccess error_success cstring _t setnamedsecurityinfo fapisuccess cstring fapisuccess theapp queuedebuglogline pusersid mheapfree pusersid szdomain mheapfree szdomain pnewacl mheapfree pnewacl localfree fapisuccess bool c sec run as user loadapi if m hadvapi32 dll 0 m hadvapi32 dll load library t advapi32 dll if m hactiveds dll 0 m hactiveds dll load library t activeds if m hadvapi32 dll 0 add debug log line false t failed to load advapi32 dll return false if m hactiveds dll 0 add debug log line false t failed to load activeds dll return false bool b succeeded true b succeeded b succeeded create process with logonw t create process with logonw get proc address m hadvapi32 dll create process with logonw null b succeeded b succeeded get named security info t get named security info get proc address m hadvapi32 dll twinapi get named security info null b succeeded b succeeded set named security info t set named security info get proc address m hadvapi32 dll twinapi set named security info null b succeeded b succeeded add access allowed ace ex t add access allowed ace ex get proc address m hadvapi32 dll add access allowed ace ex null probably these functions do not need to bel loaded dynamically but just to be sure b succeeded b succeeded lookup account name t lookup account name get proc address m hadvapi32 dll twinapi lookup account name null b succeeded b succeeded get acl information t get acl information get proc address m hadvapi32 dll get acl information null b succeeded b succeeded initialize acl t initialize acl get proc address m hadvapi32 dll initialize acl null b succeeded b succeeded get ace t get ace get proc address m hadvapi32 dll get ace null b succeeded b succeeded add ace t add ace get proc address m hadvapi32 dll add ace null b succeeded b succeeded equal sid t equal sid get proc address m hadvapi32 dll equal sid null b succeeded b succeeded get length sid t get length sid get proc address m hadvapi32 dll get length sid null for secure shell execute b succeeded b succeeded open process token t open process token get proc address m hadvapi32 dll open process token null b succeeded b succeeded get token information t get token information get proc address m hadvapi32 dll get token information null b succeeded b succeeded create restricted token t create restricted token get proc address m hadvapi32 dll create restricted token null b succeeded b succeeded create process as user t create process as user get proc address m hadvapi32 dll twinapi create process as user null activeds dll b succeeded b succeeded a ds get object ta ds get object get proc address m hactiveds dll a ds get object null b succeeded b succeeded a ds build enumerator ta ds build enumerator get proc address m hactiveds dll a ds build enumerator null b succeeded b succeeded a ds enumerate next ta ds enumerate next get proc address m hactiveds dll a ds enumerate next null if b succeeded add debug log line false t failed to load all functions from advapi32 dll freeapi return false return true csecrunasuser m_hadvapi32_dll m_hadvapi32_dll loadlibrary _t m_hactiveds_dll m_hactiveds_dll loadlibrary _t m_hadvapi32_dll adddebuglogline _t m_hactiveds_dll adddebuglogline _t bsucceeded bsucceeded bsucceeded createprocesswithlogonw tcreateprocesswithlogonw getprocaddress m_hadvapi32_dll createprocesswithlogonw bsucceeded bsucceeded getnamedsecurityinfo tgetnamedsecurityinfo getprocaddress m_hadvapi32_dll _twinapi getnamedsecurityinfo bsucceeded bsucceeded setnamedsecurityinfo tsetnamedsecurityinfo getprocaddress m_hadvapi32_dll _twinapi setnamedsecurityinfo bsucceeded bsucceeded addaccessallowedaceex taddaccessallowedaceex getprocaddress m_hadvapi32_dll addaccessallowedaceex bsucceeded bsucceeded lookupaccountname tlookupaccountname getprocaddress m_hadvapi32_dll _twinapi lookupaccountname bsucceeded bsucceeded getaclinformation tgetaclinformation getprocaddress m_hadvapi32_dll getaclinformation bsucceeded bsucceeded initializeacl tinitializeacl getprocaddress m_hadvapi32_dll initializeacl bsucceeded bsucceeded getace tgetace getprocaddress m_hadvapi32_dll getace bsucceeded bsucceeded addace taddace getprocaddress m_hadvapi32_dll addace bsucceeded bsucceeded equalsid tequalsid getprocaddress m_hadvapi32_dll equalsid bsucceeded bsucceeded getlengthsid tgetlengthsid getprocaddress m_hadvapi32_dll getlengthsid secureshellexecute bsucceeded bsucceeded openprocesstoken topenprocesstoken getprocaddress m_hadvapi32_dll openprocesstoken bsucceeded bsucceeded gettokeninformation tgettokeninformation getprocaddress m_hadvapi32_dll gettokeninformation bsucceeded bsucceeded createrestrictedtoken tcreaterestrictedtoken getprocaddress m_hadvapi32_dll createrestrictedtoken bsucceeded bsucceeded createprocessasuser tcreateprocessasuser getprocaddress m_hadvapi32_dll _twinapi createprocessasuser bsucceeded bsucceeded adsgetobject tadsgetobject getprocaddress m_hactiveds_dll adsgetobject bsucceeded bsucceeded adsbuildenumerator tadsbuildenumerator getprocaddress m_hactiveds_dll adsbuildenumerator bsucceeded bsucceeded adsenumeratenext tadsenumeratenext getprocaddress m_hactiveds_dll adsenumeratenext bsucceeded adddebuglogline _t void c sec run as user freeapi if m hadvapi32 dll 0 free library m hadvapi32 dll m hadvapi32 dll 0 if m hactiveds dll 0 free library m hactiveds dll m hactiveds dll 0 csecrunasuser m_hadvapi32_dll freelibrary m_hadvapi32_dll m_hadvapi32_dll m_hactiveds_dll freelibrary m_hactiveds_dll m_hactiveds_dll c search params wnd c search params wnd m szfloat set size 0 0 m szmru set size 0 0 load default windows system cursor a shared resource m hcurmove load cursor null idc sizeall m searchdlg null m pacsearchstring null m rcnamelbl set rect empty m rcname set rect empty m rcdropdownarrow set rect empty m rcfiletypelbl set rect empty m rcfiletype set rect empty m rcreset set rect empty m rcmethodlbl set rect empty m rcmethod set rect empty m rcopts set rect empty m rcstart set rect empty m rcmore set rect empty m rccancel set rect empty m rcunicode set rect empty csearchparamswnd csearchparamswnd m_szfloat setsize m_szmru setsize m_hcurmove loadcursor idc_sizeall m_searchdlg m_pacsearchstring m_rcnamelbl setrectempty m_rcname setrectempty m_rcdropdownarrow setrectempty m_rcfiletypelbl setrectempty m_rcfiletype setrectempty m_rcreset setrectempty m_rcmethodlbl setrectempty m_rcmethod setrectempty m_rcopts setrectempty m_rcstart setrectempty m_rcmore setrectempty m_rccancel setrectempty m_rcunicode setrectempty c search params wnd c search params wnd if m pacsearchstring m pacsearchstring unbind m pacsearchstring release destroy cursor is not to be used for a shared cursor as returned with load cursor if m hcurmove verify destroy cursor m hcurmove csearchparamswnd csearchparamswnd m_pacsearchstring m_pacsearchstring m_pacsearchstring destroycursor loadcursor m_hcurmove destroycursor m_hcurmove void c search params wnd localize set window text get res string ids searchparams get dlg item idc mstatic3 set window text get res string ids sw name get dlg item idc mstatic7 set window text get res string ids type get dlg item idc search reset set window text get res string ids pw reset get dlg item idc meth set window text get res string ids method get dlg item idc search unicode set window text get res string ids search unicode m ctlstart set window text get res string ids sw start m ctlcancel set window text get res string ids cancel m ctlmore set window text get res string ids more set window text get res string ids searchparams init methods ctrl init file types ctrl m ctlopts set item text or min size 0 get res string ids searchminsize m ctlopts set item text or max size 0 get res string ids searchmaxsize m ctlopts set item text or availability 0 get res string ids searchavail m ctlopts set item text or extension 0 get res string ids searchextention m ctlopts set item text or complete sources 0 get res string ids complsources m ctlopts set item text or codec 0 get res string ids codec m ctlopts set item text or bitrate 0 get res string ids minbitrate m ctlopts set item text or length 0 get res string ids minlength m ctlopts set item text or title 0 get res string ids title m ctlopts set item text or album 0 get res string ids album m ctlopts set item text or artist 0 get res string ids artist csearchparamswnd setwindowtext getresstring ids_searchparams getdlgitem idc_mstatic3 setwindowtext getresstring ids_sw_name getdlgitem idc_mstatic7 setwindowtext getresstring ids_type getdlgitem idc_search_reset setwindowtext getresstring ids_pw_reset getdlgitem idc_meth setwindowtext getresstring ids_method getdlgitem idc_search_unicode setwindowtext getresstring ids_search_unicode m_ctlstart setwindowtext getresstring ids_sw_start m_ctlcancel setwindowtext getresstring ids_cancel m_ctlmore setwindowtext getresstring ids_more setwindowtext getresstring ids_searchparams initmethodsctrl initfiletypesctrl m_ctlopts setitemtext orminsize getresstring ids_searchminsize m_ctlopts setitemtext ormaxsize getresstring ids_searchmaxsize m_ctlopts setitemtext oravailability getresstring ids_searchavail m_ctlopts setitemtext orextension getresstring ids_searchextention m_ctlopts setitemtext orcompletesources getresstring ids_complsources m_ctlopts setitemtext orcodec getresstring ids_codec m_ctlopts setitemtext orbitrate getresstring ids_minbitrate m_ctlopts setitemtext orlength getresstring ids_minlength m_ctlopts setitemtext ortitle getresstring ids_title m_ctlopts setitemtext oralbum getresstring ids_album m_ctlopts setitemtext orartist getresstring ids_artist void c search params wnd reset history if m pacsearchstring null return m ctlname send message wm keydown vk escape 0x00510001 m pacsearchstring clear csearchparamswnd resethistory m_pacsearchstring m_ctlname sendmessage wm_keydown vk_escape m_pacsearchstring void c search params wnd save settings save search strings csearchparamswnd savesettings savesearchstrings s search params c search params wnd get parameters c string str expression m ctlname get window text str expression str expression trim if is valid ed2k string str expression afx message box get res string ids search exprerror t n n get res string ids search invalidchar mb iconwarning mb help emule faq search hid base prompt return null bool b unicode m ctlunicode is window enabled m ctlunicode get check if b unicode c stringa stracp str expression if is valid ed2k stringa stracp afx message box get res string ids search exprerror t n n get res string ids search invalidchar mb iconwarning mb help emule faq search hid base prompt return null c stringa str file type int i item m ctlfiletype get cur sel if i item cb err lpcstr pszed2k file type lpcstr m ctlfiletype get item data ptr i item assert pszed2k file type null str file type pszed2k file type c string str min size m ctlopts get item text or min size 1 uint64 ull min size get search attr size str min size if ull min size uint64 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or min size 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null c string str max size m ctlopts get item text or max size 1 uint64 ull max size get search attr size str max size if ull max size uint64 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or max size 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null if ull max size ull min size ull max size 0 todo create a message box for that m ctlopts set item text or max size 1 t c string str extension if m ctlopts get item data or extension 1 0 str extension m ctlopts get item text or extension 1 str extension trim if str extension is empty str extension 0 t str extension str extension mid 1 m ctlopts set item text or extension 1 str extension uint u availability 0 if m ctlopts get item data or availability 1 0 c string str availability m ctlopts get item text or availability 1 u availability get search attr number str availability if u availability uint 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or availability 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null else if u availability 1000000 u availability 1000000 str availability format t u u availability m ctlopts set item text or availability 1 str availability uint u complete 0 if m ctlopts get item data or complete sources 1 0 c string str complete m ctlopts get item text or complete sources 1 u complete get search attr number str complete if u complete uint 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or complete sources 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null else if u complete 1000000 u complete 1000000 str complete format t u u complete m ctlopts set item text or complete sources 1 str complete c string str codec if m ctlopts get item data or codec 1 0 str codec m ctlopts get item text or codec 1 str codec trim ulong ul min bitrate 0 if m ctlopts get item data or bitrate 1 0 c string str min bitrate m ctlopts get item text or bitrate 1 ul min bitrate get search attr number str min bitrate if ul min bitrate ulong 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or bitrate 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null else if ul min bitrate 1000000 ul min bitrate 1000000 str min bitrate format t u ul min bitrate m ctlopts set item text or bitrate 1 str min bitrate ulong ul min length 0 if m ctlopts get item data or length 1 0 c string str min length m ctlopts get item text or length 1 ul min length get search attr length str min length if ul min length ulong 1 c string str error str error format get res string ids search attrerr m ctlopts get item text or length 0 afx message box get res string ids search exprerror t n n str error mb iconwarning mb help emule faq search hid base prompt return null else if ul min length 3600 24 ul min length 3600 24 c string str value sec to time length ul min length str value m ctlopts set item text or length 1 str value s search params p params new s search params p params str expression str expression p params e type e search type m ctlmethod get cur sel p params str file type str file type p params str min size str min size p params ull min size ull min size p params str max size str max size p params ull max size ull max size p params u availability u availability p params str extension str extension p params b match keywords is dlg button checked idc match keywords 0 p params u complete u complete p params str codec str codec p params ul min bitrate ul min bitrate p params ul min length ul min length if m ctlopts get item data or title 1 0 p params str title m ctlopts get item text or title 1 p params str title trim if m ctlopts get item data or album 1 0 p params str album m ctlopts get item text or album 1 p params str album trim if m ctlopts get item data or artist 1 0 p params str artist m ctlopts get item text or artist 1 p params str artist trim p params b unicode b unicode return p params ssearchparams csearchparamswnd getparameters cstring strexpression m_ctlname getwindowtext strexpression strexpression isvalided2kstring strexpression afxmessagebox getresstring ids_search_exprerror _t getresstring ids_search_invalidchar mb_iconwarning mb_help emule_faq_search hid_base_prompt bunicode m_ctlunicode iswindowenabled m_ctlunicode getcheck bunicode cstringa strexpression isvalided2kstringa afxmessagebox getresstring ids_search_exprerror _t getresstring ids_search_invalidchar mb_iconwarning mb_help emule_faq_search hid_base_prompt cstringa strfiletype iitem m_ctlfiletype getcursel iitem cb_err pszed2kfiletype m_ctlfiletype getitemdataptr iitem pszed2kfiletype strfiletype pszed2kfiletype cstring strminsize m_ctlopts getitemtext orminsize ullminsize getsearchattrsize strminsize ullminsize cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext orminsize afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt cstring strmaxsize m_ctlopts getitemtext ormaxsize ullmaxsize getsearchattrsize strmaxsize ullmaxsize cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext ormaxsize afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt ullmaxsize ullminsize ullmaxsize m_ctlopts setitemtext ormaxsize _t cstring strextension m_ctlopts getitemdata orextension strextension m_ctlopts getitemtext orextension strextension strextension isempty strextension _t strextension strextension m_ctlopts setitemtext orextension strextension uavailability m_ctlopts getitemdata oravailability cstring stravailability m_ctlopts getitemtext oravailability uavailability getsearchattrnumber stravailability uavailability cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext oravailability afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt uavailability uavailability stravailability _t uavailability m_ctlopts setitemtext oravailability stravailability ucomplete m_ctlopts getitemdata orcompletesources cstring strcomplete m_ctlopts getitemtext orcompletesources ucomplete getsearchattrnumber strcomplete ucomplete cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext orcompletesources afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt ucomplete ucomplete strcomplete _t ucomplete m_ctlopts setitemtext orcompletesources strcomplete cstring strcodec m_ctlopts getitemdata orcodec strcodec m_ctlopts getitemtext orcodec strcodec ulminbitrate m_ctlopts getitemdata orbitrate cstring strminbitrate m_ctlopts getitemtext orbitrate ulminbitrate getsearchattrnumber strminbitrate ulminbitrate cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext orbitrate afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt ulminbitrate ulminbitrate strminbitrate _t ulminbitrate m_ctlopts setitemtext orbitrate strminbitrate ulminlength m_ctlopts getitemdata orlength cstring strminlength m_ctlopts getitemtext orlength ulminlength getsearchattrlength strminlength ulminlength cstring strerror strerror getresstring ids_search_attrerr m_ctlopts getitemtext orlength afxmessagebox getresstring ids_search_exprerror _t strerror mb_iconwarning mb_help emule_faq_search hid_base_prompt ulminlength ulminlength cstring strvalue sectotimelength ulminlength strvalue m_ctlopts setitemtext orlength strvalue ssearchparams pparams ssearchparams pparams strexpression strexpression pparams etype esearchtype m_ctlmethod getcursel pparams strfiletype strfiletype pparams strminsize strminsize pparams ullminsize ullminsize pparams strmaxsize strmaxsize pparams ullmaxsize ullmaxsize pparams uavailability uavailability pparams strextension strextension pparams bmatchkeywords isdlgbuttonchecked idc_match_keywords pparams ucomplete ucomplete pparams strcodec strcodec pparams ulminbitrate ulminbitrate pparams ulminlength ulminlength m_ctlopts getitemdata ortitle pparams strtitle m_ctlopts getitemtext ortitle pparams strtitle m_ctlopts getitemdata oralbum pparams stralbum m_ctlopts getitemtext oralbum pparams stralbum m_ctlopts getitemdata orartist pparams strartist m_ctlopts getitemtext orartist pparams strartist pparams bunicode bunicode pparams void c search params wnd set parameters const s search params p params if p params b client shared files m ctlname set window text p params str expression if m ctlunicode is window enabled m ctlunicode set check p params b unicode else m ctlunicode set check 0 m ctlfiletype select item data stringa p params str file type m ctlopts set item text or min size 1 p params str min size m ctlopts set item text or max size 1 p params str max size m ctlopts set item text or extension 1 p params str extension c string str buff if p params u availability 0 str buff format t u p params u availability else str buff empty m ctlopts set item text or availability 1 str buff if p params u complete 0 str buff format t u p params u complete else str buff empty m ctlopts set item text or complete sources 1 str buff m ctlopts set item text or codec 1 p params str codec if p params ul min bitrate 0 str buff format t u p params ul min bitrate else str buff empty m ctlopts set item text or bitrate 1 str buff if p params ul min length 0 sec to time length p params ul min length str buff else str buff empty m ctlopts set item text or length 1 str buff m ctlopts set item text or title 1 p params str title m ctlopts set item text or album 1 p params str album m ctlopts set item text or artist 1 p params str artist csearchparamswnd setparameters ssearchparams pparams pparams bclientsharedfiles m_ctlname setwindowtext pparams strexpression m_ctlunicode iswindowenabled m_ctlunicode setcheck pparams bunicode m_ctlunicode setcheck m_ctlfiletype selectitemdatastringa pparams strfiletype m_ctlopts setitemtext orminsize pparams strminsize m_ctlopts setitemtext ormaxsize pparams strmaxsize m_ctlopts setitemtext orextension pparams strextension cstring strbuff pparams uavailability strbuff _t pparams uavailability strbuff m_ctlopts setitemtext oravailability strbuff pparams ucomplete strbuff _t pparams ucomplete strbuff m_ctlopts setitemtext orcompletesources strbuff m_ctlopts setitemtext orcodec pparams strcodec pparams ulminbitrate strbuff _t pparams ulminbitrate strbuff m_ctlopts setitemtext orbitrate strbuff pparams ulminlength sectotimelength pparams ulminlength strbuff strbuff m_ctlopts setitemtext orlength strbuff m_ctlopts setitemtext ortitle pparams strtitle m_ctlopts setitemtext oralbum pparams stralbum m_ctlopts setitemtext orartist pparams strartist c size c search params wnd calc dynamic layout int n length dword dw mode c frame wnd p frm get docking frame this function is typically called with c size size horz m pbar calc dynamic layout 0 lm horz lm horzdock c size size vert m pbar calc dynamic layout 0 lm vertdock c size size float m pbar calc dynamic layout 0 lm horz lm mruwidth c rect rc frm clnt p frm get client rect rc frm clnt c rect rc inside rc frm clnt calc inside rect rc inside dw mode lm horzdock c rect rc borders rc borders left rc inside left rc frm clnt left rc borders top rc inside top rc frm clnt top rc borders bottom rc frm clnt bottom rc inside bottom rc borders right rc frm clnt right rc inside right if dw mode lm horzdock lm vertdock if dw mode lm vertdock c size sz float sz float cx min vert width sz float cy rc frm clnt height get system metrics sm cyedge 2 m szfloat sz float return sz float else if dw mode lm horzdock c size sz float sz float cx rc frm clnt width get system metrics sm cxedge 2 sz float cy m sizedefault cy rc borders top rc borders bottom m szfloat sz float return sz float return c dialog bar calc dynamic layout n length dw mode if dw mode lm mruwidth return m szmru if dw mode lm commit m szmru m szfloat return m szfloat c size sz float if dw mode lm lengthy 0 sz float cx n length if n length m sizedefault cx rc borders left rc borders right sz float cx min vert width sz float cy min horz width else sz float cy m sizedefault cy rc borders top rc borders bottom else sz float cy n length if n length min horz width sz float cx m sizedefault cx rc borders left rc borders right sz float cy m sizedefault cy rc borders top rc borders bottom else sz float cx min vert width m szfloat sz float return sz float csize csearchparamswnd calcdynamiclayout nlength dwmode cframewnd pfrm getdockingframe csize sizehorz m_pbar calcdynamiclayout lm_horz lm_horzdock csize sizevert m_pbar calcdynamiclayout lm_vertdock csize sizefloat m_pbar calcdynamiclayout lm_horz lm_mruwidth crect rcfrmclnt pfrm getclientrect rcfrmclnt crect rcinside rcfrmclnt calcinsiderect rcinside dwmode lm_horzdock crect rcborders rcborders rcinside rcfrmclnt rcborders rcinside rcfrmclnt rcborders rcfrmclnt rcinside rcborders rcfrmclnt rcinside dwmode lm_horzdock lm_vertdock dwmode lm_vertdock csize szfloat szfloat min_vert_width szfloat rcfrmclnt getsystemmetrics sm_cyedge m_szfloat szfloat szfloat dwmode lm_horzdock csize szfloat szfloat rcfrmclnt getsystemmetrics sm_cxedge szfloat m_sizedefault rcborders rcborders m_szfloat szfloat szfloat cdialogbar calcdynamiclayout nlength dwmode dwmode lm_mruwidth m_szmru dwmode lm_commit m_szmru m_szfloat m_szfloat csize szfloat dwmode lm_lengthy szfloat nlength nlength m_sizedefault rcborders rcborders szfloat min_vert_width szfloat min_horz_width szfloat m_sizedefault rcborders rcborders szfloat nlength nlength min_horz_width szfloat m_sizedefault rcborders rcborders szfloat m_sizedefault rcborders rcborders szfloat min_vert_width m_szfloat szfloat szfloat void c search params wnd on update cmdui c frame wnd p target bool b disable if no hndler disable mfc s command routing by not passing the process flow to base class csearchparamswnd onupdatecmdui cframewnd ptarget bdisableifnohndler bool c search params wnd pre translate message msg p msg if p msg message wm keydown if p msg w param vk escape return false if m pacsearchstring m pacsearchstring is bound p msg w param vk delete p msg hwnd m ctlname m hwnd get async key state vk menu 0 get async key state vk control 0 m pacsearchstring clear if p msg w param vk return m ctlstart is window enabled if m pacsearchstring m pacsearchstring is bound p msg hwnd m ctlname m hwnd c string str text m ctlname get window text str text if str text is empty m ctlname set window text t this seems to be the only chance to let the dropdown list to disapear m ctlname set window text str text m ctlname set sel str text get length str text get length return c dialog bar pre translate message p msg csearchparamswnd pretranslatemessage pmsg pmsg wm_keydown pmsg wparam vk_escape m_pacsearchstring m_pacsearchstring isbound pmsg wparam vk_delete pmsg m_ctlname m_hwnd getasynckeystate vk_menu getasynckeystate vk_control m_pacsearchstring pmsg wparam vk_return m_ctlstart iswindowenabled m_pacsearchstring m_pacsearchstring isbound pmsg m_ctlname m_hwnd cstring strtext m_ctlname getwindowtext strtext strtext isempty m_ctlname setwindowtext _t m_ctlname setwindowtext strtext m_ctlname setsel strtext getlength strtext getlength cdialogbar pretranslatemessage pmsg void c search params wnd update controls int i method m ctlmethod get cur sel if i method cb err if i method the prefs get search method if i method search type kademlia on en change name else if i method search type ed2k server m searchdlg is local ed2k search running m ctlstart enable window false else if i method search type ed2k global m searchdlg is global ed2k search running m ctlstart enable window false the prefs set search method i method m ctlopts set item data or availability i method search type file donkey 1 0 m ctlopts set item data or extension i method search type file donkey 1 0 m ctlopts set item data or complete sources i method search type kademlia i method search type file donkey 1 0 m ctlopts set item data or codec i method search type file donkey 1 0 m ctlopts set item data or bitrate i method search type file donkey 1 0 m ctlopts set item data or length i method search type file donkey 1 0 m ctlopts set item data or title i method search type ed2k server i method search type ed2k global i method search type file donkey 1 0 m ctlopts set item data or album i method search type ed2k server i method search type ed2k global i method search type file donkey 1 0 m ctlopts set item data or artist i method search type ed2k server i method search type ed2k global i method search type file donkey 1 0 csearchparamswnd updatecontrols imethod m_ctlmethod getcursel imethod cb_err imethod theprefs getsearchmethod imethod searchtypekademlia onenchangename imethod searchtypeed2kserver m_searchdlg islocaled2ksearchrunning m_ctlstart enablewindow imethod searchtypeed2kglobal m_searchdlg isglobaled2ksearchrunning m_ctlstart enablewindow theprefs setsearchmethod imethod m_ctlopts setitemdata oravailability imethod searchtypefiledonkey m_ctlopts setitemdata orextension imethod searchtypefiledonkey m_ctlopts setitemdata orcompletesources imethod searchtypekademlia imethod searchtypefiledonkey m_ctlopts setitemdata orcodec imethod searchtypefiledonkey m_ctlopts setitemdata orbitrate imethod searchtypefiledonkey m_ctlopts setitemdata orlength imethod searchtypefiledonkey m_ctlopts setitemdata ortitle imethod searchtypeed2kserver imethod searchtypeed2kglobal imethod searchtypefiledonkey m_ctlopts setitemdata oralbum imethod searchtypeed2kserver imethod searchtypeed2kglobal imethod searchtypefiledonkey m_ctlopts setitemdata orartist imethod searchtypeed2kserver imethod searchtypeed2kglobal imethod searchtypefiledonkey void c search params wnd update unicode ctrl bool b unicode is disabled m ctlunicode is window enabled m ctlunicode get check 0 bool b offer unicode false if e search type m ctlmethod get cur sel search type file donkey c string str expr m ctlname get window text str expr c stringw wstr expr str expr for int i 0 i wstr expr get length i if wstr expr i 0x80 b offer unicode true break m ctlunicode enable window b offer unicode if b unicode is disabled m ctlunicode set check b offer unicode csearchparamswnd updateunicodectrl bunicodeisdisabled m_ctlunicode iswindowenabled m_ctlunicode getcheck bofferunicode esearchtype m_ctlmethod getcursel searchtypefiledonkey cstring strexpr m_ctlname getwindowtext strexpr cstringw wstrexpr strexpr wstrexpr getlength wstrexpr bofferunicode m_ctlunicode enablewindow bofferunicode bunicodeisdisabled m_ctlunicode setcheck bofferunicode bool c search params wnd save search strings if m pacsearchstring null return false return m pacsearchstring save list the prefs get config dir search strings profile csearchparamswnd savesearchstrings m_pacsearchstring m_pacsearchstring savelist theprefs getconfigdir search_strings_profile void c search params wnd set all icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t searchmethod server 16 16 iml add c temp icon loader t searchmethod global 16 16 iml add c temp icon loader t searchmethod kademlia 16 16 iml add c temp icon loader t searchmethod filedonkey 16 16 m ctlmethod set image list iml m imlsearchmethods delete image list m imlsearchmethods attach iml detach iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t searchfiletype any 16 16 iml add c temp icon loader t searchfiletype archive 16 16 iml add c temp icon loader t searchfiletype audio 16 16 iml add c temp icon loader t searchfiletype cdimage 16 16 iml add c temp icon loader t searchfiletype picture 16 16 iml add c temp icon loader t searchfiletype program 16 16 iml add c temp icon loader t searchfiletype video 16 16 iml add c temp icon loader t searchfiletype document 16 16 iml add c temp icon loader t searchfiletype emulecollection 16 16 m ctlfiletype set image list iml m imlfiletype delete image list m imlfiletype attach iml detach csearchparamswnd setallicons cimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t searchmethod_server ctempiconloader _t searchmethod_global ctempiconloader _t searchmethod_kademlia ctempiconloader _t searchmethod_filedonkey m_ctlmethod setimagelist m_imlsearchmethods deleteimagelist m_imlsearchmethods theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t searchfiletype_any ctempiconloader _t searchfiletype_archive ctempiconloader _t searchfiletype_audio ctempiconloader _t searchfiletype_cdimage ctempiconloader _t searchfiletype_picture ctempiconloader _t searchfiletype_program ctempiconloader _t searchfiletype_video ctempiconloader _t searchfiletype_document ctempiconloader _t searchfiletype_emulecollection m_ctlfiletype setimagelist m_imlfiletype deleteimagelist m_imlfiletype void c search params wnd init methods ctrl int i method m ctlmethod get cur sel m ctlmethod reset content verify m ctlmethod add item get res string ids server 0 search type ed2k server verify m ctlmethod add item get res string ids globalsearch 1 search type ed2k global verify m ctlmethod add item get res string ids kademlia t get res string ids network 2 search type kademlia verify m ctlmethod add item t file donkey web 3 search type file donkey update horz extent m ctlmethod 16 adjust dropped width to ensure all strings are fully visible m ctlmethod set cur sel i method cb err i method search type ed2k server csearchparamswnd initmethodsctrl imethod m_ctlmethod getcursel m_ctlmethod resetcontent m_ctlmethod additem getresstring ids_server searchtypeed2kserver m_ctlmethod additem getresstring ids_globalsearch searchtypeed2kglobal m_ctlmethod additem getresstring ids_kademlia _t getresstring ids_network searchtypekademlia m_ctlmethod additem _t filedonkey searchtypefiledonkey updatehorzextent m_ctlmethod m_ctlmethod setcursel imethod cb_err imethod searchtypeed2kserver void c search params wnd init file types ctrl get current selected entry by value language independent c stringa str cur sel file type int i item m ctlfiletype get cur sel if i item cb err lpcstr pszed2k file type lpcstr m ctlfiletype get item data ptr i item assert pszed2k file type null str cur sel file type pszed2k file type m ctlfiletype reset content create temp list of new entries language dependent std list s file type cb entry lst file type cb entries lst file type cb entries push back s file type cb entry get res string ids search any 0 lst file type cb entries push back s file type cb entry get res string ids search arc ed2kftstr archive 1 lst file type cb entries push back s file type cb entry get res string ids search audio ed2kftstr audio 2 lst file type cb entries push back s file type cb entry get res string ids search cdimg ed2kftstr cdimage 3 lst file type cb entries push back s file type cb entry get res string ids search pics ed2kftstr image 4 lst file type cb entries push back s file type cb entry get res string ids search prg ed2kftstr program 5 lst file type cb entries push back s file type cb entry get res string ids search video ed2kftstr video 6 lst file type cb entries push back s file type cb entry get res string ids search doc ed2kftstr document 7 lst file type cb entries push back s file type cb entry get res string ids search emulecollection ed2kftstr emulecollection 8 sort list with current language locale lst file type cb entries sort fill combobox control with already sorted list std list s file type cb entry const iterator it for it lst file type cb entries begin it lst file type cb entries end it int i item if i item m ctlfiletype add item it m strlabel it m iimage cb err m ctlfiletype set item data i item dword ptr it m pszitemdata update horz extent m ctlfiletype 16 adjust dropped width to ensure all strings are fully visible restore previous selected entry by value language independent if m ctlfiletype select item data stringa str cur sel file type if m ctlfiletype select string get res string ids search any m ctlfiletype set cur sel 0 csearchparamswnd initfiletypesctrl cstringa strcurselfiletype iitem m_ctlfiletype getcursel iitem cb_err pszed2kfiletype m_ctlfiletype getitemdataptr iitem pszed2kfiletype strcurselfiletype pszed2kfiletype m_ctlfiletype resetcontent sfiletypecbentry lstfiletypecbentries lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_any lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_arc ed2kftstr_archive lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_audio ed2kftstr_audio lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_cdimg ed2kftstr_cdimage lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_pics ed2kftstr_image lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_prg ed2kftstr_program lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_video ed2kftstr_video lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_doc ed2kftstr_document lstfiletypecbentries push_back sfiletypecbentry getresstring ids_search_emulecollection ed2kftstr_emulecollection lstfiletypecbentries sfiletypecbentry const_iterator lstfiletypecbentries lstfiletypecbentries iitem iitem m_ctlfiletype additem m_strlabel m_iimage cb_err m_ctlfiletype setitemdata iitem dword_ptr m_pszitemdata updatehorzextent m_ctlfiletype m_ctlfiletype selectitemdatastringa strcurselfiletype m_ctlfiletype selectstring getresstring ids_search_any m_ctlfiletype setcursel uint64 c search params wnd get search attr size const c string rstr expr c string str expr rstr expr str expr trim lptstr endptr null double dbl tcstod str expr endptr if endptr endptr t 0 while endptr t endptr tchar ch modifier totlower endptr if ch modifier t b return uint64 dbl 0 5 else if ch modifier t k return uint64 dbl 1024 0 5 else if ch modifier t 0 ch modifier t m else if ch modifier t g return uint64 dbl 1024 1024 1024 0 5 else return uint64 1 return uint64 dbl 1024 1024 0 5 default m bytes csearchparamswnd getsearchattrsize cstring rstrexpr cstring strexpr rstrexpr strexpr _tcstod strexpr _t _t chmodifier _totlower chmodifier _t chmodifier _t chmodifier _t chmodifier _t chmodifier _t mbytes ulong c search params wnd get search attr number const c string rstr expr c string str expr rstr expr str expr trim lptstr endptr null double dbl tcstod str expr endptr if endptr endptr t 0 while endptr t endptr tchar ch modifier totlower endptr if ch modifier t 0 else if ch modifier t k return ulong dbl 1000 0 5 else if ch modifier t m return ulong dbl 1000 1000 0 5 else if ch modifier t g return ulong dbl 1000 1000 1000 0 5 else return ulong 1 return ulong dbl 0 5 csearchparamswnd getsearchattrnumber cstring rstrexpr cstring strexpr rstrexpr strexpr _tcstod strexpr _t _t chmodifier _totlower chmodifier _t chmodifier _t chmodifier _t chmodifier _t ulong c search params wnd get search attr length const c string rstr expr c string str expr rstr expr str expr trim uint hour 0 min 0 sec 0 if stscanf str expr t u u u hour min sec 3 return hour 3600 min 60 sec if stscanf str expr t u u min sec 2 return min 60 sec lptstr endptr null double dbl tcstod str expr endptr if endptr endptr t 0 while endptr t endptr tchar ch modifier totlower endptr if ch modifier t 0 ch modifier t s else if ch modifier t m return ulong dbl 60 0 5 else if ch modifier t h return ulong dbl 60 60 0 5 else return ulong 1 return ulong dbl 0 5 csearchparamswnd getsearchattrlength cstring rstrexpr cstring strexpr rstrexpr strexpr _stscanf strexpr _t _stscanf strexpr _t _tcstod strexpr _t _t chmodifier _totlower chmodifier _t chmodifier _t chmodifier _t chmodifier _t void c search params wnd do data exchange c data exchange pdx c dialog bar do data exchange pdx ddx control pdx idc combo1 m ctlmethod ddx control pdx idc typesearch m ctlfiletype ddx control pdx idc searchname m ctlname ddx control pdx idc search opts m ctlopts ddx control pdx idc starts m ctlstart ddx control pdx idc cancels m ctlcancel ddx control pdx idc more m ctlmore ddx control pdx idc search unicode m ctlunicode csearchparamswnd dodataexchange cdataexchange cdialogbar dodataexchange ddx_control idc_combo1 m_ctlmethod ddx_control idc_typesearch m_ctlfiletype ddx_control idc_searchname m_ctlname ddx_control idc_search_opts m_ctlopts ddx_control idc_starts m_ctlstart ddx_control idc_cancels m_ctlcancel ddx_control idc_more m_ctlmore ddx_control idc_search_unicode m_ctlunicode lresult c search params wnd on init dialog wparam w param lparam l param default init window styles this void m sizedefault not yet set c rect size default get window rect size default c rect rc borders 4 4 4 4 set borders rc borders m szfloat cx size default width rc borders left rc borders right get system metrics sm cxedge 2 m szfloat cy size default height rc borders top rc borders bottom get system metrics sm cyedge 2 m szmru m szfloat update data false set all icons get dlg item idc mstatic3 get window rect m rcnamelbl screen to client m rcnamelbl m ctlname get window rect m rcname screen to client m rcname m ctlunicode get window rect m rcunicode screen to client m rcunicode get dlg item idc dd get window rect m rcdropdownarrow screen to client m rcdropdownarrow get dlg item idc mstatic7 get window rect m rcfiletypelbl screen to client m rcfiletypelbl m ctlfiletype get window rect m rcfiletype screen to client m rcfiletype get dlg item idc search reset get window rect m rcreset screen to client m rcreset get dlg item idc meth get window rect m rcmethodlbl screen to client m rcmethodlbl m ctlmethod get window rect m rcmethod screen to client m rcmethod m ctlopts get window rect m rcopts screen to client m rcopts m ctlstart get window rect m rcstart screen to client m rcstart m ctlmore get window rect m rcmore screen to client m rcmore m ctlcancel get window rect m rccancel screen to client m rccancel if the prefs get use autocompletion m pacsearchstring new c custom auto complete m pacsearchstring add ref if m pacsearchstring bind m ctlname aco updownkeydropslist aco autosuggest m pacsearchstring load list the prefs get config dir search strings profile if the app m fontsymbol m hobject get dlg item idc dd set font the app m fontsymbol get dlg item idc dd set window text t 6 show a down arrow else get dlg item idc dd show window sw hide m ctlname limit text max search expression len max length of search expression init methods ctrl if m ctlmethod set cur sel the prefs get search method cb err m ctlmethod set cur sel search type ed2k server m ctlfiletype get combo box ctrl modify style 0 cbs sort init file types ctrl if m ctlfiletype select string get res string ids search any m ctlfiletype set cur sel 0 c image list il dummy image list dummy list for getting the proper height of listview entries il dummy image list create 1 the app get small sytem icon size cy the app m idfltimagelistcolorflags ilc mask 1 1 m ctlopts set image list il dummy image list lvsil small assert m ctlopts get style lvs shareimagelists 0 il dummy image list detach m ctlopts set extended style lvs ex gridlines lvs ex labeltip m ctlopts insert column 0 t parameter m ctlopts insert column 1 t value m ctlopts insert item or min size get res string ids searchminsize m ctlopts insert item or max size get res string ids searchmaxsize m ctlopts insert item or availability get res string ids searchavail m ctlopts insert item or extension get res string ids searchextention m ctlopts insert item or complete sources get res string ids complsources m ctlopts insert item or codec get res string ids codec m ctlopts insert item or bitrate get res string ids minbitrate m ctlopts insert item or length get res string ids minlength m ctlopts insert item or title get res string ids title m ctlopts insert item or album get res string ids album m ctlopts insert item or artist get res string ids artist m ctlopts set column width 0 100 lvscw autosize m ctlopts set column width 1 120 update controls on en change name return true csearchparamswnd oninitdialog wparam lparam initwindowstyles m_sizedefault crect sizedefault getwindowrect sizedefault crect rcborders setborders rcborders m_szfloat sizedefault rcborders rcborders getsystemmetrics sm_cxedge m_szfloat sizedefault rcborders rcborders getsystemmetrics sm_cyedge m_szmru m_szfloat updatedata setallicons getdlgitem idc_mstatic3 getwindowrect m_rcnamelbl screentoclient m_rcnamelbl m_ctlname getwindowrect m_rcname screentoclient m_rcname m_ctlunicode getwindowrect m_rcunicode screentoclient m_rcunicode getdlgitem idc_dd getwindowrect m_rcdropdownarrow screentoclient m_rcdropdownarrow getdlgitem idc_mstatic7 getwindowrect m_rcfiletypelbl screentoclient m_rcfiletypelbl m_ctlfiletype getwindowrect m_rcfiletype screentoclient m_rcfiletype getdlgitem idc_search_reset getwindowrect m_rcreset screentoclient m_rcreset getdlgitem idc_meth getwindowrect m_rcmethodlbl screentoclient m_rcmethodlbl m_ctlmethod getwindowrect m_rcmethod screentoclient m_rcmethod m_ctlopts getwindowrect m_rcopts screentoclient m_rcopts m_ctlstart getwindowrect m_rcstart screentoclient m_rcstart m_ctlmore getwindowrect m_rcmore screentoclient m_rcmore m_ctlcancel getwindowrect m_rccancel screentoclient m_rccancel theprefs getuseautocompletion m_pacsearchstring ccustomautocomplete m_pacsearchstring addref m_pacsearchstring m_ctlname aco_updownkeydropslist aco_autosuggest m_pacsearchstring loadlist theprefs getconfigdir search_strings_profile theapp m_fontsymbol m_hobject getdlgitem idc_dd setfont theapp m_fontsymbol getdlgitem idc_dd setwindowtext _t getdlgitem idc_dd showwindow sw_hide m_ctlname limittext max_search_expression_len initmethodsctrl m_ctlmethod setcursel theprefs getsearchmethod cb_err m_ctlmethod setcursel searchtypeed2kserver m_ctlfiletype getcomboboxctrl modifystyle cbs_sort initfiletypesctrl m_ctlfiletype selectstring getresstring ids_search_any m_ctlfiletype setcursel cimagelist ildummyimagelist ildummyimagelist theapp getsmallsytemiconsize theapp m_idfltimagelistcolorflags ilc_mask m_ctlopts setimagelist ildummyimagelist lvsil_small m_ctlopts getstyle lvs_shareimagelists ildummyimagelist m_ctlopts setextendedstyle lvs_ex_gridlines lvs_ex_labeltip m_ctlopts insertcolumn _t m_ctlopts insertcolumn _t m_ctlopts insertitem orminsize getresstring ids_searchminsize m_ctlopts insertitem ormaxsize getresstring ids_searchmaxsize m_ctlopts insertitem oravailability getresstring ids_searchavail m_ctlopts insertitem orextension getresstring ids_searchextention m_ctlopts insertitem orcompletesources getresstring ids_complsources m_ctlopts insertitem orcodec getresstring ids_codec m_ctlopts insertitem orbitrate getresstring ids_minbitrate m_ctlopts insertitem orlength getresstring ids_minlength m_ctlopts insertitem ortitle getresstring ids_title m_ctlopts insertitem oralbum getresstring ids_album m_ctlopts insertitem orartist getresstring ids_artist m_ctlopts setcolumnwidth lvscw_autosize m_ctlopts setcolumnwidth updatecontrols onenchangename void c search params wnd on size uint n type int cx int cy c dialog bar on size n type cx cy if m ctlname m hwnd null return if cx min horz width c rect rc client get client rect rc client calc inside rect rc client true get dlg item idc mstatic3 move window rc client left m rcnamelbl left rc client top m rcnamelbl top m rcnamelbl width m rcnamelbl height m ctlname move window rc client left m rcname left rc client top m rcname top m rcname width m rcname height m ctlunicode move window rc client left m rcunicode left rc client top m rcunicode top m rcunicode width m rcunicode height get dlg item idc dd move window rc client left m rcdropdownarrow left rc client top m rcdropdownarrow top m rcdropdownarrow width m rcdropdownarrow height get dlg item idc mstatic7 move window rc client left m rcfiletypelbl left rc client top m rcfiletypelbl top m rcfiletypelbl width m rcfiletypelbl height m ctlfiletype move window rc client left m rcfiletype left rc client top m rcfiletype top m rcfiletype width m rcfiletype height get dlg item idc search reset move window rc client left m rcreset left rc client top m rcreset top m rcreset width m rcreset height get dlg item idc meth move window rc client left m rcmethodlbl left rc client top m rcmethodlbl top m rcmethodlbl width m rcmethodlbl height m ctlmethod move window rc client left m rcmethod left rc client top m rcmethod top m rcmethod width m rcmethod height m ctlstart move window rc client left m rcstart left rc client top m rcstart top m rcstart width m rcstart height m ctlmore move window rc client left m rcmore left rc client top m rcmore top m rcmore width m rcmore height m ctlcancel move window rc client left m rccancel left rc client top m rccancel top m rccancel width m rccancel height int i width opts rc client right rc client left m rcopts left m ctlopts move window rc client left m rcopts left rc client top m rcopts top i width opts m rcopts height c rect rc opts clnt m ctlopts get client rect rc opts clnt m ctlopts set column width 0 lvscw autosize m ctlopts set column width 1 rc opts clnt width m ctlopts get column width 0 m ctlopts modify style 0 lvs nocolumnheader else if cx min horz width c rect rc client get client rect rc client calc inside rect rc client false int y rc client top c rect rc name lbl get dlg item idc mstatic3 get window rect rc name lbl screen to client rc name lbl get dlg item idc mstatic3 move window rc client left y rc name lbl width rc name lbl height y rc name lbl height 2 c rect rc name m ctlname get window rect rc name screen to client rc name c rect rc drop down arrow get dlg item idc dd get window rect rc drop down arrow screen to client rc drop down arrow int i name width rc client width 4 rc drop down arrow width m ctlname move window rc client left y i name width rc name height get dlg item idc dd move window rc client left i name width 4 y rc drop down arrow width rc drop down arrow height y rc name height 2 c rect rc unicode m ctlunicode get window rect rc unicode screen to client rc unicode m ctlunicode move window rc client left y rc client width rc unicode height y rc unicode height 8 c rect rc file type lbl get dlg item idc mstatic7 get window rect rc file type lbl screen to client rc file type lbl get dlg item idc mstatic7 move window rc client left y rc file type lbl width rc file type lbl height y rc file type lbl height 2 c rect rc file type m ctlfiletype get window rect rc file type screen to client rc file type m ctlfiletype move window rc client left y rc file type width rc file type height c rect rc reset get dlg item idc search reset get window rect rc reset screen to client rc reset get dlg item idc search reset move window rc client left rc file type width 8 y rc reset width rc reset height y rc file type height 8 c rect rc method lbl get dlg item idc meth get window rect rc method lbl screen to client rc method lbl get dlg item idc meth move window rc client left y rc method lbl width rc method lbl height y rc method lbl height 2 c rect rc method m ctlmethod get window rect rc method screen to client rc method m ctlmethod move window rc client left y rc method width rc method height y rc method height 8 m ctlstart move window rc client left y m rcstart width m rcstart height m ctlmore move window rc client left m rcstart width 4 y m rcmore width m rcmore height y m rcstart height 4 m ctlcancel move window rc client left y m rccancel width m rccancel height y m rcstart height 4 int i opts height rc client bottom y 2 m ctlopts move window rc client left y rc client width i opts height c rect rc opts clnt m ctlopts get client rect rc opts clnt m ctlopts set column width 1 rc opts clnt width m ctlopts get column width 0 y i opts height 4 m ctlopts modify style lvs nocolumnheader 0 csearchparamswnd onsize ntype cdialogbar onsize ntype m_ctlname m_hwnd min_horz_width crect rcclient getclientrect rcclient calcinsiderect rcclient getdlgitem idc_mstatic3 movewindow rcclient m_rcnamelbl rcclient m_rcnamelbl m_rcnamelbl m_rcnamelbl m_ctlname movewindow rcclient m_rcname rcclient m_rcname m_rcname m_rcname m_ctlunicode movewindow rcclient m_rcunicode rcclient m_rcunicode m_rcunicode m_rcunicode getdlgitem idc_dd movewindow rcclient m_rcdropdownarrow rcclient m_rcdropdownarrow m_rcdropdownarrow m_rcdropdownarrow getdlgitem idc_mstatic7 movewindow rcclient m_rcfiletypelbl rcclient m_rcfiletypelbl m_rcfiletypelbl m_rcfiletypelbl m_ctlfiletype movewindow rcclient m_rcfiletype rcclient m_rcfiletype m_rcfiletype m_rcfiletype getdlgitem idc_search_reset movewindow rcclient m_rcreset rcclient m_rcreset m_rcreset m_rcreset getdlgitem idc_meth movewindow rcclient m_rcmethodlbl rcclient m_rcmethodlbl m_rcmethodlbl m_rcmethodlbl m_ctlmethod movewindow rcclient m_rcmethod rcclient m_rcmethod m_rcmethod m_rcmethod m_ctlstart movewindow rcclient m_rcstart rcclient m_rcstart m_rcstart m_rcstart m_ctlmore movewindow rcclient m_rcmore rcclient m_rcmore m_rcmore m_rcmore m_ctlcancel movewindow rcclient m_rccancel rcclient m_rccancel m_rccancel m_rccancel iwidthopts rcclient rcclient m_rcopts m_ctlopts movewindow rcclient m_rcopts rcclient m_rcopts iwidthopts m_rcopts crect rcoptsclnt m_ctlopts getclientrect rcoptsclnt m_ctlopts setcolumnwidth lvscw_autosize m_ctlopts setcolumnwidth rcoptsclnt m_ctlopts getcolumnwidth m_ctlopts modifystyle lvs_nocolumnheader min_horz_width crect rcclient getclientrect rcclient calcinsiderect rcclient rcclient crect rcnamelbl getdlgitem idc_mstatic3 getwindowrect rcnamelbl screentoclient rcnamelbl getdlgitem idc_mstatic3 movewindow rcclient rcnamelbl rcnamelbl rcnamelbl crect rcname m_ctlname getwindowrect rcname screentoclient rcname crect rcdropdownarrow getdlgitem idc_dd getwindowrect rcdropdownarrow screentoclient rcdropdownarrow inamewidth rcclient rcdropdownarrow m_ctlname movewindow rcclient inamewidth rcname getdlgitem idc_dd movewindow rcclient inamewidth rcdropdownarrow rcdropdownarrow rcname crect rcunicode m_ctlunicode getwindowrect rcunicode screentoclient rcunicode m_ctlunicode movewindow rcclient rcclient rcunicode rcunicode crect rcfiletypelbl getdlgitem idc_mstatic7 getwindowrect rcfiletypelbl screentoclient rcfiletypelbl getdlgitem idc_mstatic7 movewindow rcclient rcfiletypelbl rcfiletypelbl rcfiletypelbl crect rcfiletype m_ctlfiletype getwindowrect rcfiletype screentoclient rcfiletype m_ctlfiletype movewindow rcclient rcfiletype rcfiletype crect rcreset getdlgitem idc_search_reset getwindowrect rcreset screentoclient rcreset getdlgitem idc_search_reset movewindow rcclient rcfiletype rcreset rcreset rcfiletype crect rcmethodlbl getdlgitem idc_meth getwindowrect rcmethodlbl screentoclient rcmethodlbl getdlgitem idc_meth movewindow rcclient rcmethodlbl rcmethodlbl rcmethodlbl crect rcmethod m_ctlmethod getwindowrect rcmethod screentoclient rcmethod m_ctlmethod movewindow rcclient rcmethod rcmethod rcmethod m_ctlstart movewindow rcclient m_rcstart m_rcstart m_ctlmore movewindow rcclient m_rcstart m_rcmore m_rcmore m_rcstart m_ctlcancel movewindow rcclient m_rccancel m_rccancel m_rcstart ioptsheight rcclient m_ctlopts movewindow rcclient rcclient ioptsheight crect rcoptsclnt m_ctlopts getclientrect rcoptsclnt m_ctlopts setcolumnwidth rcoptsclnt m_ctlopts getcolumnwidth ioptsheight m_ctlopts modifystyle lvs_nocolumnheader void c search params wnd on bn clicked start m ctlmore enable window false if m ctlopts get edit ctrl get safe hwnd m ctlopts commit edit ctrl s search params p params get parameters if p params if p params str expression is empty if m pacsearchstring m pacsearchstring is bound m pacsearchstring add item p params str expression 0 m searchdlg start search p params else delete p params csearchparamswnd onbnclickedstart m_ctlmore enablewindow m_ctlopts geteditctrl getsafehwnd m_ctlopts commiteditctrl ssearchparams pparams getparameters pparams pparams strexpression isempty m_pacsearchstring m_pacsearchstring isbound m_pacsearchstring additem pparams strexpression m_searchdlg startsearch pparams pparams void c search params wnd on bn clicked cancel m searchdlg cancel search c wnd p wnd focus get focus m ctlcancel enable window false if p wnd focus p wnd focus m hwnd m ctlcancel m hwnd m ctlname set focus m ctlstart enable window true csearchparamswnd onbnclickedcancel m_searchdlg cancelsearch cwnd pwndfocus getfocus m_ctlcancel enablewindow pwndfocus pwndfocus m_hwnd m_ctlcancel m_hwnd m_ctlname setfocus m_ctlstart enablewindow void c search params wnd on bn clicked more c wnd p wnd focus get focus m ctlmore enable window false if p wnd focus p wnd focus m hwnd m ctlmore m hwnd m ctlstart set focus if m searchdlg search more p wnd focus get focus m ctlstart enable window false if p wnd focus p wnd focus m hwnd m ctlstart m hwnd m ctlname set focus m ctlcancel enable window true csearchparamswnd onbnclickedmore cwnd pwndfocus getfocus m_ctlmore enablewindow pwndfocus pwndfocus m_hwnd m_ctlmore m_hwnd m_ctlstart setfocus m_searchdlg searchmore pwndfocus getfocus m_ctlstart enablewindow pwndfocus pwndfocus m_hwnd m_ctlstart m_hwnd m_ctlname setfocus m_ctlcancel enablewindow void c search params wnd on cbn sel change method update controls on en change name csearchparamswnd oncbnselchangemethod updatecontrols onenchangename void c search params wnd on cbn sel end ok method update controls csearchparamswnd oncbnselendokmethod updatecontrols void c search params wnd ondd clicked m ctlname set focus m ctlname set window text t m ctlname send message wm keydown vk down 0x00510001 csearchparamswnd onddclicked m_ctlname setfocus m_ctlname setwindowtext _t m_ctlname sendmessage wm_keydown vk_down void c search params wnd on bn clicked search reset m ctlname set window text t if m ctlfiletype select string get res string ids search any m ctlfiletype set cur sel 0 for int i 0 i m ctlopts get item count i m ctlopts set item text i 1 t on en change name csearchparamswnd onbnclickedsearchreset m_ctlname setwindowtext _t m_ctlfiletype selectstring getresstring ids_search_any m_ctlfiletype setcursel m_ctlopts getitemcount m_ctlopts setitemtext _t onenchangename void c search params wnd on en change name m ctlstart enable window m ctlname get window text length 0 update unicode ctrl csearchparamswnd onenchangename m_ctlstart enablewindow m_ctlname getwindowtextlength updateunicodectrl void c search params wnd on destroy c dialog bar on destroy m imlsearchmethods delete image list m imlfiletype delete image list csearchparamswnd ondestroy cdialogbar ondestroy m_imlsearchmethods deleteimagelist m_imlfiletype deleteimagelist void c search params wnd on sys color change c dialog bar on sys color change set all icons csearchparamswnd onsyscolorchange cdialogbar onsyscolorchange setallicons void c search params wnd on sys command uint nid lparam l param if nid sc keymenu if l param emule hotmenu accel the app emuledlg send message wm command idc hotmenu else the app emuledlg send message wm syscommand nid l param return c dialog bar on sys command nid l param csearchparamswnd onsyscommand lparam sc_keymenu lparam emule_hotmenu_accel theapp sendmessage wm_command idc_hotmenu theapp sendmessage wm_syscommand lparam cdialogbar onsyscommand lparam bool c search params wnd on set cursor c wnd p wnd uint n hit test uint message if m hcurmove m dwstyle cbrs gripper cbrs floating cbrs gripper p wnd get safe hwnd m hwnd c point pt cursor if get cursor pos pt cursor screen to client pt cursor c rect rc clnt get client rect rc clnt bool b mouse over gripper if m dwstyle cbrs orient horz b mouse over gripper rc clnt pt in rect pt cursor pt cursor x 10 else b mouse over gripper rc clnt pt in rect pt cursor pt cursor y 10 if b mouse over gripper set cursor m hcurmove return true return c dialog bar on set cursor p wnd n hit test message csearchparamswnd onsetcursor cwnd pwnd nhittest m_hcurmove m_dwstyle cbrs_gripper cbrs_floating cbrs_gripper pwnd getsafehwnd m_hwnd cpoint ptcursor getcursorpos ptcursor screentoclient ptcursor crect rcclnt getclientrect rcclnt bmouseovergripper m_dwstyle cbrs_orient_horz bmouseovergripper rcclnt ptinrect ptcursor ptcursor bmouseovergripper rcclnt ptinrect ptcursor ptcursor bmouseovergripper setcursor m_hcurmove cdialogbar onsetcursor pwnd nhittest bool c search params wnd on help info helpinfo p help info the app show help emule faq search return true csearchparamswnd onhelpinfo phelpinfo theapp showhelp emule_faq_search c search attr m itag ft filename void m str m uintegeroperator ed2k search op equal m nnum 0 csearchattr m_itag ft_filename m_str m_uintegeroperator ed2k_search_op_equal m_nnum c search attr lpcstr psz string m itag ft filename m str psz string m uintegeroperator ed2k search op equal m nnum 0 csearchattr pszstring m_itag ft_filename m_str pszstring m_uintegeroperator ed2k_search_op_equal m_nnum c search expr void m aexpr csearchexpr m_aexpr c search expr const c search attr p attr m aexpr add p attr csearchexpr csearchattr pattr m_aexpr pattr void add e search operators e operator if e operator searchop or m aexpr add searchoptok or else if e operator searchop not m aexpr add searchoptok not else assert e operator searchop and m aexpr add searchoptok and esearchoperators eoperator eoperator searchop_or m_aexpr searchoptok_or eoperator searchop_not m_aexpr searchoptok_not eoperator searchop_and m_aexpr searchoptok_and void add const c search attr p attr m aexpr add p attr csearchattr pattr m_aexpr pattr void add const c search expr p expr m aexpr append p expr m aexpr csearchexpr pexpr m_aexpr pexpr m_aexpr c search expr target c safe mem file p data e utf8 str e str encode bool b supports64 bit bool pb packet using64 bit m data p data m estrencode e str encode m bsupports64bit b supports64 bit m pbpacketusing64bit pb packet using64 bit if m pbpacketusing64bit m pbpacketusing64bit false csearchexprtarget csafememfile pdata eutf8str estrencode bsupports64bit pbpacketusing64bit m_data pdata m_estrencode estrencode m_bsupports64bit bsupports64bit m_pbpacketusing64bit pbpacketusing64bit m_pbpacketusing64bit m_pbpacketusing64bit const c string get debug string const return m strdbg cstring getdebugstring m_strdbg void write booleanand m data writeu int8 0 boolean operator parameter type m data writeu int8 0x00 and m strdbg append format t and writebooleanand m_data writeuint8 m_data writeuint8 m_strdbg appendformat _t void write booleanor m data writeu int8 0 boolean operator parameter type m data writeu int8 0x01 or m strdbg append format t or writebooleanor m_data writeuint8 m_data writeuint8 m_strdbg appendformat _t void write booleannot m data writeu int8 0 boolean operator parameter type m data writeu int8 0x02 not m strdbg append format t not writebooleannot m_data writeuint8 m_data writeuint8 m_strdbg appendformat _t void write meta data search param const c string rstr value m data writeu int8 1 string parameter type m data write string rstr value m estrencode string value m strdbg append format t s rstr value writemetadatasearchparam cstring rstrvalue m_data writeuint8 m_data writestring rstrvalue m_estrencode m_strdbg appendformat _t rstrvalue void write meta data search param uint u meta tagid const c string rstr value m data writeu int8 2 string parameter type m data write string rstr value m estrencode string value m data writeu int16 sizeof uint8 meta tag id length m data writeu int8 uint8 u meta tagid meta tag id name m strdbg append format t s s dbg get file meta tag name u meta tagid rstr value writemetadatasearchparam umetatagid cstring rstrvalue m_data writeuint8 m_data writestring rstrvalue m_estrencode m_data writeuint16 m_data writeuint8 umetatagid m_strdbg appendformat _t dbggetfilemetatagname umetatagid rstrvalue void write meta data search param lpcstr psz meta tagid const c string rstr value m data writeu int8 2 string parameter type m data write string rstr value m estrencode string value m data write string psz meta tagid meta tag id m strdbg append format t s s dbg get file meta tag name psz meta tagid rstr value writemetadatasearchparam pszmetatagid cstring rstrvalue m_data writeuint8 m_data writestring rstrvalue m_estrencode m_data writestring pszmetatagid m_strdbg appendformat _t dbggetfilemetatagname pszmetatagid rstrvalue void write meta data search param uint u meta tagid uint u operator uint64 ull value bool b64 bit value ull value 0xfffffff fui64 if b64 bit value m bsupports64bit if m pbpacketusing64bit m pbpacketusing64bit true m data writeu int8 8 numeric parameter type int64 m data writeu int64 ull value numeric value else if b64 bit value ull value 0xffffffffu m data writeu int8 3 numeric parameter type int32 m data writeu int32 uint32 ull value numeric value m data writeu int8 uint8 u operator comparison operator m data writeu int16 sizeof uint8 meta tag id length m data writeu int8 uint8 u meta tagid meta tag id name m strdbg append format t s s i64u dbg get file meta tag name u meta tagid dbg get search operator name u operator ull value writemetadatasearchparam umetatagid uoperator ullvalue b64bitvalue ullvalue 0xffffffffui64 b64bitvalue m_bsupports64bit m_pbpacketusing64bit m_pbpacketusing64bit m_data writeuint8 m_data writeuint64 ullvalue b64bitvalue ullvalue m_data writeuint8 m_data writeuint32 ullvalue m_data writeuint8 uoperator m_data writeuint16 m_data writeuint8 umetatagid m_strdbg appendformat _t dbggetfilemetatagname umetatagid dbggetsearchoperatorname uoperator ullvalue void write meta data search param lpcstr psz meta tagid uint u operator uint64 ull value bool b64 bit value ull value 0xfffffff fui64 if b64 bit value m bsupports64bit if m pbpacketusing64bit m pbpacketusing64bit true m data writeu int8 8 numeric parameter type int64 m data writeu int64 ull value numeric value else if b64 bit value ull value 0xffffffffu m data writeu int8 3 numeric parameter type int32 m data writeu int32 uint32 ull value numeric value m data writeu int8 uint8 u operator comparison operator m data write string psz meta tagid meta tag id m strdbg append format t s s i64u dbg get file meta tag name psz meta tagid dbg get search operator name u operator ull value writemetadatasearchparam pszmetatagid uoperator ullvalue b64bitvalue ullvalue 0xffffffffui64 b64bitvalue m_bsupports64bit m_pbpacketusing64bit m_pbpacketusing64bit m_data writeuint8 m_data writeuint64 ullvalue b64bitvalue ullvalue m_data writeuint8 m_data writeuint32 ullvalue m_data writeuint8 uoperator m_data writestring pszmetatagid m_strdbg appendformat _t dbggetfilemetatagname pszmetatagid dbggetsearchoperatorname uoperator ullvalue public s file type cb entry const c string str label lpcstr psz item data int i image m strlabel str label m pszitemdata psz item data m iimage i image sfiletypecbentry cstring strlabel pszitemdata iimage m_strlabel strlabel m_pszitemdata pszitemdata m_iimage iimage operator const s file type cb entry e const return m strlabel compare e m strlabel 0 sfiletypecbentry m_strlabel m_strlabel c resizable page c comment dialog lst idd ids cmt readall m pafiles null m bdatachanged false m strcaption get res string ids cmt readall m psp psz title m strcaption m psp dw flags psp usetitle m pafiles null m timer 0 cresizablepage ccommentdialoglst ids_cmt_readall m_pafiles m_bdatachanged m_strcaption getresstring ids_cmt_readall m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_pafiles m_timer c comment dialog lst c comment dialog lst ccommentdialoglst ccommentdialoglst void c comment dialog lst refresh data bool delete old if delete old m lstcomments delete all items for int i 0 i m pafiles get size i c abstract file file static downcast c abstract file m pafiles i if file is part file for position pos c part file file srclist get head position pos null c up down client cur src c part file file srclist get next pos if cur src has file rating cur src get file comment is empty m lstcomments add item cur src const c typed ptr list c ptr list kademlia c entry list file get notes for position pos list get head position pos null kademlia c entry entry list get next pos m lstcomments add item entry if file is part file c part file file update file rating comment avail c string info if m lstcomments get item count 0 info t get res string ids cmt none t get dlg item idc cmstatus set window text info ccommentdialoglst refreshdata deleteold deleteold m_lstcomments deleteallitems m_pafiles getsize cabstractfile static_downcast cabstractfile m_pafiles ispartfile cpartfile getheadposition cupdownclient cur_src cpartfile getnext cur_src hasfilerating cur_src getfilecomment isempty m_lstcomments additem cur_src ctypedptrlist cptrlist centry getnotes getheadposition centry getnext m_lstcomments additem ispartfile cpartfile updatefileratingcommentavail cstring m_lstcomments getitemcount _t getresstring ids_cmt_none _t getdlgitem idc_cmstatus setwindowtext bool c comment dialog lst on init dialog c resizable page on init dialog init window styles this add anchor idc lst top left bottom right add anchor idc searchkad bottom right add anchor idc cmstatus bottom left m lstcomments init localize start time for calling refresh data verify m timer set timer 301 5000 0 null return true ccommentdialoglst oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_lst top_left bottom_right addanchor idc_searchkad bottom_right addanchor idc_cmstatus bottom_left m_lstcomments refreshdata m_timer settimer void c comment dialog lst do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc lst m lstcomments ccommentdialoglst dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_lst m_lstcomments bool c comment dialog lst on set active if c resizable page on set active return false if m bdatachanged refresh data m bdatachanged false return true ccommentdialoglst onsetactive cresizablepage onsetactive m_bdatachanged refreshdata m_bdatachanged void c comment dialog lst on bn clicked apply c resizable page onok ccommentdialoglst onbnclickedapply cresizablepage void c comment dialog lst on bn clicked search kad if kademlia c kademlia is connected for int i 0 i m pafiles get size i c abstract file file static downcast c abstract file m pafiles i if file if kademlia c search manager prepare lookup kademlia c search notes true kademlia cu int128 file get file hash afx message box get res string ids kadsearchalready mb ok mb iconinformation 0 ccommentdialoglst onbnclickedsearchkad ckademlia isconnected m_pafiles getsize cabstractfile static_downcast cabstractfile m_pafiles csearchmanager preparelookup csearch cuint128 getfilehash afxmessagebox getresstring ids_kadsearchalready mb_ok mb_iconinformation lresult c comment dialog lst on data changed wparam lparam m bdatachanged true return 1 ccommentdialoglst ondatachanged m_bdatachanged void c comment dialog lst on destroy if m timer kill timer m timer m timer 0 ccommentdialoglst ondestroy m_timer killtimer m_timer m_timer void c comment dialog lst on timer uint nid event refresh data false ccommentdialoglst ontimer nidevent refreshdata c dialog preview dlg idd p parent memset m icons 0 sizeof m icons cdialog previewdlg pparent m_icons m_icons preview dlg preview dlg for int i 0 i arrsize m icons i if m icons i verify destroy icon m icons i previewdlg previewdlg m_icons m_icons destroyicon m_icons void preview dlg show create idd previewdialog null previewdlg idd_previewdialog void preview dlg show image int n number int n image count m pfile get previews get size if n image count 0 return else if n image count n number n number 0 else if n number 0 n number n image count 1 m ncurrentimage n number hbitmap hbitmap m imagestatic set bitmap m pfile get previews n number make bitmap m imagestatic getdc m hdc if hbitmap delete object hbitmap c string str info str info format t image u of u n number 1 n image count set dlg item text idc preview info str info previewdlg showimage nnumber nimagecount m_pfile getpreviews getsize nimagecount nimagecount nnumber nnumber nnumber nnumber nimagecount m_ncurrentimage nnumber m_imagestatic setbitmap m_pfile getpreviews nnumber makebitmap m_imagestatic m_hdc deleteobject cstring strinfo strinfo _t nnumber nimagecount setdlgitemtext idc_preview_info strinfo bool preview dlg on init dialog c dialog on init dialog if m pfile null assert false return false init window styles this c string title get res string ids dl preview title remove t set window text title c string t m pfile get file name m ncurrentimage 0 show image 0 c button get dlg item idc pv exit set icon m icons 0 the app load icon t cancel c button get dlg item idc pv next set icon m icons 1 the app load icon t forward c button get dlg item idc pv prior set icon m icons 2 the app load icon t back return true previewdlg oninitdialog cdialog oninitdialog m_pfile initwindowstyles cstring getresstring ids_dl_preview _t setwindowtext cstring _t m_pfile getfilename m_ncurrentimage showimage cbutton getdlgitem idc_pv_exit seticon m_icons theapp loadicon _t cbutton getdlgitem idc_pv_next seticon m_icons theapp loadicon _t cbutton getdlgitem idc_pv_prior seticon m_icons theapp loadicon _t void preview dlg do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc pv image m imagestatic previewdlg dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_pv_image m_imagestatic void preview dlg on close hbitmap hbitmap m imagestatic set bitmap null if hbitmap delete object hbitmap c dialog on close delete this previewdlg onclose m_imagestatic setbitmap deleteobject cdialog onclose void preview dlg on bn clicked pv exit on close previewdlg onbnclickedpvexit onclose void preview dlg on bn clicked pv next show image m ncurrentimage 1 previewdlg onbnclickedpvnext showimage m_ncurrentimage void preview dlg on bn clicked pv prior show image m ncurrentimage 1 previewdlg onbnclickedpvprior showimage m_ncurrentimage c list view walker property sheet p list ctrl m upshinvokepage u psh invoke page position pos pa files get head position while pos m aitems add pa files get next pos m psh dw flags psh hashelp m psh dw flags psh noapplynow m wndmetadata m psp dw flags psp hashelp m wndmetadata m psp dw flags psp useiconid m wndmetadata m psp psz icon t metadata if m aitems get size 1 the prefs is ext controls enabled m wndmetadata set files m aitems add page m wndmetadata m wndcomments m psp dw flags psp hashelp m wndcomments m psp dw flags psp useiconid m wndcomments m psp psz icon t file comments m wndcomments set files m aitems add page m wndcomments lpctstr p psh start page m ppshstartpage if m upshinvokepage 0 p psh start page makeintresource m upshinvokepage for int i 0 i m pages get size i c property page p page get page i if p page m psp psz template p psh start page m psh n start page i break clistviewwalkerpropertysheet plistctrl m_upshinvokepage upshinvokepage pafiles getheadposition m_aitems pafiles getnext m_psh dwflags psh_hashelp m_psh dwflags psh_noapplynow m_wndmetadata m_psp dwflags psp_hashelp m_wndmetadata m_psp dwflags psp_useiconid m_wndmetadata m_psp pszicon _t m_aitems getsize theprefs isextcontrolsenabled m_wndmetadata setfiles m_aitems addpage m_wndmetadata m_wndcomments m_psp dwflags psp_hashelp m_wndcomments m_psp dwflags psp_useiconid m_wndcomments m_psp pszicon _t filecomments m_wndcomments setfiles m_aitems addpage m_wndcomments ppshstartpage m_ppshstartpage m_upshinvokepage ppshstartpage m_upshinvokepage m_pages getsize cpropertypage ppage getpage ppage m_psp psztemplate ppshstartpage m_psh nstartpage c search result file detail sheet c search result file detail sheet csearchresultfiledetailsheet csearchresultfiledetailsheet void c search result file detail sheet update title if m aitems get size 1 set window text get res string ids details t static downcast c search file m aitems 0 get file name else set window text get res string ids details csearchresultfiledetailsheet updatetitle m_aitems getsize setwindowtext getresstring ids_details _t static_downcast csearchfile m_aitems getfilename setwindowtext getresstring ids_details bool c search result file detail sheet on init dialog enable stacked tabs false bool b result c list view walker property sheet on init dialog high color tab update image list this init window styles this enable save restore t search result file details sheet call this after on init dialog update title return b result csearchresultfiledetailsheet oninitdialog enablestackedtabs bresult clistviewwalkerpropertysheet oninitdialog highcolortab updateimagelist initwindowstyles enablesaverestore _t searchresultfiledetailssheet oninitdialog updatetitle bresult void c search result file detail sheet on destroy if m upshinvokepage 0 m ppshstartpage get page get active index m psp psz template c list view walker property sheet on destroy csearchresultfiledetailsheet ondestroy m_upshinvokepage m_ppshstartpage getpage getactiveindex m_psp psztemplate clistviewwalkerpropertysheet ondestroy lresult c search result file detail sheet on data changed wparam lparam update title return 1 csearchresultfiledetailsheet ondatachanged updatetitle c scheduler c scheduler load from file save originals m ilastcheckedminute 60 cscheduler cscheduler loadfromfile saveoriginals m_ilastcheckedminute c scheduler c scheduler save to file remove all cscheduler cscheduler savetofile removeall int c scheduler add schedule schedule struct schedule schedulelist add schedule return schedulelist get count 1 cscheduler addschedule schedule_struct getcount void c scheduler remove schedule int index if index schedulelist get count return schedule struct todel todel schedulelist get at index delete todel schedulelist remove at index cscheduler removeschedule getcount schedule_struct getat removeat void c scheduler remove all while schedulelist get count 0 remove schedule 0 cscheduler removeall getcount removeschedule int c scheduler load from file c string str name c string temp str name format t spreferences ini the prefs get config dir c ini ini str name t scheduler uint max ini get int t count 0 uint count 0 while count max str name format t schedule i count temp ini get string t title t str name if temp t schedule struct news new schedule struct news title temp news day ini get int t day 0 news enabled ini get bool t enabled news time ini get int t start time news time2 ini get int t end time ini ser get true news actions arrsize news actions t actions ini ser get true news values arrsize news values t values add schedule news count else break return count cscheduler loadfromfile cstring strname cstring strname _t theprefs getconfigdir cini strname _t getint _t strname _t getstring _t _t strname _t schedule_struct schedule_struct getint _t getbool _t getint _t starttime getint _t endtime serget _t serget _t addschedule void c scheduler save to file c string temp schedule struct schedule c ini ini the prefs get config file t scheduler ini write int t count get count for uint8 i 0 i get count i schedule the app scheduler get schedule i temp format t schedule i i ini write string t title schedule title temp ini write int t day schedule day ini write int t start time schedule time ini write int t end time schedule time2 ini write bool t enabled schedule enabled ini ser get false schedule actions arrsize schedule actions t actions ini ser get false schedule values arrsize schedule values t values cscheduler savetofile cstring schedule_struct cini theprefs getconfigfile _t writeint _t getcount getcount theapp getschedule _t writestring _t writeint _t writeint _t starttime writeint _t endtime writebool _t serget _t serget _t int c scheduler check bool forcecheck if the prefs is scheduler enabled the app scheduler get count 0 the app emuledlg is running return 1 schedule struct schedule c time t now c time safe mktime c time get current time get local tm if forcecheck t now get minute m ilastcheckedminute return 1 m ilastcheckedminute t now get minute the app scheduler restore originals for uint8 si 0 si the app scheduler get count si schedule the app scheduler get schedule si if schedule actions 0 0 schedule enabled continue check day of week if schedule day day dayly int dow t now get day of week switch schedule day case day mo if dow 2 continue break case day di if dow 3 continue break case day mi if dow 4 continue break case day do if dow 5 continue break case day fr if dow 6 continue break case day sa if dow 7 continue break case day so if dow 1 continue break case day mo fr if dow 7 dow 1 continue break case day mo sa if dow 1 continue break case day sa so if dow 2 dow 6 continue check time uint h1 h2 m1 m2 c time t1 c time schedule time c time t2 c time schedule time2 h1 t1 get hour h2 t2 get hour m1 t1 get minute m2 t2 get minute int it1 it2 itn it1 h1 60 m1 it2 h2 60 m2 itn t now get hour 60 t now get minute if it1 it2 normal timespan if itn it1 itn it2 continue else reversed timespan 23 30 to 5 10 now 10 if itn it1 itn it2 continue ok lets do the actions of this schedule activate schedule si schedule time2 0 return 1 cscheduler theprefs isschedulerenabled theapp getcount theapp isrunning schedule_struct ctime tnow ctime safe_mktime ctime getcurrenttime getlocaltm tnow getminute m_ilastcheckedminute m_ilastcheckedminute tnow getminute theapp restoreoriginals theapp getcount theapp getschedule day_dayly tnow getdayofweek day_mo day_di day_mi day_do day_fr day_sa day_so day_mo_fr day_mo_sa day_sa_so ctime ctime ctime ctime gethour gethour getminute getminute tnow gethour tnow getminute activateschedule void c scheduler save originals original upload the prefs get max upload original download the prefs get max download original connections the prefs get max connections original cons5s the prefs get max conper five original sources the prefs get max source per file default cscheduler saveoriginals original_upload theprefs getmaxupload original_download theprefs getmaxdownload original_connections theprefs getmaxconnections original_cons5s theprefs getmaxconperfive original_sources theprefs getmaxsourceperfiledefault void c scheduler restore originals the prefs set max upload original upload the prefs set max download original download the prefs set max connections original connections the prefs set max cons per five original cons5s the prefs set max sources per file original sources cscheduler restoreoriginals theprefs setmaxupload original_upload theprefs setmaxdownload original_download theprefs setmaxconnections original_connections theprefs setmaxconsperfive original_cons5s theprefs setmaxsourcesperfile original_sources void c scheduler activate schedule int index bool makedefault schedule struct schedule get schedule index for int ai 0 ai 16 ai if schedule actions ai 0 break if schedule values ai maybe ignore in some future cases continue switch schedule actions ai case 1 the prefs set max upload tstoi schedule values ai if makedefault original upload uint16 tstoi schedule values ai break case 2 the prefs set max download tstoi schedule values ai if makedefault original download uint16 tstoi schedule values ai break case 3 the prefs set max sources per file tstoi schedule values ai if makedefault original sources tstoi schedule values ai break case 4 the prefs set max cons per five tstoi schedule values ai if makedefault original cons5s tstoi schedule values ai break case 5 the prefs set max connections tstoi schedule values ai if makedefault original connections tstoi schedule values ai break case 6 the app downloadqueue set cat status tstoi schedule values ai mp stop break case 7 the app downloadqueue set cat status tstoi schedule values ai mp resume break cscheduler activateschedule schedule_struct getschedule theprefs setmaxupload _tstoi original_upload _tstoi theprefs setmaxdownload _tstoi original_download _tstoi theprefs setmaxsourcesperfile _tstoi original_sources _tstoi theprefs setmaxconsperfive _tstoi original_cons5s _tstoi theprefs setmaxconnections _tstoi original_connections _tstoi theapp setcatstatus _tstoi mp_stop theapp setcatstatus _tstoi mp_resume crar file crar file m hlibunrar null m harchive null m pfnraropenarchiveex null m pfnrarclosearchive null m pfnrarreadheaderex null m pfnrarprocessfilew null crarfile crarfile m_hlibunrar m_harchive m_pfnraropenarchiveex m_pfnrarclosearchive m_pfnrarreadheaderex m_pfnrarprocessfilew crar file crar file close if m hlibunrar verify free library m hlibunrar crarfile crarfile m_hlibunrar freelibrary m_hlibunrar bool crar file open lpctstr psz archive file path if init un rar lib return false close m strarchivefilepath psz archive file path rar open archive data ex open archive data 0 open archive data arc namew const cast lpwstr lpcwstr m strarchivefilepath open archive data open mode rar om extract try m harchive m pfnraropenarchiveex open archive data catch m harchive null if m harchive null open archive data open result 0 close return false return true crarfile pszarchivefilepath initunrarlib m_strarchivefilepath pszarchivefilepath raropenarchivedataex openarchivedata openarchivedata arcnamew const_cast m_strarchivefilepath openarchivedata openmode rar_om_extract m_harchive m_pfnraropenarchiveex openarchivedata m_harchive m_harchive openarchivedata openresult void crar file close if m harchive assert m pfnrarclosearchive if m pfnrarclosearchive try verify m pfnrarclosearchive m harchive 0 catch m harchive null m strarchivefilepath empty crarfile m_harchive m_pfnrarclosearchive m_pfnrarclosearchive m_pfnrarclosearchive m_harchive m_harchive m_strarchivefilepath bool crar file get next file c string str file if m hlibunrar null m pfnrarreadheaderex null m harchive null assert 0 return false struct rar header data ex header data 0 int i read header result try i read header result m pfnrarreadheaderex m harchive header data catch i read header result 1 if i read header result 0 return false str file header data file namew return str file is empty crarfile getnextfile cstring strfile m_hlibunrar m_pfnrarreadheaderex m_harchive rarheaderdataex headerdata ireadheaderresult ireadheaderresult m_pfnrarreadheaderex m_harchive headerdata ireadheaderresult ireadheaderresult strfile headerdata filenamew strfile isempty bool crar file extract lpctstr psz dst file path if m hlibunrar null m pfnrarprocessfilew null m harchive null assert 0 return false int i process file result try i process file result m pfnrarprocessfilew m harchive rar extract null psz dst file path catch i process file result 1 if i process file result 0 return false return true crarfile pszdstfilepath m_hlibunrar m_pfnrarprocessfilew m_harchive iprocessfileresult iprocessfileresult m_pfnrarprocessfilew m_harchive rar_extract pszdstfilepath iprocessfileresult iprocessfileresult bool crar file skip if m hlibunrar null m pfnrarprocessfilew null m harchive null assert 0 return false int i process file result try i process file result m pfnrarprocessfilew m harchive rar skip null null catch i process file result 1 if i process file result 0 return false return true crarfile m_hlibunrar m_pfnrarprocessfilew m_harchive iprocessfileresult iprocessfileresult m_pfnrarprocessfilew m_harchive rar_skip iprocessfileresult iprocessfileresult bool crar file init un rar lib if m hlibunrar null m hlibunrar load library t unrar dll if m hlibunrar farproc m pfnraropenarchiveex get proc address m hlibunrar rar open archive ex farproc m pfnrarclosearchive get proc address m hlibunrar rar close archive farproc m pfnrarreadheaderex get proc address m hlibunrar rar read header ex farproc m pfnrarprocessfilew get proc address m hlibunrar rar process filew if m pfnraropenarchiveex null m pfnrarclosearchive null m pfnrarreadheaderex null m pfnrarprocessfilew null free library m hlibunrar m hlibunrar null if m hlibunrar null log warning log statusbar t failed to initialize unrar dll download latest version of unrar dll from http www rarlab com and copy unrar dll into e mule installation folder return m hlibunrar null crarfile initunrarlib m_hlibunrar m_hlibunrar loadlibrary _t m_hlibunrar m_pfnraropenarchiveex getprocaddress m_hlibunrar raropenarchiveex m_pfnrarclosearchive getprocaddress m_hlibunrar rarclosearchive m_pfnrarreadheaderex getprocaddress m_hlibunrar rarreadheaderex m_pfnrarprocessfilew getprocaddress m_hlibunrar rarprocessfilew m_pfnraropenarchiveex m_pfnrarclosearchive m_pfnrarreadheaderex m_pfnrarprocessfilew freelibrary m_hlibunrar m_hlibunrar m_hlibunrar logwarning log_statusbar _t emule m_hlibunrar c quantizer c quantizer uint n max colors uint n color bits m ncolorbits n color bits 8 n color bits 8 m ptree null m nleafcount 0 for int i 0 i int m ncolorbits i m preduciblenodes i null m nmaxcolors n max colors cquantizer cquantizer nmaxcolors ncolorbits m_ncolorbits ncolorbits ncolorbits m_ptree m_nleafcount m_ncolorbits m_preduciblenodes m_nmaxcolors nmaxcolors c quantizer c quantizer if m ptree null delete tree m ptree cquantizer cquantizer m_ptree deletetree m_ptree bool c quantizer process image handle h image byte r g b int i j bitmapinfoheader ds memcpy ds h image sizeof ds int effwdt ds bi bit count ds bi width 31 32 4 int n pad effwdt ds bi width ds bi bit count 7 8 byte pb bits byte h image lpdword h image switch ds bi bit count case 1 1 bit dib case 4 4 bit dib case 8 8 bit dib for i 0 i ds bi height i for j 0 j ds bi width j byte idx get pixel index j i ds bi bit count effwdt pb bits byte pal byte h image sizeof bitmapinfoheader long ldx idx sizeof rgbquad b pal ldx g pal ldx r pal ldx add color m ptree r g b m ncolorbits 0 m nleafcount m preduciblenodes while m nleafcount m nmaxcolors reduce tree m ncolorbits m nleafcount m preduciblenodes break case 24 24 bit dib for i 0 i ds bi height i for j 0 j ds bi width j b pb bits g pb bits r pb bits add color m ptree r g b m ncolorbits 0 m nleafcount m preduciblenodes while m nleafcount m nmaxcolors reduce tree m ncolorbits m nleafcount m preduciblenodes pb bits n pad break default unrecognized color format return false return true cquantizer processimage himage himage bibitcount biwidth npad biwidth bibitcount pbbits himage himage bibitcount biheight biwidth getpixelindex bibitcount pbbits himage addcolor m_ptree m_ncolorbits m_nleafcount m_preduciblenodes m_nleafcount m_nmaxcolors reducetree m_ncolorbits m_nleafcount m_preduciblenodes biheight biwidth pbbits pbbits pbbits addcolor m_ptree m_ncolorbits m_nleafcount m_preduciblenodes m_nleafcount m_nmaxcolors reducetree m_ncolorbits m_nleafcount m_preduciblenodes pbbits npad uint c quantizer get color count return m nleafcount cquantizer getcolorcount m_nleafcount void c quantizer set color table rgbquad prgb uint n index 0 get palette colors m ptree prgb n index cquantizer setcolortable nindex getpalettecolors m_ptree nindex uint n color bits uint n level uint p leaf count node p reducible nodes static byte mask 8 0x80 0x40 0x20 0x10 0x08 0x04 0x02 0x01 if the node doesn t exist create it if pp node null pp node node create node n level n color bits p leaf count p reducible nodes update color information if it s a leaf node if pp node b is leaf pp node n pixel count pp node n red sum r pp node n green sum g pp node n blue sum b else recurse a level deeper if the node is not a leaf int shift 7 n level int n index r mask n level shift 2 g mask n level shift 1 b mask n level shift add color pp node p child n index r g b n color bits n level 1 p leaf count p reducible nodes ncolorbits nlevel pleafcount preduciblenodes ppnode ppnode createnode nlevel ncolorbits pleafcount preduciblenodes ppnode bisleaf ppnode npixelcount ppnode nredsum ppnode ngreensum ppnode nbluesum nlevel nindex nlevel nlevel nlevel addcolor ppnode pchild nindex ncolorbits nlevel pleafcount preduciblenodes node p reducible nodes node p node node calloc 1 sizeof node if p node null return null p node b is leaf n level n color bits true false if p node b is leaf p leaf count else p node p next p reducible nodes n level p reducible nodes n level p node return p node preduciblenodes pnode pnode pnode bisleaf nlevel ncolorbits pnode bisleaf pleafcount pnode pnext preduciblenodes nlevel preduciblenodes nlevel pnode pnode node p reducible nodes find the deepest level containing at least one reducible node for int i n color bits 1 i 0 p reducible nodes i null i reduce the node most recently added to the list at level i node p node p reducible nodes i p reducible nodes i p node p next uint n red sum 0 uint n green sum 0 uint n blue sum 0 uint n children 0 for i 0 i 8 i if p node p child i null n red sum p node p child i n red sum n green sum p node p child i n green sum n blue sum p node p child i n blue sum p node n pixel count p node p child i n pixel count free p node p child i p node p child i null n children p node b is leaf true p node n red sum n red sum p node n green sum n green sum p node n blue sum n blue sum p leaf count n children 1 preduciblenodes ncolorbits preduciblenodes pnode preduciblenodes preduciblenodes pnode pnext nredsum ngreensum nbluesum nchildren pnode pchild nredsum pnode pchild nredsum ngreensum pnode pchild ngreensum nbluesum pnode pchild nbluesum pnode npixelcount pnode pchild npixelcount pnode pchild pnode pchild nchildren pnode bisleaf pnode nredsum nredsum pnode ngreensum ngreensum pnode nbluesum nbluesum pleafcount nchildren void c quantizer delete tree node pp node for int i 0 i 8 i if pp node p child i null delete tree pp node p child i free pp node pp node null cquantizer deletetree ppnode ppnode pchild deletetree ppnode pchild ppnode ppnode void c quantizer get palette colors node p tree rgbquad prgb uint p index if p tree if p tree b is leaf prgb p index rgb red byte p tree n red sum p tree n pixel count prgb p index rgb green byte p tree n green sum p tree n pixel count prgb p index rgb blue byte p tree n blue sum p tree n pixel count prgb p index rgb reserved 0 p index else for int i 0 i 8 i if p tree p child i null get palette colors p tree p child i prgb p index cquantizer getpalettecolors ptree pindex ptree ptree bisleaf pindex rgbred ptree nredsum ptree npixelcount pindex rgbgreen ptree ngreensum ptree npixelcount pindex rgbblue ptree nbluesum ptree npixelcount pindex rgbreserved pindex ptree pchild getpalettecolors ptree pchild pindex byte c quantizer get pixel index long x long y int nbit long effwdt byte pimage if nbit 8 return pimage y effwdt x else byte pos byte i dst pimage y effwdt x nbit 3 if nbit 4 pos byte 4 1 x 2 i dst 0x0f pos return i dst pos else if nbit 1 pos byte 7 x 8 i dst 0x01 pos return i dst pos return 0 cquantizer getpixelindex idst idst idst idst idst bool c preview thread init instance dbg set thread name part file preview init thread locale return true cpreviewthread initinstance dbgsetthreadname partfilepreview initthreadlocale return false try uint64 n size m ppartfile get file size c string str extension c string tcsrchr m ppartfile get file name t c string str preview name m ppartfile get temp path t m ppartfile get file name mid 0 5 t preview str extension bool b full sized true if str extension compare no case t mpg str extension compare no case t mpeg b full sized false if dest file open str preview name c file mode write c file share deny write c file mode create return false src file seek to begin if b full sized dest file set length n size dest file seek to begin byte aby buffer 4096 uint32 n read while dest file get position 4096 partsize 2 n read src file read aby buffer 4096 dest file write aby buffer n read src file seek longlong partsize 2 c file end uint32 n to go partsize 2 if b full sized dest file seek longlong partsize 2 c file end do n read n to go 4096 1 n to go 4096 n to go n read n read src file read aby buffer 4096 dest file write aby buffer n read while n to go dest file close src file close m ppartfile m bpreviewing false shellexecuteinfo se memset se 0 sizeof se se f mask see mask nocloseprocess se lp verb t open c string path if m player is empty tchar short path 512 cax2 short path for vlc get short path name str preview name short path arrsize short path path the prefs get video player int pos path reverse find t if pos 1 path empty else path path left pos 1 se lp file m player se lp parameters short path se lp directory path else se lp file str preview name se n show sw show se cb size sizeof se shell execute ex se if se h process wait for single object se h process infinite close handle se h process c file remove str preview name nsize m_ppartfile getfilesize cstring strextension cstring _tcsrchr m_ppartfile getfilename _t cstring strpreviewname m_ppartfile gettemppath _t m_ppartfile getfilename _t _preview strextension bfullsized strextension comparenocase _t strextension comparenocase _t bfullsized destfile strpreviewname cfile modewrite cfile sharedenywrite cfile modecreate srcfile seektobegin bfullsized destfile setlength nsize destfile seektobegin abybuffer nread destfile getposition nread srcfile abybuffer destfile abybuffer nread srcfile cfile ntogo bfullsized destfile cfile nread ntogo ntogo ntogo nread nread srcfile abybuffer destfile abybuffer nread ntogo destfile srcfile m_ppartfile m_bpreviewing fmask see_mask_nocloseprocess lpverb _t cstring m_player isempty shortpath getshortpathname strpreviewname shortpath shortpath theprefs getvideoplayer reversefind _t lpfile m_player lpparameters shortpath lpdirectory lpfile strpreviewname nshow sw_show cbsize shellexecuteex hprocess waitforsingleobject hprocess closehandle hprocess cfile strpreviewname void c preview thread set values c part file p part file c string player m ppartfile p part file m player player cpreviewthread setvalues cpartfile ppartfile cstring m_ppartfile ppartfile m_player c preview thread c preview thread cpreviewthread cpreviewthread c preview thread c preview thread cpreviewthread cpreviewthread c preview apps c preview apps m tdefappsfilelastmodified 0 cpreviewapps cpreviewapps m_tdefappsfilelastmodified c string c preview apps get default apps file const return the prefs get config dir t preview apps dat cstring cpreviewapps getdefaultappsfile theprefs getconfigdir _t previewapps int c preview apps read all apps remove all apps c string str file path get default apps file file read file tfsopen str file path t r sh denywr if read file null c string name url sbuffer while feof read file tchar buffer 1024 if fgetts buffer arrsize buffer read file null break sbuffer buffer sbuffer trim right t r n t ignore comments too short lines if sbuffer get at 0 t sbuffer get at 0 t sbuffer get length 5 continue int i pos 0 c string str title sbuffer tokenize t i pos str title trim if str title is empty c string str command line sbuffer tokenize t i pos str command line trim if str command line is empty lpctstr psz command line str command line lptstr psz command args path get args psz command line c string str command str command args if psz command args str command str command line left psz command args psz command line else str command str command line str command trim t t if str command is empty uint64 ull min completed size 0 uint64 ull min start of file 0 c string array astr extensions c string str params sbuffer tokenize t i pos while str params is empty int i pos param 0 c string str id str params tokenize t i pos param if str id is empty c string str value str params tokenize t i pos param if str id compare no case t ext 0 if str value is empty if str value 0 t str value t str value astr extensions add str value else if str id compare no case t min size 0 if str value is empty stscanf str value t i64u ull min completed size else if str id compare no case t min start 0 if str value is empty stscanf str value t i64u ull min start of file str params sbuffer tokenize t i pos s preview app svc svc str title str title svc str command str command svc str command args psz command args svc str command args trim svc astr extensions append astr extensions svc ull min completed size ull min completed size svc ull min start of file ull min start of file m aapps add svc fclose read file struct stat st if tstat str file path st 0 m tdefappsfilelastmodified st st mtime return m aapps get count cpreviewapps readallapps removeallapps cstring strfilepath getdefaultappsfile readfile _tfsopen strfilepath _t _sh_denywr readfile cstring readfile _fgetts readfile trimright _t getat _t getat _t getlength ipos cstring strtitle _t ipos strtitle strtitle isempty cstring strcommandline _t ipos strcommandline strcommandline isempty pszcommandline strcommandline pszcommandargs pathgetargs pszcommandline cstring strcommand strcommandargs pszcommandargs strcommand strcommandline pszcommandargs pszcommandline strcommand strcommandline strcommand _t strcommand isempty ullmincompletedsize ullminstartoffile cstringarray astrextensions cstring strparams _t ipos strparams isempty iposparam cstring strid strparams _t iposparam strid isempty cstring strvalue strparams _t iposparam strid comparenocase _t strvalue isempty strvalue _t strvalue _t strvalue astrextensions strvalue strid comparenocase _t minsize strvalue isempty _stscanf strvalue _t ullmincompletedsize strid comparenocase _t minstart strvalue isempty _stscanf strvalue _t ullminstartoffile strparams _t ipos spreviewapp strtitle strtitle strcommand strcommand strcommandargs pszcommandargs strcommandargs astrextensions astrextensions ullmincompletedsize ullmincompletedsize ullminstartoffile ullminstartoffile m_aapps readfile _stat _tstat strfilepath m_tdefappsfilelastmodified st_mtime m_aapps getcount void c preview apps remove all apps m aapps remove all m tdefappsfilelastmodified 0 cpreviewapps removeallapps m_aapps removeall m_tdefappsfilelastmodified int c preview apps get all menu entries c menu r menu const c part file file update apps for int i 0 i m aapps get count i const s preview app r svc m aapps get at i if mp preview app min i mp preview app max break bool b enabled false if file if file get completed size uint64 16 1024 b enabled true r menu append menu mf string b enabled mf enabled mf grayed mp preview app min i r svc str title return m aapps get count cpreviewapps getallmenuentries cmenu rmenu cpartfile updateapps m_aapps getcount spreviewapp rsvc m_aapps getat mp_preview_app_min mp_preview_app_max benabled getcompletedsize benabled rmenu appendmenu mf_string benabled mf_enabled mf_grayed mp_preview_app_min rsvc strtitle m_aapps getcount void c preview apps run app c part file file uint u menuid const s preview app svc m aapps get at u menuid mp preview app min c string str part file path file get full name strip available met extension to get the part file name if str part file path get length 4 str part file path right 4 t met str part file path delete str part file path get length 4 4 if the path contains spaces quote the entire path if str part file path find t 1 str part file path t str part file path t get directory of video player application c string str command dir svc str command int i pos str command dir reverse find t if i pos 1 str command dir empty else str command dir str command dir left i pos 1 path remove backslash str command dir get buffer str command dir release buffer c string str args svc str command args if str args is empty str args t str args str part file path file flush buffer true c string str command svc str command expand environment strings str command expand environment strings str args expand environment strings str command dir trace starting preview application n trace command s n str command trace args s n str args trace dir s n str command dir shell execute null t open str command str args str command dir sw shownormal cpreviewapps runapp cpartfile umenuid spreviewapp m_aapps getat umenuid mp_preview_app_min cstring strpartfilepath getfullname strpartfilepath getlength strpartfilepath _t strpartfilepath strpartfilepath getlength strpartfilepath _t strpartfilepath _t strpartfilepath _t cstring strcommanddir strcommand ipos strcommanddir reversefind _t ipos strcommanddir strcommanddir strcommanddir ipos pathremovebackslash strcommanddir getbuffer strcommanddir releasebuffer cstring strargs strcommandargs strargs isempty strargs _t strargs strpartfilepath flushbuffer cstring strcommand strcommand expandenvironmentstrings strcommand expandenvironmentstrings strargs expandenvironmentstrings strcommanddir strcommand strargs strcommanddir shellexecute _t strcommand strargs strcommanddir sw_shownormal c preview apps e can preview res c preview apps can preview const c part file file int i app get preview app file if i app 1 return not handled const s preview app p app m aapps get at i app if p app ull min completed size 0 if file get completed size p app ull min completed size return no if p app ull min start of file 0 if file is complete 0 p app ull min start of file false return no return yes cpreviewapps ecanpreviewres cpreviewapps canpreview cpartfile iapp getpreviewapp iapp nothandled spreviewapp papp m_aapps getat iapp papp ullmincompletedsize getcompletedsize papp ullmincompletedsize papp ullminstartoffile iscomplete papp ullminstartoffile int c preview apps get preview app const c part file file lpctstr psz ext path find extension file get file name if psz ext null return 1 update apps int i app 1 for int i 0 i app 1 i m aapps get count i const s preview app r app m aapps get at i for int j 0 j r app astr extensions get count j if r app astr extensions get at j compare no case psz ext 0 i app i break return i app cpreviewapps getpreviewapp cpartfile pszext pathfindextension getfilename pszext updateapps iapp iapp m_aapps getcount spreviewapp rapp m_aapps getat rapp astrextensions getcount rapp astrextensions getat comparenocase pszext iapp iapp bool c preview apps preview c part file file int i app get preview app file if i app 1 return false run app file mp preview app min i app return true cpreviewapps cpartfile iapp getpreviewapp iapp runapp mp_preview_app_min iapp void c preview apps update apps if m aapps get count 0 read all apps else struct stat st if tstat get default apps file st 0 st st mtime m tdefappsfilelastmodified read all apps cpreviewapps updateapps m_aapps getcount readallapps _stat _tstat getdefaultappsfile st_mtime m_tdefappsfilelastmodified readallapps void c ini add modul path c string str file name bool b modul path true tchar drive max drive tchar dir max dir tchar fname max fname tchar ext max ext tsplitpath str file name drive dir fname ext if drive 0 path canonicalize doesn t work with for all plattforms c string str module if b modul path get module file name null str module get buffer max ini buffer max ini buffer str module release buffer else get current directory max ini buffer str module get buffer max ini buffer str module release buffer fix by cpp world online no str module trim right t str module trim right t str module t str module release buffer tsplitpath str module drive dir fname ext str module drive str module dir str module str file name str file name str module cini addmodulpath cstring strfilename bmodulpath _max_drive _max_dir _max_fname _max_ext _tsplitpath strfilename pathcanonicalize cstring strmodule bmodulpath getmodulefilename strmodule getbuffer max_ini_buffer max_ini_buffer strmodule releasebuffer getcurrentdirectory max_ini_buffer strmodule getbuffer max_ini_buffer strmodule releasebuffer strmodule trimright _t strmodule trimright _t strmodule _t strmodule releasebuffer _tsplitpath strmodule strmodule strmodule strmodule strfilename strfilename strmodule c string c ini get default section return afx get app name cstring cini getdefaultsection afxgetappname c string c ini get default ini file bool b modul path true tchar drive max drive tchar dir max dir tchar fname max fname tchar ext max ext c string str temp c string str appl name get module file name null str temp get buffer max ini buffer max ini buffer str temp release buffer tsplitpath str temp drive dir fname ext str temp fname appl name str temp t ini appl name ini if b modul path str appl name drive str appl name dir str appl name str temp else get current directory max ini buffer str appl name get buffer max ini buffer str appl name release buffer str appl name trim right t str appl name trim right t str appl name t str appl name str temp return str appl name cstring cini getdefaultinifile bmodulpath _max_drive _max_dir _max_fname _max_ext cstring strtemp cstring strapplname getmodulefilename strtemp getbuffer max_ini_buffer max_ini_buffer strtemp releasebuffer _tsplitpath strtemp strtemp applname strtemp _t applname bmodulpath strapplname strapplname strapplname strtemp getcurrentdirectory max_ini_buffer strapplname getbuffer max_ini_buffer strapplname releasebuffer strapplname trimright _t strapplname trimright _t strapplname _t strapplname strtemp strapplname m bmodulpath true m strfilename get default ini file m bmodulpath m strsection get default section m_bmodulpath m_strfilename getdefaultinifile m_bmodulpath m_strsection getdefaultsection m bmodulpath ini m bmodulpath if m strfilename is empty m strfilename get default ini file m bmodulpath add modul path m strfilename m bmodulpath if m strsection is empty m strsection get default section m_bmodulpath m_bmodulpath m_strfilename isempty m_strfilename getdefaultinifile m_bmodulpath addmodulpath m_strfilename m_bmodulpath m_strsection isempty m_strsection getdefaultsection m bmodulpath true if m strfilename is empty m strfilename get default ini file m bmodulpath add modul path m strfilename m bmodulpath m strsection get default section m_bmodulpath m_strfilename isempty m_strfilename getdefaultinifile m_bmodulpath addmodulpath m_strfilename m_bmodulpath m_strsection getdefaultsection m bmodulpath true if m strfilename is empty m strfilename get default ini file m bmodulpath add modul path m strfilename m bmodulpath if m strsection is empty m strsection get default section m_bmodulpath m_strfilename isempty m_strfilename getdefaultinifile m_bmodulpath addmodulpath m_strfilename m_bmodulpath m_strsection isempty m_strsection getdefaultsection c ini c ini cini cini const const void c ini set file name const c string str file name m strfilename str file name add modul path m strfilename cini setfilename cstring strfilename m_strfilename strfilename addmodulpath m_strfilename void c ini set section const c string str section m strsection str section cini setsection cstring strsection m_strsection strsection const c string c ini get file name const return m strfilename cstring cini getfilename m_strfilename const c string c ini get section const return m strsection cstring cini getsection m_strsection c string c ini get string lpctstr str entry lpctstr str default null lpctstr str section null if str default null return c string getlpcstr str entry str section t else return c string getlpcstr str entry str section str default cstring cini getstring strentry strdefault strsection strdefault cstring strentry strsection _t cstring strentry strsection strdefault c string c ini get stringutf8 lpctstr str entry lpctstr str default null lpctstr str section null uses conversion if str section null m strsection str section c stringa strutf8 get private profile stringa t2ca m strsection t2ca str entry t2ca str default strutf8 get buffer set length max ini buffer max ini buffer t2ca m strfilename strutf8 release buffer return opt utf8 to str strutf8 cstring cini getstringutf8 strentry strdefault strsection uses_conversion strsection m_strsection strsection cstringa getprivateprofilestringa m_strsection strentry strdefault getbuffersetlength max_ini_buffer max_ini_buffer m_strfilename releasebuffer optutf8tostr c string c ini get string long lpctstr str entry lpctstr str default null lpctstr str section null c string ret unsigned int maxstrlen max ini buffer if str section null m strsection str section do get private profile string m strsection str entry str default null t str default ret get buffer set length maxstrlen maxstrlen m strfilename ret release buffer if unsigned int ret get length maxstrlen 2 break maxstrlen max ini buffer while maxstrlen 32767 return ret cstring cini getstringlong strentry strdefault strsection cstring max_ini_buffer strsection m_strsection strsection getprivateprofilestring m_strsection strentry strdefault _t strdefault getbuffersetlength m_strfilename releasebuffer getlength max_ini_buffer double c ini get double lpctstr str entry double f default 0 0 lpctstr str section null tchar str default max path sntprintf str default arrsize str default t g f default getlpcstr str entry str section str default return tstof m chbuffer cini getdouble strentry fdefault strsection strdefault max_path _sntprintf strdefault strdefault _t fdefault strentry strsection strdefault _tstof m_chbuffer float c ini get float lpctstr str entry float f default 0 0 lpctstr str section null tchar str default max path sntprintf str default arrsize str default t g f default getlpcstr str entry str section str default return float tstof m chbuffer cini getfloat strentry fdefault strsection strdefault max_path _sntprintf strdefault strdefault _t fdefault strentry strsection strdefault _tstof m_chbuffer int c ini get int lpctstr str entry int n default 0 lpctstr str section null tchar str default max path sntprintf str default arrsize str default t d n default getlpcstr str entry str section str default return tstoi m chbuffer cini getint strentry ndefault strsection strdefault max_path _sntprintf strdefault strdefault _t ndefault strentry strsection strdefault _tstoi m_chbuffer ulonglong c ini getu int64 lpctstr str entry ulonglong n default 0 lpctstr str section null tchar str default max path sntprintf str default arrsize str default t i64u n default getlpcstr str entry str section str default ulonglong n result if stscanf m chbuffer t i64u n result 1 return 0 return n result cini getuint64 strentry ndefault strsection strdefault max_path _sntprintf strdefault strdefault _t ndefault strentry strsection strdefault nresult _stscanf m_chbuffer _t nresult nresult word c ini getword lpctstr str entry word n default 0 lpctstr str section null tchar str default max path sntprintf str default arrsize str default t u n default getlpcstr str entry str section str default return word tstoi m chbuffer cini strentry ndefault strsection strdefault max_path _sntprintf strdefault strdefault _t ndefault strentry strsection strdefault _tstoi m_chbuffer bool c ini get bool lpctstr str entry bool b default false lpctstr str section null tchar str default max path sntprintf str default arrsize str default t d int b default getlpcstr str entry str section str default return tstoi m chbuffer 0 cini getbool strentry bdefault strsection strdefault max_path _sntprintf strdefault strdefault _t bdefault strentry strsection strdefault _tstoi m_chbuffer c point c ini get point lpctstr str entry c point pt default lpctstr str section c point pt return pt default c string str default str default format t d d pt default x pt default y c string str point get string str entry str default str section stscanf str point t d d pt return x pt return y return pt return cpoint cini getpoint strentry cpoint ptdefault strsection cpoint ptreturn ptdefault cstring strdefault strdefault _t ptdefault ptdefault cstring strpoint getstring strentry strdefault strsection _stscanf strpoint _t ptreturn ptreturn ptreturn c rect c ini get rect lpctstr str entry c rect rect default lpctstr str section c rect rect return rect default c string str default old version str default format d d d d rect default top rect default left rect default bottom rect default right str default format t d d d d rect default left rect default top rect default right rect default bottom c string str rect get string str entry str default str section new version found if 4 stscanf str rect t d d d d rect default left rect default top rect default right rect default bottom return rect return old version found stscanf str rect t d d d d rect return top rect return left rect return bottom rect return right return rect return crect cini getrect strentry crect rectdefault strsection crect rectreturn rectdefault cstring strdefault strdefault rectdefault rectdefault rectdefault rectdefault strdefault _t rectdefault rectdefault rectdefault rectdefault cstring strrect getstring strentry strdefault strsection _stscanf strrect _t rectdefault rectdefault rectdefault rectdefault rectreturn _stscanf strrect _t rectreturn rectreturn rectreturn rectreturn rectreturn colorref c ini get col ref lpctstr str entry colorref cr default lpctstr str section int temp 3 getr value cr default getg value cr default getb value cr default c string str default str default format t rgb hd hd hd temp 0 temp 1 temp 2 c string str col ref get string str entry str default str section stscanf str col ref t rgb d d d temp temp 1 temp 2 return rgb temp 0 temp 1 temp 2 cini getcolref strentry crdefault strsection getrvalue crdefault getgvalue crdefault getbvalue crdefault cstring strdefault strdefault _t cstring strcolref getstring strentry strdefault strsection _stscanf strcolref _t bool c ini get binary lpctstr lpsz entry byte pp data uint p bytes lpctstr psz section pp data null p bytes 0 c string str get string lpsz entry null psz section if str is empty return false assert str get length 2 0 int ptr n len str get length p bytes uint n len 2 pp data new byte p bytes for int i 0 i n len i 2 pp data i 2 byte str i 1 a 4 str i a return true cini getbinary lpszentry ppdata pbytes pszsection ppdata pbytes cstring getstring lpszentry pszsection isempty getlength int_ptr nlen getlength pbytes nlen ppdata pbytes nlen ppdata void c ini write string lpctstr str entry lpctstr str lpctstr str section null if str section null m strsection str section write private profile string m strsection str entry str m strfilename cini writestring strentry strsection strsection m_strsection strsection writeprivateprofilestring m_strsection strentry m_strfilename void c ini write stringutf8 lpctstr str entry lpctstr psz lpctstr str section null uses conversion if str section null m strsection str section c string str psz write private profile stringa t2ca m strsection t2ca str entry str to utf8 str t2ca m strfilename cini writestringutf8 strentry strsection uses_conversion strsection m_strsection strsection cstring writeprivateprofilestringa m_strsection strentry strtoutf8 m_strfilename void c ini write double lpctstr str entry double f lpctstr str section null if str section null m strsection str section tchar str buffer max path sntprintf str buffer arrsize str buffer t g f write private profile string m strsection str entry str buffer m strfilename cini writedouble strentry strsection strsection m_strsection strsection strbuffer max_path _sntprintf strbuffer strbuffer _t writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini write float lpctstr str entry float f lpctstr str section null if str section null m strsection str section tchar str buffer max path sntprintf str buffer arrsize str buffer t g f write private profile string m strsection str entry str buffer m strfilename cini writefloat strentry strsection strsection m_strsection strsection strbuffer max_path _sntprintf strbuffer strbuffer _t writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini write int lpctstr str entry int n lpctstr str section null if str section null m strsection str section tchar str buffer max path itot n str buffer 10 write private profile string m strsection str entry str buffer m strfilename cini writeint strentry strsection strsection m_strsection strsection strbuffer max_path _itot strbuffer writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini writeu int64 lpctstr str entry ulonglong n lpctstr str section null if str section null m strsection str section tchar str buffer max path ui64tot n str buffer 10 write private profile string m strsection str entry str buffer m strfilename cini writeuint64 strentry strsection strsection m_strsection strsection strbuffer max_path _ui64tot strbuffer writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini writeword lpctstr str entry word n lpctstr str section null if str section null m strsection str section tchar str buffer max path ultot n str buffer 10 write private profile string m strsection str entry str buffer m strfilename cini strentry strsection strsection m_strsection strsection strbuffer max_path _ultot strbuffer writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini write bool lpctstr str entry bool b lpctstr str section null if str section null m strsection str section tchar str buffer max path sntprintf str buffer arrsize str buffer t d int b write private profile string m strsection str entry str buffer m strfilename cini writebool strentry strsection strsection m_strsection strsection strbuffer max_path _sntprintf strbuffer strbuffer _t writeprivateprofilestring m_strsection strentry strbuffer m_strfilename void c ini write point lpctstr str entry c point pt lpctstr str section if str section null m strsection str section c string str buffer str buffer format t d d pt x pt y write m strfilename m strsection str entry str buffer cini writepoint strentry cpoint strsection strsection m_strsection strsection cstring strbuffer strbuffer _t m_strfilename m_strsection strentry strbuffer void c ini write rect lpctstr str entry c rect rect lpctstr str section if str section null m strsection str section c string str buffer str buffer format t d d d d rect top rect left rect bottom rect right write m strfilename m strsection str entry str buffer cini writerect strentry crect strsection strsection m_strsection strsection cstring strbuffer strbuffer _t m_strfilename m_strsection strentry strbuffer void c ini write col ref lpctstr str entry colorref cr lpctstr str section if str section null m strsection str section c string str buffer str buffer format t rgb d d d getr value cr getg value cr getb value cr write m strfilename m strsection str entry str buffer cini writecolref strentry strsection strsection m_strsection strsection cstring strbuffer strbuffer _t getrvalue getgvalue getbvalue m_strfilename m_strsection strentry strbuffer bool c ini write binary lpctstr lpsz entry lpbyte p data uint n bytes lpctstr psz section convert to string and write out lptstr lpsz new tchar n bytes 2 1 uint i for i 0 i n bytes i lpsz i 2 tchar p data i 0x0f a low nibble lpsz i 2 1 tchar p data i 4 0x0f a high nibble lpsz i 2 0 write string lpsz entry lpsz psz section delete lpsz return true cini writebinary lpszentry pdata nbytes pszsection nbytes nbytes pdata pdata writestring lpszentry pszsection void c ini ser get string bool b get c string str lpctstr str entry lpctstr str section lpctstr str default if b get str get string str entry str default null str section null else write string str entry str str section null cini sergetstring bget cstring strentry strsection strdefault bget getstring strentry strdefault strsection writestring strentry strsection void c ini ser get double bool b get double f lpctstr str entry lpctstr str section null double f default 0 0 if b get f get double str entry f default null str section null else write double str entry f str section null cini sergetdouble bget strentry strsection fdefault bget getdouble strentry fdefault strsection writedouble strentry strsection void c ini ser get float bool b get float f lpctstr str entry lpctstr str section null float f default 0 0 if b get f get float str entry f default null str section null else write float str entry f str section null cini sergetfloat bget strentry strsection fdefault bget getfloat strentry fdefault strsection writefloat strentry strsection void c ini ser get int bool b get int n lpctstr str entry lpctstr str section null int n default 0 if b get n get int str entry n default null str section null else write int str entry n str section null cini sergetint bget strentry strsection ndefault bget getint strentry ndefault strsection writeint strentry strsection void c ini ser getdword bool b get dword n lpctstr str entry lpctstr str section null dword n default 0 if b get n dword get int str entry n default null str section null else write int str entry n str section null cini sergetdword bget strentry strsection ndefault bget getint strentry ndefault strsection writeint strentry strsection void c ini ser get bool bool b get bool b lpctstr str entry lpctstr str section null bool b default false if b get b get bool str entry b default null str section null else write bool str entry b str section null cini sergetbool bget strentry strsection bdefault bget getbool strentry bdefault strsection writebool strentry strsection void c ini ser get point bool b get c point pt lpctstr str entry lpctstr str section c point pt default if b get pt get point str entry pt default str section else write point str entry pt str section cini sergetpoint bget cpoint strentry strsection cpoint ptdefault bget getpoint strentry ptdefault strsection writepoint strentry strsection void c ini ser get rect bool b get c rect rect lpctstr str entry lpctstr str section c rect rect default if b get rect get rect str entry rect default str section else write rect str entry rect str section cini sergetrect bget crect strentry strsection crect rectdefault bget getrect strentry rectdefault strsection writerect strentry strsection void c ini ser get col ref bool b get colorref cr lpctstr str entry lpctstr str section colorref cr default if b get cr get col ref str entry cr default str section else write col ref str entry cr str section cini sergetcolref bget strentry strsection crdefault bget getcolref strentry crdefault strsection writecolref strentry strsection void c ini ser get bool b get c string str lpctstr str entry lpctstr str section null lpctstr str default null ser get string b get str str entry str section str default cini serget bget cstring strentry strsection strdefault sergetstring bget strentry strsection strdefault void c ini ser get bool b get double f lpctstr str entry lpctstr str section null double f default 0 0 ser get double b get f str entry str section f default cini serget bget strentry strsection fdefault sergetdouble bget strentry strsection fdefault void c ini ser get bool b get float f lpctstr str entry lpctstr str section null float f default 0 0 ser get float b get f str entry str section f default cini serget bget strentry strsection fdefault sergetfloat bget strentry strsection fdefault void c ini ser get bool b get int n lpctstr str entry lpctstr str section null int n default 0 ser get int b get n str entry str section n default cini serget bget strentry strsection ndefault sergetint bget strentry strsection ndefault void c ini ser get bool b get short n lpctstr str entry lpctstr str section null int n default 0 int n temp n ser get int b get n temp str entry str section n default n short n temp cini serget bget strentry strsection ndefault ntemp sergetint bget ntemp strentry strsection ndefault ntemp void c ini ser get bool b get dword n lpctstr str entry lpctstr str section null dword n default 0 ser getdword b get n str entry str section n default cini serget bget strentry strsection ndefault sergetdword bget strentry strsection ndefault void c ini ser get bool b get word n lpctstr str entry lpctstr str section null dword n default 0 dword dw temp n ser getdword b get dw temp str entry str section n default n word dw temp cini serget bget strentry strsection ndefault dwtemp sergetdword bget dwtemp strentry strsection ndefault dwtemp void c ini ser get bool b get c point pt lpctstr str entry lpctstr str section null c point pt default c point 0 0 ser get point b get pt str entry str section pt default cini serget bget cpoint strentry strsection cpoint ptdefault cpoint sergetpoint bget strentry strsection ptdefault void c ini ser get bool b get c rect rect lpctstr str entry lpctstr str section null c rect rect default c rect 0 0 0 0 ser get rect b get rect str entry str section rect default cini serget bget crect strentry strsection crect rectdefault crect sergetrect bget strentry strsection rectdefault void c ini ser get bool b get c string ar int n count lpctstr str entry lpctstr str section null lpctstr default null if n count 0 c string str buffer if b get str buffer get string str entry t str section int n offset 0 for int i 0 i n count i n offset parse str buffer n offset ar i if ar i get length 0 ar i default else str buffer ar 0 for int i 1 i n count i str buffer append char t str buffer append ar i write string str entry str buffer str section cini serget bget cstring ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection noffset ncount noffset strbuffer noffset getlength strbuffer ncount strbuffer appendchar _t strbuffer writestring strentry strbuffer strsection void c ini ser get bool b get double ar int n count lpctstr str entry lpctstr str section null double default 0 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i default else ar i tstof str temp else c string str temp str buffer format t g ar 0 for int i 1 i n count i str temp format t g ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstof strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get float ar int n count lpctstr str entry lpctstr str section null float default 0 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i default else ar i float tstof str temp else c string str temp str buffer format t g ar 0 for int i 1 i n count i str temp format t g ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstof strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get unsigned char ar int n count lpctstr str entry lpctstr str section null unsigned char default 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i default else ar i unsigned char tstoi str temp else c string str temp str buffer format t d ar 0 for int i 1 i n count i str temp format t d ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstoi strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get int ar int n count lpctstr str entry lpctstr str section null int default 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i default else ar i tstoi str temp else c string str temp str buffer format t d ar 0 for int i 1 i n count i str temp format t d ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstoi strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get short ar int n count lpctstr str entry lpctstr str section null int default 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i short default else ar i short tstoi str temp else c string str temp str buffer format t d ar 0 for int i 1 i n count i str temp format t d ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstoi strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get dword ar int n count lpctstr str entry lpctstr str section null dword default 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i default else ar i dword tstoi str temp else c string str temp str buffer format t d ar 0 for int i 1 i n count i str temp format t d ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstoi strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get word ar int n count lpctstr str entry lpctstr str section null dword default 0 if n count 0 c string str buffer if b get str buffer get string str entry t str section c string str temp int n offset 0 for int i 0 i n count i n offset parse str buffer n offset str temp if str temp get length 0 ar i word default else ar i word tstoi str temp else c string str temp str buffer format t d ar 0 for int i 1 i n count i str temp format t d ar i str buffer append char t str buffer append str temp write string str entry str buffer str section cini serget bget ncount strentry strsection ncount cstring strbuffer bget strbuffer getstring strentry _t strsection cstring strtemp noffset ncount noffset strbuffer noffset strtemp strtemp getlength _tstoi strtemp cstring strtemp strbuffer _t ncount strtemp _t strbuffer appendchar _t strbuffer strtemp writestring strentry strbuffer strsection void c ini ser get bool b get c point ar int n count lpctstr str entry lpctstr str section null c point default c point 0 0 c string str buffer for int i 0 i n count i str buffer format t i i str buffer str entry str buffer ser get b get ar i str buffer str section default cini serget bget cpoint ncount strentry strsection cpoint cpoint cstring strbuffer ncount strbuffer _t _ strbuffer strentry strbuffer serget bget strbuffer strsection void c ini ser get bool b get c rect ar int n count lpctstr str entry lpctstr str section null c rect default c rect 0 0 0 0 c string str buffer for int i 0 i n count i str buffer format t i i str buffer str entry str buffer ser get b get ar i str buffer str section default cini serget bget crect ncount strentry strsection crect crect cstring strbuffer ncount strbuffer _t _ strbuffer strentry strbuffer serget bget strbuffer strsection int c ini parse const c string str in int n offset c string str out str out empty int n length str in get length if n offset n length if n offset 0 str in n offset t n offset while n offset n length if istspace tuchar str in n offset break n offset while n offset n length str out str in n offset if str in n offset t break str out trim return n offset cini cstring strin noffset cstring strout strout nlength strin getlength noffset nlength noffset strin noffset _t noffset noffset nlength _istspace _tuchar strin noffset noffset noffset nlength strout strin noffset strin noffset _t strout noffset void c ini delete key lpctstr psz key write private profile string m strsection psz key null m strfilename cini deletekey pszkey writeprivateprofilestring m_strsection pszkey m_strfilename void c ini init lpctstr str file name lpctstr str section null if str section null m strsection str section if str file name null m strfilename str file name cini strfilename strsection strsection m_strsection strsection strfilename m_strfilename strfilename tchar c ini getlpcstr lpctstr str entry lpctstr str section lpctstr str default evtl section neu setzen if str section null m strsection str section c string temp if str default null temp read m strfilename m strsection str entry c string else temp read m strfilename m strsection str entry str default return tchar memcpy m chbuffer lpctstr temp temp get length 1 sizeof tchar 1 damit die null am ende mit kopiert wird cini strentry strsection strdefault strsection m_strsection strsection cstring strdefault m_strfilename m_strsection strentry cstring m_strfilename m_strsection strentry strdefault m_chbuffer getlength c string c ini read lpctstr str file name lpctstr str section lpctstr str entry lpctstr str default c string str return get private profile string str section str entry str default str return get buffer set length max ini buffer max ini buffer str file name str return release buffer return str return cstring cini strfilename strsection strentry strdefault cstring strreturn getprivateprofilestring strsection strentry strdefault strreturn getbuffersetlength max_ini_buffer max_ini_buffer strfilename strreturn releasebuffer strreturn void c ini write lpctstr str file name lpctstr str section lpctstr str entry lpctstr str value write private profile string str section str entry str value str file name cini strfilename strsection strentry strvalue writeprivateprofilestring strsection strentry strvalue strfilename cgzip file cgzip file m gzfile 0 cgzipfile cgzipfile m_gzfile bool cgzip file open lpctstr psz file path assert m gzfile 0 close uses conversion m gzfile gzopen t2ca psz file path rb if m gzfile use gzip uncompress only for real gzip compressed files and do not let handle it also uncompressed files this way the open function can be used to check if that file is a gzip file at all if gzdirect m gzfile 0 close else m strgzfilepath psz file path return m gzfile 0 cgzipfile pszfilepath m_gzfile uses_conversion m_gzfile pszfilepath m_gzfile m_gzfile m_strgzfilepath pszfilepath m_gzfile void cgzip file close if m gzfile verify gzclose m gzfile z ok m gzfile 0 m strgzfilepath empty cgzipfile m_gzfile m_gzfile z_ok m_gzfile m_strgzfilepath c string cgzip file get uncompressed file name const return name without path of input file without gz extension c string str uncompressed file name get uncompressed file path if str uncompressed file name is empty skip any possible available directories lpctstr psz file name path find file name str uncompressed file name if psz file name str uncompressed file name psz file name return str uncompressed file name cstring cgzipfile getuncompressedfilename cstring struncompressedfilename getuncompressedfilepath struncompressedfilename isempty pszfilename pathfindfilename struncompressedfilename pszfilename struncompressedfilename pszfilename struncompressedfilename c string cgzip file get uncompressed file path const return path of input file without gz extension c string str uncompressed file path lpctstr psz ext path find extension m strgzfilepath if psz ext null tcsicmp psz ext t gz 0 str uncompressed file path m strgzfilepath path remove extension str uncompressed file path get buffer str uncompressed file path get length str uncompressed file path release buffer return str uncompressed file path cstring cgzipfile getuncompressedfilepath cstring struncompressedfilepath pszext pathfindextension m_strgzfilepath pszext _tcsicmp pszext _t struncompressedfilepath m_strgzfilepath pathremoveextension struncompressedfilepath getbuffer struncompressedfilepath getlength struncompressedfilepath releasebuffer struncompressedfilepath bool cgzip file extract lpctstr psz file path int fd out tsopen psz file path o creat o trunc o wronly o binary sh denywr s iread s iwrite if fd out 1 return false bool b result true const int i buff size 32768 byte puc buff new byte i buff size while gzeof m gzfile int i read gzread m gzfile puc buff i buff size if i read 0 break if i read 0 b result false break if write fd out puc buff i read i read b result false break delete puc buff close fd out if b result tremove psz file path return b result cgzipfile pszfilepath fdout _tsopen pszfilepath _o_creat _o_trunc _o_wronly _o_binary _sh_denywr _s_iread _s_iwrite fdout bresult ibuffsize pucbuff ibuffsize m_gzfile iread m_gzfile pucbuff ibuffsize iread iread bresult fdout pucbuff iread iread bresult pucbuff fdout bresult _tremove pszfilepath bresult cp pg proxy cp pg proxy c property page cp pg proxy idd cppgproxy cppgproxy cpropertypage cppgproxy cp pg proxy cp pg proxy cppgproxy cppgproxy void cp pg proxy load settings uses conversion c button get dlg item idc enableproxy set check proxy use proxy c button get dlg item idc enableauth set check proxy enable password c combo box get dlg item idc proxytype set cur sel proxy type set window texta get dlg item idc proxyname proxy name c string buffer buffer format t u proxy port get dlg item idc proxyport set window text buffer get dlg item idc username a set window text a2t proxy user get dlg item idc password set window text a2t proxy password on bn clicked enable proxy cppgproxy loadsettings uses_conversion cbutton getdlgitem idc_enableproxy setcheck useproxy cbutton getdlgitem idc_enableauth setcheck enablepassword ccombobox getdlgitem idc_proxytype setcursel setwindowtexta getdlgitem idc_proxyname cstring _t getdlgitem idc_proxyport setwindowtext getdlgitem idc_username_a setwindowtext getdlgitem idc_password setwindowtext onbnclickedenableproxy void cp pg proxy do data exchange c data exchange pdx c property page do data exchange pdx cppgproxy dodataexchange cdataexchange cpropertypage dodataexchange bool cp pg proxy on init dialog c property page on init dialog init window styles this proxy the prefs get proxy settings load settings localize return true return true unless you set the focus to a control exception ocx property pages should return false cppgproxy oninitdialog cpropertypage oninitdialog initwindowstyles theprefs getproxysettings loadsettings bool cp pg proxy on apply uses conversion proxy use proxy is dlg button checked idc enableproxy 0 proxy enable password c button get dlg item idc enableauth get check 0 proxy type uint16 c combo box get dlg item idc proxytype get cur sel if get dlg item idc proxyname get window text length c stringa str proxya get window texta get dlg item idc proxyname str proxya get buffer 256 256 str proxya release buffer str proxya free extra int i colon str proxya find if i colon 1 set dlg item texta m hwnd idc proxyport str proxya mid i colon 1 str proxya str proxya left i colon proxy name str proxya else proxy name empty proxy use proxy false if get dlg item idc proxyport get window text length tchar buffer 6 get dlg item idc proxyport get window text buffer countof buffer if proxy port uint16 tstoi buffer 0 proxy port 1080 else proxy port 1080 if get dlg item idc username a get window text length c string str user get dlg item idc username a get window text str user proxy user t2ca str user else proxy user empty proxy enable password false if get dlg item idc password get window text length c string str passwd get dlg item idc password get window text str passwd proxy password t2ca str passwd else proxy password empty proxy enable password false the prefs set proxy settings proxy load settings return true cppgproxy onapply uses_conversion useproxy isdlgbuttonchecked idc_enableproxy enablepassword cbutton getdlgitem idc_enableauth getcheck ccombobox getdlgitem idc_proxytype getcursel getdlgitem idc_proxyname getwindowtextlength cstringa strproxya getwindowtexta getdlgitem idc_proxyname strproxya getbuffer strproxya releasebuffer strproxya freeextra icolon strproxya icolon setdlgitemtexta m_hwnd idc_proxyport strproxya icolon strproxya strproxya icolon strproxya useproxy getdlgitem idc_proxyport getwindowtextlength getdlgitem idc_proxyport getwindowtext _countof _tstoi getdlgitem idc_username_a getwindowtextlength cstring struser getdlgitem idc_username_a getwindowtext struser struser enablepassword getdlgitem idc_password getwindowtextlength cstring strpasswd getdlgitem idc_password getwindowtext strpasswd strpasswd enablepassword theprefs setproxysettings loadsettings bool cp pg proxy on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgproxy oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg proxy on bn clicked enable proxy set modified true c button btn c button get dlg item idc enableproxy get dlg item idc enableauth enable window btn get check 0 get dlg item idc proxytype enable window btn get check 0 get dlg item idc proxyname enable window btn get check 0 get dlg item idc proxyport enable window btn get check 0 get dlg item idc username a enable window btn get check 0 get dlg item idc password enable window btn get check 0 if btn get check 0 on bn clicked enable authentication if btn get check 0 on cbn sel change proxy type cppgproxy onbnclickedenableproxy setmodified cbutton cbutton getdlgitem idc_enableproxy getdlgitem idc_enableauth enablewindow getcheck getdlgitem idc_proxytype enablewindow getcheck getdlgitem idc_proxyname enablewindow getcheck getdlgitem idc_proxyport enablewindow getcheck getdlgitem idc_username_a enablewindow getcheck getdlgitem idc_password enablewindow getcheck getcheck onbnclickedenableauthentication getcheck oncbnselchangeproxytype void cp pg proxy on bn clicked enable authentication set modified true c button btn c button get dlg item idc enableauth get dlg item idc username a enable window btn get check 0 get dlg item idc password enable window btn get check 0 cppgproxy onbnclickedenableauthentication setmodified cbutton cbutton getdlgitem idc_enableauth getdlgitem idc_username_a enablewindow getcheck getdlgitem idc_password enablewindow getcheck void cp pg proxy on cbn sel change proxy type set modified true c combo box cbbox c combo box get dlg item idc proxytype if cbbox get cur sel proxytype socks5 cbbox get cur sel proxytype http10 cbbox get cur sel proxytype http11 c button get dlg item idc enableauth set check 0 on bn clicked enable authentication get dlg item idc enableauth enable window false else get dlg item idc enableauth enable window true cppgproxy oncbnselchangeproxytype setmodified ccombobox ccombobox getdlgitem idc_proxytype getcursel proxytype_socks5 getcursel proxytype_http10 getcursel proxytype_http11 cbutton getdlgitem idc_enableauth setcheck onbnclickedenableauthentication getdlgitem idc_enableauth enablewindow getdlgitem idc_enableauth enablewindow void cp pg proxy on help the app show help emule faq preferences proxy cppgproxy onhelp theapp showhelp emule_faq_preferences_proxy bool cp pg proxy on help info helpinfo p help info on help return true cppgproxy onhelpinfo phelpinfo onhelp m ctrltreeoptions the app m idfltimagelistcolorflags clear all members m_ctrltreeoptions theapp m_idfltimagelistcolorflags clearallmembers cp pg debug cp pg debug cppgdebug cppgdebug void cp pg debug clear all members m binitializedtreeopts false m htiserver null m hticlient null memset m cb 0 sizeof m cb memset m lv 0 sizeof m lv memset m checks 0 sizeof m checks memset m levels 0 sizeof m levels memset m htiinteger 0 sizeof m htiinteger memset m ivalinteger 0 sizeof m ivalinteger cppgdebug clearallmembers m_binitializedtreeopts m_htiserver m_hticlient m_cb m_cb m_lv m_lv m_checks m_checks m_levels m_levels m_htiinteger m_htiinteger m_ivalinteger m_ivalinteger bool cp pg debug on init dialog define set detail opt idx var m checks idx var 0 m levels idx var 0 var var define set integer opt idx var m ivalinteger idx var set detail opt 0 the prefs m idebugservertcplevel set detail opt 1 the prefs m idebugserverudplevel set detail opt 2 the prefs m idebugserversourceslevel set detail opt 3 the prefs m idebugserversearcheslevel set detail opt 4 the prefs m idebugclienttcplevel set detail opt 5 the prefs m idebugclientudplevel set detail opt 6 the prefs m idebugclientkadudplevel set integer opt 0 the prefs m idbgheap undef set opt undef set integer opt m ctrltreeoptions set image list color flags the app m idfltimagelistcolorflags c property page on init dialog init window styles this return true return true unless you set the focus to a control exception ocx property pages should return false cppgdebug oninitdialog set_detail_opt m_checks m_levels set_integer_opt m_ivalinteger set_detail_opt theprefs m_idebugservertcplevel set_detail_opt theprefs m_idebugserverudplevel set_detail_opt theprefs m_idebugserversourceslevel set_detail_opt theprefs m_idebugserversearcheslevel set_detail_opt theprefs m_idebugclienttcplevel set_detail_opt theprefs m_idebugclientudplevel set_detail_opt theprefs m_idebugclientkadudplevel set_integer_opt theprefs m_idbgheap set_opt set_integer_opt m_ctrltreeoptions setimagelistcolorflags theapp m_idfltimagelistcolorflags cpropertypage oninitdialog initwindowstyles bool cp pg debug on apply if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus if update data return false define get detail opt idx opt if m checks idx opt m levels idx 0 m levels idx 1 else opt m levels idx define get integer opt idx opt opt m ivalinteger idx get detail opt 0 the prefs m idebugservertcplevel get detail opt 1 the prefs m idebugserverudplevel get detail opt 2 the prefs m idebugserversourceslevel get detail opt 3 the prefs m idebugserversearcheslevel get detail opt 4 the prefs m idebugclienttcplevel get detail opt 5 the prefs m idebugclientudplevel get detail opt 6 the prefs m idebugclientkadudplevel get integer opt 0 the prefs m idbgheap undef get detail opt undef get integer opt set modified false return c property page on apply cppgdebug onapply m_ctrltreeoptions handlechildcontrollosingfocus updatedata get_detail_opt m_checks m_levels m_levels m_levels get_integer_opt m_ivalinteger get_detail_opt theprefs m_idebugservertcplevel get_detail_opt theprefs m_idebugserverudplevel get_detail_opt theprefs m_idebugserversourceslevel get_detail_opt theprefs m_idebugserversearcheslevel get_detail_opt theprefs m_idebugclienttcplevel get_detail_opt theprefs m_idebugclientudplevel get_detail_opt theprefs m_idebugclientkadudplevel get_integer_opt theprefs m_idbgheap get_detail_opt get_integer_opt setmodified cpropertypage onapply bool cp pg debug on kill active if prop page is closed by pressing enter we have to explicitly commit any possibly pending data from an open edit control m ctrltreeoptions handle child control losing focus return c property page on kill active cppgdebug onkillactive m_ctrltreeoptions handlechildcontrollosingfocus cpropertypage onkillactive void cp pg debug do data exchange c data exchange pdx c property page do data exchange pdx ddx control pdx idc debug opts m ctrltreeoptions if m binitializedtreeopts int i img server 8 default icon int i img client 8 default icon c image list piml m ctrltreeoptions get image list tvsil normal if piml hicon h icon the app load icon t server if h icon i img server piml add h icon verify destroy icon h icon h icon the app load icon t stats clients if h icon i img client piml add h icon verify destroy icon h icon define add detail item idx label group m cb idx m ctrltreeoptions insert check box label group m lv idx m ctrltreeoptions insert item t level treeoptsctrlimg edit treeoptsctrlimg edit m cb idx m ctrltreeoptions add edit box m lv idx runtime class c num tree options edit define add integer item idx label group m htiinteger idx m ctrltreeoptions insert item label treeoptsctrlimg edit treeoptsctrlimg edit group m ctrltreeoptions add edit box m htiinteger idx runtime class c num tree options edit m htiserver m ctrltreeoptions insert check box t server tvi root false add detail item 0 t tcp m htiserver add detail item 1 t udp m htiserver add detail item 2 t sources m htiserver add detail item 3 t searches m htiserver m hticlient m ctrltreeoptions insert check box t client tvi root false add detail item 4 t tcp m hticlient add detail item 5 t udp ed2k m hticlient add detail item 6 t udp kad m hticlient add integer item 0 t memory corruption check level tvi root undef add detail item undef add integer item m ctrltreeoptions expand m htiserver tve expand m ctrltreeoptions expand m hticlient tve expand m ctrltreeoptions send message wm vscroll sb top m binitializedtreeopts true for int i 0 i arrsize m cb i ddx treecheck pdx idc debug opts m cb i m checks i m ctrltreeoptions update check box group m htiserver m ctrltreeoptions update check box group m hticlient for int i 0 i arrsize m lv i ddx treeedit pdx idc debug opts m lv i m levels i for int i 0 i arrsize m htiinteger i ddx treeedit pdx idc debug opts m htiinteger i m ivalinteger i cppgdebug dodataexchange cdataexchange cpropertypage dodataexchange ddx_control idc_debug_opts m_ctrltreeoptions m_binitializedtreeopts iimgserver iimgclient cimagelist m_ctrltreeoptions getimagelist tvsil_normal hicon theapp loadicon _t hicon iimgserver hicon destroyicon hicon hicon theapp loadicon _t statsclients hicon iimgclient hicon destroyicon hicon add_detail_item m_cb m_ctrltreeoptions insertcheckbox m_lv m_ctrltreeoptions insertitem _t treeoptsctrlimg_edit treeoptsctrlimg_edit m_cb m_ctrltreeoptions addeditbox m_lv runtime_class cnumtreeoptionsedit add_integer_item m_htiinteger m_ctrltreeoptions insertitem treeoptsctrlimg_edit treeoptsctrlimg_edit m_ctrltreeoptions addeditbox m_htiinteger runtime_class cnumtreeoptionsedit m_htiserver m_ctrltreeoptions insertcheckbox _t tvi_root add_detail_item _t m_htiserver add_detail_item _t m_htiserver add_detail_item _t m_htiserver add_detail_item _t m_htiserver m_hticlient m_ctrltreeoptions insertcheckbox _t tvi_root add_detail_item _t m_hticlient add_detail_item _t m_hticlient add_detail_item _t m_hticlient add_integer_item _t tvi_root add_detail_item add_integer_item m_ctrltreeoptions m_htiserver tve_expand m_ctrltreeoptions m_hticlient tve_expand m_ctrltreeoptions sendmessage wm_vscroll sb_top m_binitializedtreeopts m_cb ddx_treecheck idc_debug_opts m_cb m_checks m_ctrltreeoptions updatecheckboxgroup m_htiserver m_ctrltreeoptions updatecheckboxgroup m_hticlient m_lv ddx_treeedit idc_debug_opts m_lv m_levels m_htiinteger ddx_treeedit idc_debug_opts m_htiinteger m_ivalinteger bool cp pg debug on command wparam w param lparam l param if w param id help on help return true return super on command w param l param cppgdebug oncommand wparam lparam wparam id_help onhelp __super oncommand wparam lparam void cp pg debug on destroy m ctrltreeoptions delete all items m ctrltreeoptions destroy window clear all members c property page on destroy cppgdebug ondestroy m_ctrltreeoptions deleteallitems m_ctrltreeoptions destroywindow clearallmembers cpropertypage ondestroy lresult cp pg debug on tree opts ctrl notify wparam w param lparam l param if w param idc debug opts treeoptsctrlnotify pton treeoptsctrlnotify l param set modified return 0 cppgdebug ontreeoptsctrlnotify wparam lparam wparam idc_debug_opts lparam setmodified void cp pg debug on help the app show help 0 cppgdebug onhelp theapp showhelp bool cp pg debug on help info helpinfo p help info on help return true cppgdebug onhelpinfo phelpinfo onhelp cics rule info uint16 n port number uint8 by protocol c string str rule name bool b remove on exit false m nportnumber n port number m byprotocol by protocol m strrulename str rule name m bremoveonexit b remove on exit cicsruleinfo nportnumber byprotocol cstring strrulename bremoveonexit m_nportnumber nportnumber m_byprotocol byprotocol m_strrulename strrulename m_bremoveonexit bremoveonexit cics rule info operator const cics rule info ri m nportnumber ri m nportnumber m byprotocol ri m byprotocol m strrulename ri m strrulename m bremoveonexit ri m bremoveonexit return this cicsruleinfo cicsruleinfo m_nportnumber m_nportnumber m_byprotocol m_byprotocol m_strrulename m_strrulename m_bremoveonexit m_bremoveonexit pinger pinger udp start sockaddr in sa for udp and raw sockets icmp must accept all responses sa sin family af inet sa sin addr s addr inaddr any sa sin port 0 udp started false attempt to initialize raw icmp socket is socket af inet sock raw ipproto icmp if is invalid socket int n ret bind is sockaddr sa sizeof sa if n ret socket error n ret wsa get last error closesocket is ignore return value error close anyway else attempt to initialize ordinal udp socket why should this fail nb no need to bind this at a moment will be bound later implicitly at sendto us socket af inet sock dgram ipproto udp if us invalid socket closesocket is ignore return value we need to close it anyway else udp started true udp end open icmp dll hicmp dll load library t icmp dll if hicmp dll 0 the app queue debug log line false t pinger load library failed unable to locate icmp dll return get pointers to icmp dll functions lpfn icmp create file icmp create file get proc address hicmp dll icmp create file lpfn icmp close handle icmp close handle get proc address hicmp dll icmp close handle lpfn icmp send echo icmp send echo get proc address hicmp dll icmp send echo if lpfn icmp create file lpfn icmp close handle lpfn icmp send echo the app queue debug log line false t pinger get proc addr failed for at least one function return open the ping service hicmp handle lpfn icmp create file if hicmp invalid handle value int n err get last error the app queue debug log line false t pinger icmp create file failed err u n err p icmp err n err return init ip info structure stip info tos 0 stip info flags 0 stip info options size 0 stip info options data null sockaddr_in sin_family af_inet sin_addr s_addr inaddr_any sin_port udpstarted af_inet sock_raw ipproto_icmp invalid_socket nret nret socket_error nret wsagetlasterror af_inet sock_dgram ipproto_udp invalid_socket udpstarted hicmp_dll loadlibrary _t hicmp_dll theapp queuedebuglogline _t loadlibrary lpfnicmpcreatefile icmpcreatefile getprocaddress hicmp_dll icmpcreatefile lpfnicmpclosehandle icmpclosehandle getprocaddress hicmp_dll icmpclosehandle lpfnicmpsendecho icmpsendecho getprocaddress hicmp_dll icmpsendecho lpfnicmpcreatefile lpfnicmpclosehandle lpfnicmpsendecho theapp queuedebuglogline _t getprocaddr lpfnicmpcreatefile invalid_handle_value nerr getlasterror theapp queuedebuglogline _t icmpcreatefile nerr picmperr nerr ipinfo stipinfo stipinfo stipinfo optionssize stipinfo optionsdata pinger pinger ud ping reworked cleanup if udp started closesocket is close udp socket closesocket us close raw icmp socket ud ping reworked cleanup end close the icmp handle bool f ret lpfn icmp close handle hicmp if f ret false int n err get last error the app queue debug log line false t error closing icmp handle err u n err p icmp err n err shut down free library hicmp dll udping udpstarted udping fret lpfnicmpclosehandle fret nerr getlasterror theapp queuedebuglogline _t nerr picmperr nerr freelibrary hicmp_dll ping status pinger ping uint32 l addr uint32 ttl bool do log bool use udp if use udp udp started return pingudp l addr ttl do log else return pingicmp l addr ttl do log pingstatus laddr dolog useudp useudp udpstarted laddr dolog laddr dolog void pinger p icmp err int nicmp err int n err index nicmp err ip status base if nicmp err max icmp err string nicmp err ip status base 1 error value is out of range display normally the app queue debug log line false t pinger s get error message nicmp err 1 else display icmp error string the app queue debug log line false t s asz send echo err n err index picmperr nicmperr nerrindex nicmperr ip_status_base nicmperr max_icmp_err_string nicmperr ip_status_base theapp queuedebuglogline _t geterrormessage nicmperr theapp queuedebuglogline _t aszsendechoerr nerrindex ping status pinger pingudp uint32 l addr uint32 ttl bool do log ud ping reworked ping sequence int nttl ttl int n ret sockaddr in sa int n addr len sizeof struct sockaddr in char buficmp 1500 allow full mtu clear icmp socket before sending udp not best solution but may be needed to exclude late responses etc u long bytes2read 0 do n ret ioctlsocket is fionread bytes2read if bytes2read 0 ignore errors here sa sin family af inet sa sin addr s addr inaddr any sa sin port 0 n ret recvfrom is socket lpstr buficmp buffer 1500 length 0 flags sockaddr sa source n addr len addrlen if last time out last time out if last time out to now time out to now time out if to now time out last time out 3 while bytes2read 0 set ttl value for udp packet should success with winsock 2 nb take care about ip ttl value it s redefined in ws2tcpip h todo solve next problem correctly e mule is linking sockets functions using wsock32 lib ip ttl 7 to use ip ttl define we must enforce linker to bind this function to ws2 32 lib ip ttl 4 linker options ignore wsock32 lib n ret setsockopt us ipproto ip ip ttl char nttl sizeof int if n ret socket error dword last error wsa get last error ping status return value return value success false return value delay timeout return value error last error if to now time out 3 to now time out last time out 3 return return value sa sin family af inet sa sin addr s addr l addr sa sin port htons udp port send lonely udp packet with almost minimal content 0 bytes is allowed too but no data will be sent then n ret sendto us lpstr nttl 4 0 sockaddr sa sizeof sa send four bytes ttl c time tick m time m time tick if n ret socket error dword last error wsa get last error ping status return value return value success false return value error last error if to now time out 3 to now time out last time out 3 return return value ip header reply ip header buficmp bytes2read 0 int timeout opt timeout bool no rcv time out false n ret setsockopt is sol socket so rcvtimeo const char timeout opt sizeof timeout opt if n ret socket error no rcv time out true float us res time 0 0f while us res time m time tick timeout if no rcv time out n ret ioctlsocket is fionread bytes2read if n ret 0 dword last error wsa get last error ping status return value return value success false return value delay timeout return value error last error if to now time out 3 to now time out last time out 3 return return value if bytes2read 0 read and filter incoming icmp else sleep 1 share time with other threads continue sa sin family af inet sa sin addr s addr inaddr any sa sin port 0 n ret recvfrom is socket lpstr buficmp buffer 1500 length 0 flags sockaddr sa source n addr len addrlen us res time m time tick if n ret socket error dword last error wsa get last error ping status return value return value success false return value delay timeout return value error last error if to now time out 3 to now time out last time out 3 return return value unsigned short header len reply h len 4 icmp header icmphdr icmp header buficmp header len in addr st dest addr st dest addr s addr reply source ip if icmphdr type icmp ttl expire icmphdr type icmp dest unreach icmphdr udp dest port htons udp port icmphdr hdrsent dest ip l addr ping status return value if icmphdr type icmp ttl expire return value success true return value status ip ttl expired transit return value delay us res time return value destination address st dest addr s addr return value ttl ttl else return value success true return value status ip dest host unreachable return value delay us res time return value destination address st dest addr s addr return value ttl 64 reply ttl 63 if do log the app queue debug log line false t reply udp pinger from s bytes d time 3 2fms ttl i ipstr st dest addr n ret us res time return value ttl return return value else verbose log filtered packets info not seen yet if last time out last time out if last time out to now time out to now time out if to now time out last time out 3 if do log the app queue debug log line false t filtered reply udp pinger from s bytes d time 3 2fms ttl i type i ipstr st dest addr n ret us res time 64 reply ttl 63 icmphdr type if us res time timeout if to now time out 3 to now time out last time out 3 ud ping reworked ping sequence end ping status return value return value success false return value delay timeout return value error ip req timed out return return value pingstatus laddr dolog udping nret sockaddr_in naddrlen sockaddr_in u_long nret sin_family af_inet sin_addr s_addr inaddr_any sin_port nret naddrlen lasttimeout lasttimeout lasttimeout tonowtimeout tonowtimeout tonowtimeout lasttimeout ip_ttl emule ip_ttl ip_ttl ws2_32 ip_ttl nret ipproto_ip ip_ttl nret socket_error lasterror wsagetlasterror pingstatus returnvalue returnvalue returnvalue returnvalue lasterror tonowtimeout tonowtimeout lasttimeout returnvalue sin_family af_inet sin_addr s_addr laddr sin_port udp_port nret ctimetick m_time m_time nret socket_error lasterror wsagetlasterror pingstatus returnvalue returnvalue returnvalue lasterror tonowtimeout tonowtimeout lasttimeout returnvalue ipheader ipheader timeoutopt norcvtimeout nret sol_socket so_rcvtimeo timeoutopt timeoutopt nret socket_error norcvtimeout usrestime usrestime m_time norcvtimeout nret nret lasterror wsagetlasterror pingstatus returnvalue returnvalue returnvalue returnvalue lasterror tonowtimeout tonowtimeout lasttimeout returnvalue sin_family af_inet sin_addr s_addr inaddr_any sin_port nret naddrlen usrestime m_time nret socket_error lasterror wsagetlasterror pingstatus returnvalue returnvalue returnvalue returnvalue lasterror tonowtimeout tonowtimeout lasttimeout returnvalue header_len h_len icmpheader icmpheader header_len in_addr stdestaddr stdestaddr s_addr source_ip icmp_ttl_expire icmp_dest_unreach dest_port udp_port dest_ip laddr pingstatus returnvalue icmp_ttl_expire returnvalue returnvalue ip_ttl_expired_transit returnvalue usrestime returnvalue destinationaddress stdestaddr s_addr returnvalue returnvalue returnvalue ip_dest_host_unreachable returnvalue usrestime returnvalue destinationaddress stdestaddr s_addr returnvalue dolog theapp queuedebuglogline _t stdestaddr nret usrestime returnvalue returnvalue lasttimeout lasttimeout lasttimeout tonowtimeout tonowtimeout tonowtimeout lasttimeout dolog theapp queuedebuglogline _t stdestaddr nret usrestime usrestime tonowtimeout tonowtimeout lasttimeout udping pingstatus returnvalue returnvalue returnvalue returnvalue ip_req_timed_out returnvalue ping status pinger pingicmp uint32 l addr uint32 ttl bool do log ping status return value in addr st dest addr char ach rep data sizeof icmpecho bufsize address is assumed to be ok st dest addr s addr l addr stip info ttl u char ttl c time tick m time m time tick send the icmp echo request and read the reply dword dw reply count lpfn icmp send echo hicmp st dest addr s addr 0 databuffer 0 data len length of databuffer stip info ach rep data sizeof ach rep data timeout float us res time m time tick if dw reply count 0 long ping time u long ach rep data 8 in addr st dest addr st dest addr s addr u long ach rep data return value success true return value status dword ach rep data 4 return value delay m time is performance counter ping time 20 ping time 10 0 ping time 10 us res time us res time 10 ping time us res time ping time return value destination address st dest addr s addr return value ttl return value status ip success ttl char ach rep data 20 0x00ff if do log the app queue debug log line false t reply icmp pinger from s bytes d time 3 2fms 3 2fms ldms ttl i ipstr st dest addr u long ach rep data 12 return value delay m time is performance counter us res time 1 0f u long ach rep data 8 return value ttl else dword last error get last error return value success false return value error last error if do log the app queue debug log line false t error from s error i ipstr st dest addr return value error return return value pingstatus laddr dolog pingstatus returnvalue in_addr stdestaddr achrepdata stdestaddr s_addr laddr stipinfo u_char ctimetick m_time m_time dwreplycount lpfnicmpsendecho stdestaddr s_addr datalen stipinfo achrepdata achrepdata usrestime m_time dwreplycount pingtime u_long achrepdata in_addr stdestaddr stdestaddr s_addr u_long achrepdata returnvalue returnvalue achrepdata returnvalue m_time isperformancecounter pingtime pingtime pingtime usrestime usrestime pingtime usrestime pingtime returnvalue destinationaddress stdestaddr s_addr returnvalue returnvalue ip_success achrepdata dolog theapp queuedebuglogline _t stdestaddr u_long achrepdata returnvalue m_time isperformancecounter usrestime u_long achrepdata returnvalue lasterror getlasterror returnvalue returnvalue lasterror dolog theapp queuedebuglogline _t stdestaddr returnvalue returnvalue c perf log c perf log m emode none m dwinterval min2ms 5 m binitialized false m dwlastsampled 0 m nlastsessionsentbytes 0 m nlastsessionrecvbytes 0 m nlastdnoh 0 m nlastupoh 0 cperflog cperflog m_emode m_dwinterval m_binitialized m_dwlastsampled m_nlastsessionsentbytes m_nlastsessionrecvbytes m_nlastdnoh m_nlastupoh void c perf log startup if m binitialized return set default log file path tchar sz app path max path get module file name null sz app path max path path remove file spec sz app path c string str def file path sz app path str def file path t perflog csv c ini ini the prefs get config file t perf log m emode e log mode ini get int t mode none if m emode none m emode one sample m emode all samples m emode none m dwinterval min2ms ini get int t interval 5 if int m dwinterval 0 m dwinterval min2ms 5 m strfilepath ini get string t file str def file path if m strfilepath is empty m strfilepath str def file path m binitialized true if m emode one sample log samples cperflog m_binitialized szapppath max_path getmodulefilename szapppath max_path pathremovefilespec szapppath cstring strdeffilepath szapppath strdeffilepath _t cini theprefs getconfigfile _t perflog m_emode elogmode getint _t m_emode m_emode onesample m_emode allsamples m_emode m_dwinterval getint _t m_dwinterval m_dwinterval m_strfilepath getstring _t strdeffilepath m_strfilepath isempty m_strfilepath strdeffilepath m_binitialized m_emode onesample logsamples void c perf log shutdown if m emode one sample write samples 0 0 0 0 cperflog m_emode onesample writesamples void c perf log log samples if m emode none return dword dw now get tick count if dw now m dwlastsampled m dwinterval return data counters amount of transferred file data uint n cur dn uint the stats session received bytes m nlastsessionrecvbytes uint n cur up uint the stats session sent bytes m nlastsessionsentbytes overhead counters amount of total overhead uint64 n dnoh total the stats get down data overhead file request the stats get down data overhead source exchange the stats get down data overhead server the stats get down data overhead kad the stats get down data overhead other uint64 n upoh total the stats get up data overhead file request the stats get up data overhead source exchange the stats get up data overhead server the stats get up data overhead kad the stats get up data overhead other uint n cur dnoh uint n dnoh total m nlastdnoh uint n cur upoh uint n upoh total m nlastupoh write samples n cur dn n cur up n cur dnoh n cur upoh m nlastsessionrecvbytes the stats session received bytes m nlastsessionsentbytes the stats session sent bytes m nlastdnoh n dnoh total m nlastupoh n upoh total m dwlastsampled dw now cperflog logsamples m_emode dwnow gettickcount dwnow m_dwlastsampled m_dwinterval ncurdn thestats sessionreceivedbytes m_nlastsessionrecvbytes ncurup thestats sessionsentbytes m_nlastsessionsentbytes ndnohtotal thestats getdowndataoverheadfilerequest thestats getdowndataoverheadsourceexchange thestats getdowndataoverheadserver thestats getdowndataoverheadkad thestats getdowndataoverheadother nupohtotal thestats getupdataoverheadfilerequest thestats getupdataoverheadsourceexchange thestats getupdataoverheadserver thestats getupdataoverheadkad thestats getupdataoverheadother ncurdnoh ndnohtotal m_nlastdnoh ncurupoh nupohtotal m_nlastupoh writesamples ncurdn ncurup ncurdnoh ncurupoh m_nlastsessionrecvbytes thestats sessionreceivedbytes m_nlastsessionsentbytes thestats sessionsentbytes m_nlastdnoh ndnohtotal m_nlastupoh nupohtotal m_dwlastsampled dwnow void c perf log write samples uint n cur dn uint n cur up uint n cur dnoh uint n cur upoh assert m binitialized time t t now time null char sz time 40 do not localize this date time string strftime sz time arrsize sz time m d y h m s localtime t now file fp tfsopen m strfilepath m emode one sample t wt t at sh denywr if fp null log error false t failed to open performance log file s hs m strfilepath strerror errno return setvbuf fp null iofbf 16384 ensure that all lines are written to file with one call if m emode one sample filelength fileno fp 0 fprintf fp pdh csv 4 0 dat down dat up ovr down ovr up n fprintf fp s u u u u n sz time n cur dn n cur up n cur dnoh n cur upoh fclose fp cperflog writesamples ncurdn ncurup ncurdnoh ncurupoh m_binitialized time_t tnow sztime sztime sztime tnow _tfsopen m_strfilepath m_emode onesample _t _t _sh_denywr logerror _t m_strfilepath _iofbf m_emode onesample _filelength datdown datup ovrdown ovrup sztime ncurdn ncurup ncurdnoh ncurupoh c peer cache finder c peer cache finder m dwpcip 0 m pcstatus pcs noinit m pclustate lus none m poscurrentlookup 0 m dwmyip 0 m bvaldited false m bnotrevaldited false m bnotresearched false m ndownloadattempts 0 m nfaileddownloads 0 m npcport 0 cpeercachefinder cpeercachefinder m_dwpcip m_pcstatus pcs_noinit m_pclustate lus_none m_poscurrentlookup m_dwmyip m_bvaldited m_bnotrevaldited m_bnotresearched m_ndownloadattempts m_nfaileddownloads m_npcport c peer cache finder c peer cache finder void cpeercachefinder cpeercachefinder void c peer cache finder init uint32 dw last search bool b last search success bool b enabled uint16 n port if b enabled m pcstatus pcs disabled else if b last search success sanitycheck bool bok false for int i 0 i arrsize an peer cach ports i if an peer cach ports i n port bok true if bok dw last search 0 b last search success false debug only the app queue debug log line false t sanitycheck for peer cache port u failed n port else m npcport n port if dw last search 0 c time last dw last search time t t last safe mktime last get local tm time t t now safe mktime c time get current time get local tm if difftime t now t last 86400 retrydays if b last search success no retry to find the cache m pcstatus pcs notfound m bnotresearched true debug only the app queue debug log line false t peer cache not starting a search last failed search is too near return else no need to revaldite the cache yet m bvaldited true m bnotrevaldited true debug only the app queue debug log line false t peer cache cache ident still valid not trying to revaldite this time else m bnotrevaldited false m bnotresearched false search forpc cpeercachefinder dwlastsearch blastsearchsuccess benabled nport benabled m_pcstatus pcs_disabled blastsearchsuccess anpeercachports anpeercachports nport dwlastsearch blastsearchsuccess debug_only theapp queuedebuglogline _t peercache nport m_npcport nport dwlastsearch ctime dwlastsearch time_t tlast safe_mktime getlocaltm time_t tnow safe_mktime ctime getcurrenttime getlocaltm tnow tlast blastsearchsuccess m_pcstatus pcs_notfound m_bnotresearched debug_only theapp queuedebuglogline _t peercache m_bvaldited m_bnotrevaldited debug_only theapp queuedebuglogline _t peercache cacheident m_bnotrevaldited m_bnotresearched searchforpc void c peer cache finder save if m pcstatus 10 permanent errorrange if m bnotresearched the prefs set peer cache last search mktime c time get current time get local tm the prefs set peer cache was found false the prefs set peer cache port 0 else if m pcstatus pcs ready if m bnotrevaldited the prefs set peer cache last search mktime c time get current time get local tm the prefs set peer cache port m npcport the prefs set peer cache was found true cpeercachefinder m_pcstatus m_bnotresearched theprefs setpeercachelastsearch ctime getcurrenttime getlocaltm theprefs setpeercachewasfound theprefs setpeercacheport m_pcstatus pcs_ready m_bnotrevaldited theprefs setpeercachelastsearch ctime getcurrenttime getlocaltm theprefs setpeercacheport m_npcport theprefs setpeercachewasfound void c peer cache finder found my publicip address uint32 dwip m dwmyip dwip if m pcstatus pcs ownipunknown m pcstatus pcs doinglookups search forpc cpeercachefinder foundmypublicipaddress m_dwmyip m_pcstatus pcs_ownipunknown m_pcstatus pcs_doinglookups searchforpc bool c peer cache finder is cache available const if m ndownloadattempts 20 m nfaileddownloads 0 if float m ndownloadattempts m nfaileddownloads float 2 return false return m pcstatus pcs ready the app get publicip 0 m npcport 0 cpeercachefinder iscacheavailable m_ndownloadattempts m_nfaileddownloads m_ndownloadattempts m_nfaileddownloads m_pcstatus pcs_ready theapp getpublicip m_npcport void c peer cache finder download attempt failed m nfaileddownloads if m ndownloadattempts 20 m nfaileddownloads 0 debug only add debug log line dlp low false t peer cache fail value 0 2f float m ndownloadattempts m nfaileddownloads if float m ndownloadattempts m nfaileddownloads float 2 add debug log line dlp low false t peer cache fail value too high disabling cache downloads cpeercachefinder downloadattemptfailed m_nfaileddownloads m_ndownloadattempts m_nfaileddownloads debug_only adddebuglogline dlp_low _t peercache m_ndownloadattempts m_nfaileddownloads m_ndownloadattempts m_nfaileddownloads adddebuglogline dlp_low _t peercache void c peer cache finder add banned version c client version info cvi version thread safe due to logic this is not really needed at this time because noone will access the list while the valdite thread is running but better to be on the safe side in case the code changes c single lock lock m settingsmutex true li banned versions add cvi version cpeercachefinder addbannedversion cclientversioninfo cviversion valditethread csinglelock m_settingsmutex libannedversions cviversion void c peer cache finder add allowed version c client version info cvi version c single lock lock m settingsmutex true li allowed versions add cvi version cpeercachefinder addallowedversion cclientversioninfo cviversion csinglelock m_settingsmutex liallowedversions cviversion bool c peer cache finder is clientpc compatible uint32 dw tag version info uint n client soft return is clientpc compatible c client version info dw tag version info n client soft cpeercachefinder isclientpccompatible dwtagversioninfo nclientsoft isclientpccompatible cclientversioninfo dwtagversioninfo nclientsoft bool c peer cache finder is clientpc compatible const c client version info cvi to check c single lock lock m settingsmutex true for int i 0 i li allowed versions get size i if cvi to check li allowed versions i return false for int i 0 i li banned versions get size i if cvi to check li banned versions i return false return true cpeercachefinder isclientpccompatible cclientversioninfo cvitocheck csinglelock m_settingsmutex liallowedversions getsize cvitocheck liallowedversions libannedversions getsize cvitocheck libannedversions lresult c peer cache finder on peer cache check response wparam w param lparam l param if m pclustate lus myhostname if wsagetasyncerror l param 0 int i buf len wsagetasyncbuflen l param if i buf len sizeof hostent lphostent p host lphostent acdnsbuffer m strmyhostname p host h name if m strmyhostname is empty debug only add debug log line false t peer cache found my hostname s continue search m strmyhostname search forpc return 0 m pcstatus pcs notfound debug only add debug log line false t dns reverse lookup for own ip failed aborting pc search else if wsagetasyncerror l param 0 int i buf len wsagetasyncbuflen l param if i buf len sizeof hostent lphostent p host lphostent acdnsbuffer if p host h length 4 p host h addr list p host h addr list 0 m dwpcip lpin addr p host h addr list 0 s addr debug only add debug log line false t found peer cache ip s ipstr m dwpcip m pclustate lus finished search forpc return 0 no luck continue search debug only add debug log line false t dns lookup for pc state i failed pc not found yet m pclustate search forpc return 0 cpeercachefinder onpeercachecheckresponse wparam lparam m_pclustate lus_myhostname lparam ibuflen lparam ibuflen phost _acdnsbuffer m_strmyhostname phost h_name m_strmyhostname isempty debug_only adddebuglogline _t peercache m_strmyhostname searchforpc m_pcstatus pcs_notfound debug_only adddebuglogline _t lparam ibuflen lparam ibuflen phost _acdnsbuffer phost h_length phost h_addr_list phost h_addr_list m_dwpcip lpin_addr phost h_addr_list s_addr debug_only adddebuglogline _t peercache m_dwpcip m_pclustate lus_finished searchforpc debug_only adddebuglogline _t m_pclustate searchforpc void c peer cache finder do reverse look up uint32 dwip cpc reverse dns thread p thread cpc reverse dns thread afx begin thread runtime class cpc reverse dns thread thread priority below normal 0 create suspended p thread m dwip dwip p thread m hwndasyncresult the app emuledlg m hwnd p thread resume thread cpeercachefinder doreverselookup cpcreversednsthread pthread cpcreversednsthread afxbeginthread runtime_class cpcreversednsthread thread_priority_below_normal create_suspended pthread m_dwip pthread m_hwndasyncresult theapp m_hwnd pthread resumethread void c peer cache finder search forpc switch m pcstatus case pcs noinit m pcstatus pcs doinglookups case pcs doinglookups switch m pclustate case lus none ok lets start base pos first m pclustate lus basepclocation do look up pcbaselocation break case lus basepclocation so the first lookup failed now we need our hostname if m dwmyip 0 we have to wait until we now our ip for a reverse lookup m pcstatus pcs ownipunknown break m pclustate lus myhostname do reverse look up m dwmyip break case lus myhostname we should have found the hostname and now start to contruct sublocations to lookup m pclustate lus extpclocation m poscurrentlookup 0 case lus extpclocation assert m strmyhostname is empty build string m poscurrentlookup m strmyhostname find m poscurrentlookup 1 if m poscurrentlookup 1 m poscurrentlookup 1 m strmyhostname get length m strmyhostname find m poscurrentlookup 1 1 failed m pclustate lus none m pcstatus pcs notfound else do look up pcbaselocation c stringa m strmyhostname mid m poscurrentlookup 1 break case lus finished if m dwmyip 0 we have to wait until we now our ip for a reverse lookup m pcstatus pcs ownipunknown break if m bvaldited m pcstatus pcs valditing valdite descriptor file else debug only the app queue log line false get res string ids peercache enabled m pcstatus pcs ready break break cpeercachefinder searchforpc m_pcstatus pcs_noinit m_pcstatus pcs_doinglookups pcs_doinglookups m_pclustate lus_none m_pclustate lus_basepclocation dolookup lus_basepclocation m_dwmyip m_pcstatus pcs_ownipunknown m_pclustate lus_myhostname doreverselookup m_dwmyip lus_myhostname m_pclustate lus_extpclocation m_poscurrentlookup lus_extpclocation m_strmyhostname isempty m_poscurrentlookup m_strmyhostname m_poscurrentlookup m_poscurrentlookup m_poscurrentlookup m_strmyhostname getlength m_strmyhostname m_poscurrentlookup m_pclustate lus_none m_pcstatus pcs_notfound dolookup cstringa m_strmyhostname m_poscurrentlookup lus_finished m_dwmyip m_pcstatus pcs_ownipunknown m_bvaldited m_pcstatus pcs_valditing valditedescriptorfile debug_only theapp queuelogline getresstring ids_peercache_enabled m_pcstatus pcs_ready void c peer cache finder valdite descriptor file cpc valdite thread p valdite thread cpc valdite thread afx begin thread runtime class cpc valdite thread thread priority below normal 0 create suspended p valdite thread set values this m dwpcip m dwmyip p valdite thread resume thread cpeercachefinder valditedescriptorfile cpcvalditethread pvalditethread cpcvalditethread afxbeginthread runtime_class cpcvalditethread thread_priority_below_normal create_suspended pvalditethread setvalues m_dwpcip m_dwmyip pvalditethread resumethread cpc valdite thread cpc valdite thread cpcvalditethread cpcvalditethread cpc valdite thread cpc valdite thread cpcvalditethread cpcvalditethread bool cpc valdite thread valdite assert m dwpcip 0 assert m dwmyip 0 c internet session session c internet file file null for int i 0 i arrsize an peer cach ports i try try to connect to the url c string strurl strurl format t http s u p2pinfo ipstr m dwpcip an peer cach ports i file c internet file session openurl strurl m npcport an peer cach ports i break catch c internet exception p exception set file to null if there s an error file null c string str error p exception get error message str error get buffer 512 512 str error release buffer str error trim t r n p exception delete debug only the app queue debug log line false t peer cache failed to retrieve p2pinfo file on port u s an peer cach ports i str error if i arrsize an peer cach ports 1 was last try debug only the app queue debug log line false t peer cache failed to retrieve p2pinfo file cache disabled an peer cach ports i return false assert file null todo this will work successfully only for very small files which were received completely right at the time the get length function is called use a polling loop which reads everything up to get bytes specified in content length or some other appropriate limit in case content length is missing uint32 ni file size uint file get length assert ni file size signaturelength if file ni file size signaturelength read content c array uint32 uint32 adw cachei ps c stringa array astrip ranges c stringa str line bool b content check failed false uint u content size ni file size signaturelength char pc content new char u content size 1 if file read pc content u content size u content size debug only the app queue debug log line false t peer cache failed to read p2pinfo file content pc content u content size 0 checking p2pinfo content note pc content gets destroyed with strtok lpstr psz line strtok pc content r n while psz line b content check failed str line psz line int pos seperator str line find 1 if pos seperator 1 str line get length pos seperator 1 c stringa str topic str line left pos seperator trim c stringa str content str line mid pos seperator 1 trim debug only the app queue debug log line false t peer cache current line to be processed hs str line cacheip if str topic cacheip adw cachei ps add inet addr str content clientip range else if str topic clientip range astrip ranges add str content expire date else if str topic expire date bool b date check failed true if str content get length 8 uint32 n year atol str content mid 0 4 uint32 n month atol str content mid 4 2 uint32 n day atol str content mid 6 2 if n year 3000 n month 12 n day 31 c time time expire date n year n month n day 0 0 0 if time expire date c time get current time b date check failed false check passed if b date check failed b content check failed true debug only the app queue debug log line false t peer cache expire date check failed expiring date hs str content enableed2k else if str topic enableed2k if atol str content 1 b content check failed true debug only the app queue debug log line false t peer cache enableed2k check failed value hs str content else debug only the app queue debug log line false t peer cache unused content tag for validity check hs str line psz line strtok null r n finish the cacheip check bool bip range check failed true for int i 0 i adw cachei ps get count i if adw cachei ps i m dwpcip bip range check failed false break if bip range check failed b content check failed true debug only the app queue debug log line false t peer cache cacheip check failed finish the range chack bool bip check failed true for int i 0 i astrip ranges get count i c stringa str cur range astrip ranges i int pos content seperator str cur range find 7 if pos content seperator 1 str cur range get length pos content seperator 7 uint32 dwip range start inet addr str cur range left pos content seperator trim uint32 dwip range end inet addr str cur range mid pos content seperator 1 trim if dwip range start inaddr none dwip range end inaddr none if ntohl dwip range start ntohl m dwmyip ntohl dwip range end ntohl m dwmyip bip check failed false check passed if bip check failed b content check failed true debug only the app queue debug log line false t peer cache clientip range check failed my ip s ipstr m dwmyip checking special headers content char ach buffer 3072 3kb should be enough for headers dword n buffer size sizeof ach buffer if b content check failed http query info file http query raw headers crlf ach buffer n buffer size null c stringa str headers ach buffer int n header pos 0 c stringa str cur header str headers tokenize r n n header pos while str cur header is empty int pos seperator str cur header find 1 if pos seperator 1 str cur header get length pos seperator 1 c stringa str topic str cur header left pos seperator trim c stringa str content str cur header mid pos seperator 1 trim debug only the app queue debug log line false t peer cache current header to be processed hs str cur header x e mule require version if str topic x e mule require version int cur pos 0 c string strpc encoded version str content c string str version strpc encoded version tokenize t cur pos while str version is empty m powner add allowed version c client version info str version str version strpc encoded version tokenize t cur pos x e mule reject version else if str topic x e mule reject version int cur pos 0 c string strpc encoded version str content c string str version strpc encoded version tokenize t cur pos while str version is empty m powner add banned version c client version info str version str version strpc encoded version tokenize t cur pos str cur header str headers tokenize r n n header pos own version check if m powner is clientpc compatible c client version info cemule app m nversionmjr cemule app m nversionmin cemule app m nversionupd cemule app m nversionbld so emule b content check failed true debug only the app queue debug log line false t peer cache current version not allowed to use this pc server please update else if b content check failed debug only the app queue debug log line false t peer cache error failed to retrieve headers errornumber s get error message get last error checking p2pinfo signature bool b signature check result false if b content check failed uchar pach complete file new uchar ni file size file seek to begin if file read pach complete file ni file size ni file size assert false b signature check result false else using namespace cryptopp integer e m n e 3 n decode achverify key arrsize achverify key uchar auc signature signaturelength for int i 0 i signaturelength i auc signature signaturelength 1 i pach complete file ni file size signaturelength i m decode auc signature signaturelength rsa function rsa rsa set public exponent e rsa set modulus n integer result rsa apply function m uchar auc result signaturelength if result encode auc result signaturelength uchar auc hash1 16 for int i 0 i 16 i auc hash1 i auc result signaturelength 1 i b signature check result md4cmp md5 sum pach complete file ni file size signaturelength get raw hash auc hash1 0 delete pach complete file if b signature check result debug only the app queue debug log line false t peer cache failed to verify peer cache server not using it delete pc content file close delete file return b signature check result b content check failed return false cpcvalditethread m_dwpcip m_dwmyip cinternetsession cinternetfile anpeercachports cstring _t m_dwpcip anpeercachports cinternetfile m_npcport anpeercachports cinternetexception pexception cstring strerror pexception geterrormessage strerror getbuffer strerror releasebuffer strerror _t pexception debug_only theapp queuedebuglogline _t peercache anpeercachports strerror anpeercachports debug_only theapp queuedebuglogline _t peercache anpeercachports getlength nifilesize getlength nifilesize nifilesize carray adwcacheips cstringaarray astripranges cstringa strline bcontentcheckfailed ucontentsize nifilesize pccontent ucontentsize pccontent ucontentsize ucontentsize debug_only theapp queuedebuglogline _t peercache pccontent ucontentsize pccontent pszline pccontent pszline bcontentcheckfailed strline pszline posseperator strline posseperator strline getlength posseperator cstringa strtopic strline posseperator cstringa strcontent strline posseperator debug_only theapp queuedebuglogline _t peercache strline strtopic adwcacheips inet_addr strcontent clientiprange strtopic clientiprange astripranges strcontent expiredate strtopic expiredate bdatecheckfailed strcontent getlength nyear strcontent nmonth strcontent nday strcontent nyear nmonth nday ctime timeexpiredate nyear nmonth nday timeexpiredate ctime getcurrenttime bdatecheckfailed bdatecheckfailed bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache expiredate strcontent strtopic strcontent bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache strcontent debug_only theapp queuedebuglogline _t peercache strline pszline biprangecheckfailed adwcacheips getcount adwcacheips m_dwpcip biprangecheckfailed biprangecheckfailed bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache rangechack bipcheckfailed astripranges getcount cstringa strcurrange astripranges poscontentseperator strcurrange poscontentseperator strcurrange getlength poscontentseperator dwiprangestart inet_addr strcurrange poscontentseperator dwiprangeend inet_addr strcurrange poscontentseperator dwiprangestart inaddr_none dwiprangeend inaddr_none dwiprangestart m_dwmyip dwiprangeend m_dwmyip bipcheckfailed bipcheckfailed bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache clientiprange m_dwmyip achbuffer nbuffersize achbuffer bcontentcheckfailed httpqueryinfo http_query_raw_headers_crlf achbuffer nbuffersize cstringa strheaders achbuffer nheaderpos cstringa strcurheader strheaders nheaderpos strcurheader isempty posseperator strcurheader posseperator strcurheader getlength posseperator cstringa strtopic strcurheader posseperator cstringa strcontent strcurheader posseperator debug_only theapp queuedebuglogline _t peercache strcurheader emule strtopic emule curpos cstring strpcencodedversion strcontent cstring strversion strpcencodedversion _t curpos strversion isempty m_powner addallowedversion cclientversioninfo strversion strversion strpcencodedversion _t curpos emule strtopic emule curpos cstring strpcencodedversion strcontent cstring strversion strpcencodedversion _t curpos strversion isempty m_powner addbannedversion cclientversioninfo strversion strversion strpcencodedversion _t curpos strcurheader strheaders nheaderpos m_powner isclientpccompatible cclientversioninfo cemuleapp m_nversionmjr cemuleapp m_nversionmin cemuleapp m_nversionupd cemuleapp m_nversionbld so_emule bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache bcontentcheckfailed debug_only theapp queuedebuglogline _t peercache geterrormessage getlasterror bsignaturecheckresult bcontentcheckfailed pachcompletefile nifilesize seektobegin pachcompletefile nifilesize nifilesize bsignaturecheckresult achverify_key achverify_key aucsignature aucsignature pachcompletefile nifilesize aucsignature rsafunction setpublicexponent setmodulus applyfunction aucresult aucresult auchash1 auchash1 aucresult bsignaturecheckresult md5sum pachcompletefile nifilesize getrawhash auchash1 pachcompletefile bsignaturecheckresult debug_only theapp queuedebuglogline _t peercache peercache pccontent bsignaturecheckresult bcontentcheckfailed bool cpc valdite thread init instance dbg set thread name pc valdite thread init thread locale return true cpcvalditethread initinstance dbgsetthreadname pcvalditethread initthreadlocale bool cpc valdite thread run if the app emuledlg null the app emuledlg is running if valdite m powner m bvaldited true m powner m npcport m npcport if m powner m pcstatus pcs valditing debug only the app queue debug log line false t peer cache valditing p2pinfo succeeded debug only the app queue log line false get res string ids peercache enabled m powner m pcstatus pcs ready else assert false else m powner m bvaldited false m powner m pcstatus pcs notverified m powner m npcport 0 return 0 cpcvalditethread theapp theapp isrunning m_powner m_bvaldited m_powner m_npcport m_npcport m_powner m_pcstatus pcs_valditing debug_only theapp queuedebuglogline _t peercache debug_only theapp queuelogline getresstring ids_peercache_enabled m_powner m_pcstatus pcs_ready m_powner m_bvaldited m_powner m_pcstatus pcs_notverified m_powner m_npcport void cpc valdite thread set values c peer cache finder in powner uint32 dwpcip uint32 dw myip m dwpcip dwpcip m dwmyip dw myip m powner in powner cpcvalditethread setvalues cpeercachefinder in_powner dwmyip m_dwpcip m_dwmyip dwmyip m_powner in_powner bool cpc reverse dns thread init instance assert m hwndasyncresult null assert m dwip 0 init thread locale memset acdnsbuffer 0 sizeof acdnsbuffer c string str hostname reverse dns lookup m dwip uint u buf len 0 uint u error wsaeinval if str hostname is empty c stringa str hostnamea str hostname u buf len sizeof hostent hostent structure sizeof char h aliases list nul entry sizeof dword 2 h addr list nul entry str hostnamea get length 1 if u buf len sizeof acdnsbuffer lphostent p host lphostent acdnsbuffer char p char p host 1 p host h aliases char p p host h aliases 0 char null p sizeof char p host h addrtype af inet p host h length sizeof dword p host h addr list char p p host h addr list 0 char m dwip p host h addr list 1 char null p sizeof char 2 p host h name p strcpy p host h name str hostnamea p str hostnamea get length 1 assert uint p acdnsbuffer u buf len u error 0 else u error wsaenobufs verify post message m hwndasyncresult um peerchache response 0 wsamakeasyncreply u buf len u error else in addr ip host fixme unable to resolve my own host will always get the windows computer domainname dunno how to avoid this cheap walk arround below by using another ip ip host s addr ntohl ntohl m dwip 1 if wsa async get host by addr the app emuledlg m hwnd um peerchache response const char ip host sizeof struct in addr af inet acdnsbuffer sizeof acdnsbuffer 0 if the prefs get verbose debug only the app queue debug log line false t dns reverse lookup for own ip failed return false cpcreversednsthread initinstance m_hwndasyncresult m_dwip initthreadlocale _acdnsbuffer _acdnsbuffer cstring strhostname reversednslookup m_dwip ubuflen uerror strhostname isempty cstringa strhostnamea strhostname ubuflen h_aliases h_addr_list strhostnamea getlength ubuflen _acdnsbuffer phost _acdnsbuffer phost phost h_aliases phost h_aliases phost h_addrtype af_inet phost h_length phost h_addr_list phost h_addr_list m_dwip phost h_addr_list phost h_name phost h_name strhostnamea strhostnamea getlength _acdnsbuffer ubuflen uerror uerror postmessage m_hwndasyncresult um_peerchache_response ubuflen uerror in_addr iphost iphost s_addr m_dwip wsaasyncgethostbyaddr theapp m_hwnd um_peerchache_response iphost in_addr af_inet _acdnsbuffer _acdnsbuffer theprefs getverbose debug_only theapp queuedebuglogline _t int c part file convert scan folder to add c string folder bool deletesource int count 0 c file find finder bool b working b working finder find file folder t part met while b working b working finder find next file convert toe mule finder get file path deletesource count shareaza b working finder find file folder t sd while b working b working finder find next file convert toe mule finder get file path deletesource count b working finder find file folder t while b working b working finder find next file c string test finder get file path if finder is directory finder get file name left 1 scan folder to add finder get file path deletesource return count cpartfileconvert scanfoldertoadd cstring cfilefind bworking bworking findfile _t bworking bworking findnextfile converttoemule getfilepath bworking findfile _t bworking bworking findnextfile converttoemule getfilepath bworking findfile _t bworking bworking findnextfile cstring getfilepath isdirectory getfilename scanfoldertoadd getfilepath void c part file convert convert toe mule c string folder bool deletesource if path file exists folder return if folder left strlen the prefs get temp dir compare no case the prefs get temp dir 0 return convert job newjob new convert job newjob folder folder newjob remove source deletesource newjob state conv queue m jobs add tail newjob if m convertgui m convertgui add job newjob start thread cpartfileconvert converttoemule cstring pathfileexists theprefs gettempdir comparenocase theprefs gettempdir convertjob convertjob removesource conv_queue m_jobs addtail m_convertgui m_convertgui addjob startthread void c part file convert start thread if convert pf thread null convert pf thread afx begin thread run null cpartfileconvert startthread convertpfthread convertpfthread afxbeginthread void c part file convert showgui if m convertgui m convertgui set foreground window else m convertgui new c part file convert dlg m convertgui create idd convertpartfiles c wnd get desktop window init window styles m convertgui m convertgui show window sw show m convertgui add anchor idc conv pb current top left top right m convertgui add anchor idc curjob top left top right m convertgui add anchor idc conv pb label top left top right m convertgui add anchor idc conv prozent top right m convertgui add anchor idc joblist top left bottom right m convertgui add anchor idc additem bottom left m convertgui add anchor idc retry bottom left m convertgui add anchor idc convremove bottom left m convertgui add anchor idc hideconvdlg bottom right m convertgui set icon m convertgui m icnwnd the app load icon t convert false init gui m convertgui pb current set range 0 100 m convertgui joblist set extended style lvs ex fullrowselect m convertgui joblist modify style lvs singlesel 0 if pfconverting null updategui pfconverting updategui 50 get res string ids imp fetchstatus true localize fill joblist convert job job for position pos m jobs get head position pos null m jobs get next pos job m jobs get at pos m convertgui add job job updategui job cpartfileconvert m_convertgui m_convertgui setforegroundwindow m_convertgui cpartfileconvertdlg m_convertgui idd_convertpartfiles cwnd getdesktopwindow initwindowstyles m_convertgui m_convertgui showwindow sw_show m_convertgui addanchor idc_conv_pb_current top_left top_right m_convertgui addanchor idc_curjob top_left top_right m_convertgui addanchor idc_conv_pb_label top_left top_right m_convertgui addanchor idc_conv_prozent top_right m_convertgui addanchor idc_joblist top_left bottom_right m_convertgui addanchor idc_additem bottom_left m_convertgui addanchor idc_retry bottom_left m_convertgui addanchor idc_convremove bottom_left m_convertgui addanchor idc_hideconvdlg bottom_right m_convertgui seticon m_convertgui m_icnwnd theapp loadicon _t m_convertgui pb_current setrange m_convertgui setextendedstyle lvs_ex_fullrowselect m_convertgui modifystyle lvs_singlesel getresstring ids_imp_fetchstatus convertjob m_jobs getheadposition m_jobs getnext m_jobs getat m_convertgui addjob void c part file convert updategui float percent c string text bool fullinfo if m convertgui null return m convertgui pb current set pos int percent c string buffer buffer format t 2f percent m convertgui set dlg item text idc conv prozent buffer if text is empty m convertgui set dlg item text idc conv pb label text if fullinfo m convertgui set dlg item text idc curjob pfconverting folder cpartfileconvert cstring m_convertgui m_convertgui pb_current setpos cstring _t m_convertgui setdlgitemtext idc_conv_prozent isempty m_convertgui setdlgitemtext idc_conv_pb_label m_convertgui setdlgitemtext idc_curjob void c part file convert updategui convert job job if m convertgui null return m convertgui update job info job cpartfileconvert convertjob m_convertgui m_convertgui updatejobinfo void c part file convert closegui if m convertgui null return m convertgui destroy window closedgui cpartfileconvert m_convertgui m_convertgui destroywindow void c part file convert closedgui m convertgui null cpartfileconvert m_convertgui void c part file convert remove all jobs for position pos m jobs get head position pos null m jobs get next pos if m convertgui m convertgui remove job m jobs get at pos delete m jobs get at pos m jobs remove all cpartfileconvert removealljobs m_jobs getheadposition m_jobs getnext m_convertgui m_convertgui removejob m_jobs getat m_jobs getat m_jobs removeall void c part file convert remove all succ jobs for position pos m jobs get head position pos null m jobs get next pos convert job del m jobs get at pos if del state conv ok if m convertgui m convertgui remove job del m jobs remove at pos delete del cpartfileconvert removeallsuccjobs m_jobs getheadposition m_jobs getnext convertjob m_jobs getat conv_ok m_convertgui m_convertgui removejob m_jobs removeat void c part file convert remove job convert job job for position pos m jobs get head position pos null m jobs get next pos convert job del m jobs get at pos if del job if m convertgui m convertgui remove job del m jobs remove at pos delete del if m jobs get count 0 return cpartfileconvert removejob convertjob m_jobs getheadposition m_jobs getnext convertjob m_jobs getat m_convertgui m_convertgui removejob m_jobs removeat m_jobs getcount c string c part file convert get returncode text int ret switch ret case conv ok return get res string ids dl transfcompl case conv inprogress return get res string ids imp inprogr case conv outofdiskspace return get res string ids imp err disksp case conv partmetnotfound return get res string ids imp err partmetio case conv ioerror return get res string ids imp err io case conv failed return get res string ids imp err failed case conv queue return get res string ids imp statusqueued case conv alreadyexists return get res string ids imp alrdwl case conv badformat return get res string ids imp err badformat default return t cstring cpartfileconvert getreturncodetext conv_ok getresstring ids_dl_transfcompl conv_inprogress getresstring ids_imp_inprogr conv_outofdiskspace getresstring ids_imp_err_disksp conv_partmetnotfound getresstring ids_imp_err_partmetio conv_ioerror getresstring ids_imp_err_io conv_failed getresstring ids_imp_err_failed conv_queue getresstring ids_imp_statusqueued conv_alreadyexists getresstring ids_imp_alrdwl conv_badformat getresstring ids_imp_err_badformat _t void c part file convert localize if m convertgui return for int i 0 i 4 i m convertgui joblist delete column 0 m convertgui joblist insert column 0 get res string ids dl filename lvcfmt left 350 0 m convertgui joblist insert column 1 get res string ids status lvcfmt left 110 1 m convertgui joblist insert column 2 get res string ids dl size lvcfmt left 150 2 m convertgui joblist insert column 3 get res string ids filehash lvcfmt left 150 3 set gui labels m convertgui set dlg item text idc additem get res string ids imp addbtn m convertgui set dlg item text idc retry get res string ids imp retrybtn m convertgui set dlg item text idc convremove get res string ids imp removebtn m convertgui set dlg item text idc hideconvdlg get res string ids fd close m convertgui set window text get res string ids importsplpf cpartfileconvert m_convertgui m_convertgui deletecolumn m_convertgui insertcolumn getresstring ids_dl_filename lvcfmt_left m_convertgui insertcolumn getresstring ids_status lvcfmt_left m_convertgui insertcolumn getresstring ids_dl_size lvcfmt_left m_convertgui insertcolumn getresstring ids_filehash lvcfmt_left m_convertgui setdlgitemtext idc_additem getresstring ids_imp_addbtn m_convertgui setdlgitemtext idc_retry getresstring ids_imp_retrybtn m_convertgui setdlgitemtext idc_convremove getresstring ids_imp_removebtn m_convertgui setdlgitemtext idc_hideconvdlg getresstring ids_fd_close m_convertgui setwindowtext getresstring ids_importsplpf if pfconverting partmettype pmt splitted try c byte array ba ba set size partsize c file inputfile int pos1 pos2 c string filename just count uint maxindex 0 uint partfilecount 0 b working finder find file folder t filepartindex t part while b working b working finder find next file partfilecount buffer finder get file name pos1 buffer find pos2 buffer find pos1 1 fileindex tstoi buffer mid pos1 1 pos2 pos1 if fileindex 0 continue if fileindex maxindex maxindex fileindex float stepperpart if partfilecount 0 stepperpart 80 0f partfilecount if uint64 maxindex partsize pfconverting size pfconverting spaceneeded uint64 maxindex partsize else pfconverting spaceneeded uint64 pfconverting size partsize partsize pfconverting size partsize else stepperpart 80 0f pfconverting spaceneeded 0 updategui pfconverting if get free disk spacex the prefs get temp dir uint64 maxindex partsize delete file return conv outofdiskspace create new partmetfile and remember the new name file create part file newfilename file get full name updategui 8 get res string ids imp stepcrdestfile file m hpartfile set length pfconverting spaceneeded uint16 curindex 0 b working finder find file folder t filepartindex t part while b working b working finder find next file stats curindex buffer format get res string ids imp loaddata curindex partfilecount updategui 10 curindex stepperpart buffer filename finder get file name pos1 filename find pos2 filename find pos1 1 fileindex tstoi filename mid pos1 1 pos2 pos1 if fileindex 0 continue uint32 chunkstart uint32 fileindex 1 partsize open read data of the part part file into buffer close file inputfile open finder get file path c file mode read c file share deny write uint32 readed inputfile read ba get data partsize inputfile close buffer format get res string ids imp savedata curindex partfilecount updategui 10 curindex stepperpart buffer write the buffered data file m hpartfile seek chunkstart c file begin file m hpartfile write ba get data readed pmt_splitted cbytearray setsize cfile cstring bworking findfile _t _t bworking bworking findnextfile getfilename _tstoi getfreediskspacex theprefs gettempdir conv_outofdiskspace createpartfile getfullname getresstring ids_imp_stepcrdestfile m_hpartfile setlength bworking findfile _t _t bworking bworking findnextfile getresstring ids_imp_loaddata getfilename _tstoi getfilepath cfile moderead cfile sharedenywrite getdata getresstring ids_imp_savedata m_hpartfile cfile m_hpartfile getdata uint afx cdecl c part file convert run lpvoid lp param dbg set thread name partfile converter init thread locale int imported 0 for search next queued job and start it pfconverting null for position pos m jobs get head position pos null m jobs get next pos pfconverting m jobs get at pos if pfconverting state conv queue break else pfconverting null if pfconverting null pfconverting state conv inprogress updategui pfconverting pfconverting state perform convert toe mule pfconverting folder if pfconverting state conv ok imported updategui pfconverting add log line true get res string ids imp status pfconverting folder get returncode text pfconverting state else break nothing more to do now clean up updategui null if imported the app sharedfiles publish next turn convert pf thread null return 0 afx_cdecl cpartfileconvert lpparam dbgsetthreadname initthreadlocale m_jobs getheadposition m_jobs getnext m_jobs getat conv_queue conv_inprogress performconverttoemule conv_ok addlogline getresstring ids_imp_status getreturncodetext theapp publishnextturn convertpfthread c resizable dialog c part file convert dlg idd p parent m pparent p parent m icnwnd null cresizabledialog cpartfileconvertdlg pparent m_pparent pparent m_icnwnd c part file convert dlg c part file convert dlg if m icnwnd verify destroy icon m icnwnd cpartfileconvertdlg cpartfileconvertdlg m_icnwnd destroyicon m_icnwnd void c part file convert dlg add job convert job job int ix joblist insert item lvif text lvif param joblist get item count job folder 0 0 0 lparam job joblist set item text ix 1 c part file convert get returncode text job state cpartfileconvertdlg addjob convertjob insertitem lvif_text lvif_param getitemcount setitemtext cpartfileconvert getreturncodetext void c part file convert dlg remove job convert job job search jobitem in listctrl lvfindinfo find find flags lvfi param find l param lparam job int itemnr joblist find item find if itemnr 1 joblist delete item itemnr cpartfileconvertdlg removejob convertjob lvfi_param lparam finditem deleteitem void c part file convert dlg update job info convert job job if job null set dlg item text idc curjob get res string ids fstat waiting set dlg item text idc conv prozent t pb current set pos 0 set dlg item text idc conv pb label t return c string buffer search jobitem in listctrl lvfindinfo find find flags lvfi param find l param lparam job int itemnr joblist find item find if itemnr 1 joblist set item text itemnr 0 job filename is empty job folder job filename joblist set item text itemnr 1 c part file convert get returncode text job state buffer if job size 0 buffer format get res string ids imp size cast itox bytes job size false false cast itox bytes job spaceneeded false false joblist set item text itemnr 2 buffer joblist set item text itemnr 3 job filehash else add job job why cpartfileconvertdlg updatejobinfo convertjob setdlgitemtext idc_curjob getresstring ids_fstat_waiting setdlgitemtext idc_conv_prozent _t pb_current setpos setdlgitemtext idc_conv_pb_label _t cstring lvfi_param lparam finditem setitemtext isempty setitemtext cpartfileconvert getreturncodetext getresstring ids_imp_size castitoxbytes castitoxbytes setitemtext setitemtext addjob void c part file convert dlg do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc conv pb current pb current ddx control pdx idc joblist joblist cpartfileconvertdlg dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_conv_pb_current pb_current ddx_control idc_joblist void c part file convert dlg post nc destroy c part file convert closedgui c resizable dialog post nc destroy delete this cpartfileconvertdlg postncdestroy cpartfileconvert cresizabledialog postncdestroy void c part file convert dlg on bn clicked ok destroy window cpartfileconvertdlg onbnclickedok destroywindow void c part file convert dlg on add folder browse lpmalloc p malloc null if sh get malloc p malloc noerror buffer a place to hold the file system pathname tchar buffer max path this struct holds the various options for the dialog browseinfo bi bi hwnd owner this m hwnd bi pidl root null bi psz display name buffer c string title get res string ids imp selfolder bi lpsz title title get buffer title get length bi ul flags bif editbox bif newdialogstyle bif nonewfolderbutton bif shareable bi lpfn null now cause the dialog to appear lpitemidlist pidl root if pidl root sh browse for folder bi null bool removesrc int reply idno if the prefs is ext controls enabled reply afx message box get res string ids imp delsrc mb yesnocancel mb defbutton2 if reply idcancel removesrc reply idyes again almost undocumented how to get a ascii pathname from the lpitemidlist struct i guess you just have to know this stuff if sh get path fromid list pidl root buffer do something with the converted string c part file convert scan folder to add c string buffer removesrc free the returned item identifier list using the shell s task allocator arghhhh p malloc free pidl root p malloc release cpartfileconvertdlg onaddfolder pmalloc shgetmalloc pmalloc max_path hwndowner m_hwnd pidlroot pszdisplayname cstring getresstring ids_imp_selfolder lpsztitle getbuffer getlength ulflags bif_editbox bif_newdialogstyle bif_nonewfolderbutton bif_shareable pidlroot pidlroot shbrowseforfolder theprefs isextcontrolsenabled afxmessagebox getresstring ids_imp_delsrc mb_yesnocancel mb_defbutton2 shgetpathfromidlist pidlroot cpartfileconvert scanfoldertoadd cstring pmalloc pidlroot pmalloc void c part file convert dlg on cancel destroy window cpartfileconvertdlg oncancel destroywindow void c part file convert dlg retry sel if joblist get selected count 0 return convert job job position pos joblist get first selected item position while pos null int index joblist get next selected item pos if index 1 job convert job joblist get item data index if job state conv ok job state conv inprogress update job info job job state conv queue c part file convert start thread cpartfileconvertdlg retrysel getselectedcount convertjob getfirstselecteditemposition getnextselecteditem convertjob getitemdata conv_ok conv_inprogress updatejobinfo conv_queue cpartfileconvert startthread void c part file convert dlg remove sel if joblist get selected count 0 return convert job job position pos joblist get first selected item position while pos null int index joblist get next selected item pos if index 1 job convert job joblist get item data index if job state conv inprogress remove job job from list c part file convert remove job job pos joblist get first selected item position cpartfileconvertdlg removesel getselectedcount convertjob getfirstselecteditemposition getnextselecteditem convertjob getitemdata conv_inprogress removejob cpartfileconvert removejob getfirstselecteditemposition void c archive recovery recover c part file part file bool preview bool b create part file copy if part file m bpreviewing part file m brecoveringarchive return part file m brecoveringarchive true add log line true t s s get res string ids attempting recovery part file get file name get the current filled list for this file c typed ptr list c ptr list gap struct filled new c typed ptr list c ptr list gap struct part file get filled list filled ifdef debug int i 0 trace s filled n function position pos filled get head position while pos gap struct gap filled get next pos trace 3u 10u 10u u n i gap start gap end gap end gap start 1 endif the rest of the work can be safely done in a new thread thread param tp new thread param tp part file part file tp filled filled tp preview preview tp b create part file copy b create part file copy do not use windows api create thread to create a thread which uses mfc crt lot of mem leaks if afx begin thread run lpvoid tp part file m brecoveringarchive false log error log statusbar t s s get res string ids recovery failed part file get file name need to delete the memory here as won t be done in thread delete memory tp carchiverecovery cpartfile partfile bcreatepartfilecopy partfile m_bpreviewing partfile m_brecoveringarchive partfile m_brecoveringarchive addlogline _t getresstring ids_attempting_recovery partfile getfilename ctypedptrlist cptrlist gap_struct ctypedptrlist cptrlist gap_struct partfile getfilledlist _debug __function__ getheadposition gap_struct getnext threadparam threadparam partfile partfile bcreatepartfilecopy bcreatepartfilecopy createthread afxbeginthread partfile m_brecoveringarchive logerror log_statusbar _t getresstring ids_recovery_failed partfile getfilename deletememory uint afx cdecl c archive recovery run lpvoid lp param thread param tp thread param lp param dbg set thread name archive recovery init thread locale if perform recovery tp part file tp filled tp preview tp b create part file copy the app queue log line true t s s get res string ids recovery failed tp part file get file name tp part file m brecoveringarchive false delete memory used by copied gap list delete memory tp return 0 afx_cdecl carchiverecovery lpparam threadparam threadparam lpparam dbgsetthreadname archiverecovery initthreadlocale performrecovery partfile bcreatepartfilecopy theapp queuelogline _t getresstring ids_recovery_failed partfile getfilename partfile m_brecoveringarchive deletememory bool preview bool b create part file copy bool success false try c file temp c string temp file name if b create part file copy copy the file temp file name part file get temp path part file get file name mid 0 5 t rec tmp if copy file part file filled temp file name return false open temp file for reading if temp open temp file name c file mode read c file share deny write return false else if temp open part file get file path c file mode read c file share deny none return false open the output file c string ext part file get file name right 4 c string output file name part file get temp path part file get file name mid 0 5 t rec ext c file output ulonglong ul temp file size 0 if output open output file name c file mode write c file share deny write c file mode create process the output file if ext compare no case t zip 0 ext compare no case t cbz 0 success recover zip temp output filled temp get length part file get file size else if ext compare no case t rar 0 ext compare no case t cbr 0 success recover rar temp output filled ul temp file size output get length close output output close close temp file temp close remove temp file if temp file name is empty c file remove temp file name report success if success the app queue log line true t s s get res string ids recovery successful part file get file name the app queue debug log line false t archive recovery part file size s temp archive file size s 1f cast itox bytes part file get file size cast itox bytes ul temp file size part file get file size uint64 0 ul temp file size 100 0 uint64 part file get file size 0 0 preview file if required if preview shellexecuteinfo se memset se 0 sizeof se se f mask see mask nocloseprocess se lp verb t open se lp file output file name se n show sw show se cb size sizeof se shell execute ex se if se h process wait for single object se h process infinite close handle se h process c file remove output file name catch c file exception error error delete catch assert 0 return success bcreatepartfilecopy cfile cstring tempfilename bcreatepartfilecopy tempfilename partfile gettemppath partfile getfilename _t copyfile partfile tempfilename tempfilename cfile moderead cfile sharedenywrite partfile getfilepath cfile moderead cfile sharedenynone cstring partfile getfilename cstring outputfilename partfile gettemppath partfile getfilename _t cfile ultempfilesize outputfilename cfile modewrite cfile sharedenywrite cfile modecreate comparenocase _t comparenocase _t recoverzip getlength partfile getfilesize comparenocase _t comparenocase _t recoverrar ultempfilesize getlength tempfilename isempty cfile tempfilename theapp queuelogline _t getresstring ids_recovery_successful partfile getfilename theapp queuedebuglogline _t castitoxbytes partfile getfilesize castitoxbytes ultempfilesize partfile getfilesize ultempfilesize partfile getfilesize fmask see_mask_nocloseprocess lpverb _t lpfile outputfilename nshow sw_show cbsize shellexecuteex hprocess waitforsingleobject hprocess closehandle hprocess cfile outputfilename cfileexception bool c archive recovery recover zip c file zip input c file zip output c typed ptr list c ptr list gap struct filled bool full size bool ret val false long file count 0 try c typed ptr list c ptr list zip centraldirectory central directory entries gap struct fill if the central directory is intact this is simple if full size read zip central directory zip input central directory entries filled if central directory entries get count 0 return false zip centraldirectory cd entry position pos central directory entries get head position bool deletecd for int i central directory entries get count i 0 i deletecd false cd entry central directory entries get at pos uint32 len entry sizeof zip entry cd entry len filename cd entry len extra field cd entry len compressed if is filled cd entry relative offset of local header cd entry relative offset of local header len entry filled zip input seek cd entry relative offset of local header c file begin update offset cd entry relative offset of local header uint zip output get position if process zip entry zip input zip output len entry null deletecd true else deletecd true if deletecd delete cd entry filename if cd entry len extra field 0 delete cd entry extra field if cd entry len comment 0 delete cd entry comment delete cd entry position del pos central directory entries get next pos central directory entries remove at del else central directory entries get next pos else have to scan the file the hard way loop through filled areas of the file looking for entries position pos filled get head position while pos null fill filled get next pos uint32 file pos uint zip input get position the file may have been positioned to the next entry in scan for marker or process zip entry if file pos fill end continue if file pos fill start zip input seek fill start c file begin if there is any problem then don t bother checking the rest of this part for scan for entry marker within this filled area if scan for zip marker zip input uint32 zip local header magic uint fill end zip input get position 1 break if zip input get position fill end break if process zip entry zip input zip output uint fill end zip input get position 1 central directory entries break remember offset before cd entries uint32 start offset uint zip output get position write all central directory entries file count central directory entries get count if file count 0 zip centraldirectory cd entry position pos central directory entries get head position while pos null cd entry central directory entries get next pos writeu int32 zip output zip cd magic writeu int16 zip output cd entry version made by writeu int16 zip output cd entry version to extract writeu int16 zip output cd entry general purpose flag writeu int16 zip output cd entry compression method writeu int16 zip output cd entry last mod file time writeu int16 zip output cd entry last mod file date writeu int32 zip output cd entry crc32 writeu int32 zip output cd entry len compressed writeu int32 zip output cd entry len unompressed writeu int16 zip output cd entry len filename writeu int16 zip output cd entry len extra field writeu int16 zip output cd entry len comment writeu int16 zip output 0 disk number start writeu int16 zip output cd entry internal file attributes writeu int32 zip output cd entry external file attributes writeu int32 zip output cd entry relative offset of local header zip output write cd entry filename cd entry len filename if cd entry len extra field 0 zip output write cd entry extra field cd entry len extra field if cd entry len comment 0 zip output write cd entry comment cd entry len comment delete cd entry filename if cd entry len extra field 0 delete cd entry extra field if cd entry len comment 0 delete cd entry comment delete cd entry remember offset before cd entries uint32 end offset uint zip output get position write end of central directory writeu int32 zip output zip end cd magic writeu int16 zip output 0 number of this disk writeu int16 zip output 0 number of the disk with the start of the central directory writeu int16 zip output uint16 file count writeu int16 zip output uint16 file count writeu int32 zip output end offset start offset writeu int32 zip output start offset writeu int16 zip output uint16 strlen zip comment zip output write zip comment strlen zip comment central directory entries remove all ret val true catch c file exception error error delete catch assert 0 tell the user how many files were recovered c string msg if file count 1 msg get res string ids recover single else msg format get res string ids recover multiple file count the app queue log line true t s msg return ret val carchiverecovery recoverzip cfile zipinput cfile zipoutput ctypedptrlist cptrlist gap_struct fullsize retval filecount ctypedptrlist cptrlist zip_centraldirectory centraldirectoryentries gap_struct fullsize readzipcentraldirectory zipinput centraldirectoryentries centraldirectoryentries getcount zip_centraldirectory cdentry centraldirectoryentries getheadposition centraldirectoryentries getcount cdentry centraldirectoryentries getat lenentry zip_entry cdentry lenfilename cdentry lenextrafield cdentry lencompressed isfilled cdentry relativeoffsetoflocalheader cdentry relativeoffsetoflocalheader lenentry zipinput cdentry relativeoffsetoflocalheader cfile cdentry relativeoffsetoflocalheader zipoutput getposition processzipentry zipinput zipoutput lenentry cdentry cdentry lenextrafield cdentry extrafield cdentry lencomment cdentry cdentry centraldirectoryentries getnext centraldirectoryentries removeat centraldirectoryentries getnext getheadposition getnext filepos zipinput getposition scanformarker processzipentry filepos filepos zipinput cfile scanforzipmarker zipinput zip_local_header_magic zipinput getposition zipinput getposition processzipentry zipinput zipoutput zipinput getposition centraldirectoryentries startoffset zipoutput getposition filecount centraldirectoryentries getcount filecount zip_centraldirectory cdentry centraldirectoryentries getheadposition cdentry centraldirectoryentries getnext writeuint32 zipoutput zip_cd_magic writeuint16 zipoutput cdentry versionmadeby writeuint16 zipoutput cdentry versiontoextract writeuint16 zipoutput cdentry generalpurposeflag writeuint16 zipoutput cdentry compressionmethod writeuint16 zipoutput cdentry lastmodfiletime writeuint16 zipoutput cdentry lastmodfiledate writeuint32 zipoutput cdentry writeuint32 zipoutput cdentry lencompressed writeuint32 zipoutput cdentry lenunompressed writeuint16 zipoutput cdentry lenfilename writeuint16 zipoutput cdentry lenextrafield writeuint16 zipoutput cdentry lencomment writeuint16 zipoutput writeuint16 zipoutput cdentry internalfileattributes writeuint32 zipoutput cdentry externalfileattributes writeuint32 zipoutput cdentry relativeoffsetoflocalheader zipoutput cdentry cdentry lenfilename cdentry lenextrafield zipoutput cdentry extrafield cdentry lenextrafield cdentry lencomment zipoutput cdentry cdentry lencomment cdentry cdentry lenextrafield cdentry extrafield cdentry lencomment cdentry cdentry endoffset zipoutput getposition writeuint32 zipoutput zip_end_cd_magic writeuint16 zipoutput writeuint16 zipoutput writeuint16 zipoutput filecount writeuint16 zipoutput filecount writeuint32 zipoutput endoffset startoffset writeuint32 zipoutput startoffset writeuint16 zipoutput zip_comment zipoutput zip_comment zip_comment centraldirectoryentries removeall retval cfileexception cstring filecount getresstring ids_recover_single getresstring ids_recover_multiple filecount theapp queuelogline _t retval bool c archive recovery recover rar c file rar input c file rar output c typed ptr list c ptr list gap struct filled bool ret val false long file count 0 try try to get file header and main header bool b valid file header false bool b old format false bool b valid main header false byte file header 7 0 rarmainhdr main header 0 if rar input read file header sizeof file header sizeof file header if file header 0 0x52 if file header 1 0x45 file header 2 0x7e file header 3 0x5e b old format true b valid file header true else if file header 1 0x61 file header 2 0x72 file header 3 0x21 file header 4 0x1a file header 5 0x07 file header 6 0x00 b valid file header true if b valid file header b old format word checkcrc if rar input read checkcrc sizeof checkcrc sizeof checkcrc if rar input read main header sizeof main header sizeof main header if main header type 0x73 dword crc crc32 0 bytef main header sizeof main header for uint i 0 i sizeof word sizeof dword i byte ch if rar input read ch sizeof ch sizeof ch break crc crc32 crc ch 1 if checkcrc word crc b valid main header true rar input seek to begin static const byte start rar file header 0x52 0x61 0x72 0x21 0x1a 0x07 0x00 main header 0x08 0x1a crc 0x73 type 0x02 0x00 flags 0x3b 0x00 size 0x00 0x00 av 0x00 0x00 av 0x00 0x00 av main comment 0xca 0x44 crc 0x75 type 0x00 0x00 flags 0x2e 0x00 size 0x12 0x00 0x14 0x34 0x2b 0x4a 0x08 0x15 0x48 0xc0 0x00 0x00 0x00 0x00 0x01 0x0a 0x2b 0xf9 0x0e 0xe2 0xc1 0x32 0xfb 0x9e 0x04 0x10 0x50 0xd7 0xfe 0xcd 0x75 0x87 0x9c 0x28 0x85 0xdf 0xa3 0x97 0xe0 if this is a solid archive the chance to successfully decompress any entries gets higher when we pass the solid main header bit to the temp archive byte start1 sizeof start memcpy start1 start sizeof start if b valid file header b valid main header main header flags 0x0008 mhd solid start1 10 8 mhd solid short start1 7 short crc32 0 start1 9 11 rar output write start1 sizeof start1 rar blockfile block while block scan for rar file header rar input uint32 rar input get length null if is filled uint block offset data uint block offset data block data length filled don t include directories in file count if block head flags 0xe0 0xe0 file count write rar block rar input rar output block else rar input seek block offset data block data length c file begin delete block file name delete block ret val true catch c file exception error error delete catch assert 0 tell the user how many files were recovered c string msg if file count 1 msg get res string ids recover single else msg format get res string ids recover multiple file count the app queue log line true t s msg return ret val carchiverecovery recoverrar cfile rarinput cfile raroutput ctypedptrlist cptrlist gap_struct retval filecount bvalidfileheader boldformat bvalidmainheader fileheader mainheader rarinput fileheader fileheader fileheader fileheader fileheader fileheader fileheader boldformat bvalidfileheader fileheader fileheader fileheader fileheader fileheader fileheader bvalidfileheader bvalidfileheader boldformat rarinput rarinput mainheader mainheader mainheader mainheader mainheader mainheader rarinput bvalidmainheader rarinput seektobegin bvalidfileheader bvalidmainheader mainheader mhd_solid mhd_solid raroutput rar_blockfile scanforrarfileheader rarinput rarinput getlength isfilled offsetdata offsetdata datalength head_flags filecount writerarblock rarinput raroutput rarinput offsetdata datalength cfile file_name retval cfileexception cstring filecount getresstring ids_recover_single getresstring ids_recover_multiple filecount theapp queuelogline _t retval bool c archive recovery scan for zip marker c file input uint32 marker uint32 available try uint32 original offset input get position int len chunk 51200 50k buffer byte chunk 51200 byte found pos null int pos 0 while available 0 len chunk input read chunk len chunk 0 available len chunk found pos chunk 0 move back one will be incremented in loop found pos while found pos null find first matching byte found pos byte memchr found pos 1 marker 0xff len chunk found pos 1 chunk 0 if found pos null continue test for end of buffer pos found pos chunk 0 if pos 3 len chunk re read buffer starting from found first byte position input seek pos len chunk c file current break check for other bytes if chunk pos 1 marker 8 0xff if chunk pos 2 marker 16 0xff if chunk pos 3 marker 24 0xff found it input seek pos len chunk c file current return true catch c file exception error error delete catch assert 0 return false carchiverecovery scanforzipmarker cfile originaloffset getposition lenchunk foundpos lenchunk lenchunk lenchunk foundpos foundpos foundpos foundpos foundpos lenchunk foundpos foundpos foundpos lenchunk lenchunk cfile lenchunk cfile cfileexception bool c archive recovery process zip entry c file zip input c file zip output uint32 available c typed ptr list c ptr list zip centraldirectory central directory entries if available 26 return false bool ret val false try need to know where it started long start offset long zip output get position entry format 4 2 bytes version needed to extract 6 2 bytes general purpose bit flag 8 2 bytes compression method 10 2 bytes last mod file time 12 2 bytes last mod file date 14 4 bytes crc 32 18 4 bytes compressed size n 22 4 bytes uncompressed size 26 2 bytes filename length f 28 2 bytes extra field length e f bytes filename e bytes extra field n bytes compressed data read header if readu int32 zip input zip local header magic return false zip entry entry 0 entry version to extract readu int16 zip input entry general purpose flag readu int16 zip input entry compression method readu int16 zip input entry last mod file time readu int16 zip input entry last mod file date readu int16 zip input entry crc32 readu int32 zip input entry len compressed readu int32 zip input entry len uncompressed readu int32 zip input entry len filename readu int16 zip input entry len extra field readu int16 zip input do some quick checks at this stage that data is looking ok if entry crc32 0 entry len compressed 0 entry len uncompressed 0 entry len filename 0 this is a directory entry else if entry crc32 0 entry len compressed 0 entry len uncompressed 0 entry len filename 0 return false is this entry complete if entry len filename entry len extra field entry len compressed available 26 move the file pointer to the start of the next entry zip input seek entry len filename entry len extra field entry len compressed c file current return false filename if entry len filename max path return false possibly corrupt don t allocate lots of memory entry filename new byte entry len filename if zip input read entry filename entry len filename entry len filename delete entry filename return false extra data if entry len extra field 0 entry extra field new byte entry len extra field zip input read entry extra field entry len extra field output writeu int32 zip output zip local header magic writeu int16 zip output entry version to extract writeu int16 zip output entry general purpose flag writeu int16 zip output entry compression method writeu int16 zip output entry last mod file time writeu int16 zip output entry last mod file date writeu int32 zip output entry crc32 writeu int32 zip output entry len compressed writeu int32 zip output entry len uncompressed writeu int16 zip output entry len filename writeu int16 zip output entry len extra field if entry len filename 0 zip output write entry filename entry len filename if entry len extra field 0 zip output write entry extra field entry len extra field read and write compressed data to avoid reading all into memory uint32 written 0 byte buf 4096 uint32 len chunk 4096 while written entry len compressed len chunk entry len compressed written if len chunk 4096 len chunk 4096 len chunk zip input read buf len chunk if len chunk 0 break written len chunk zip output write buf len chunk zip output flush central directory if central directory entries null zip centraldirectory cd entry new zip centraldirectory cd entry header zip cd magic cd entry version made by entry version to extract cd entry version to extract entry version to extract cd entry general purpose flag entry general purpose flag cd entry compression method entry compression method cd entry last mod file time entry last mod file time cd entry last mod file date entry last mod file date cd entry crc32 entry crc32 cd entry len compressed entry len compressed cd entry len unompressed entry len uncompressed cd entry len filename entry len filename cd entry len extra field entry len extra field cd entry len comment uint16 strlen zip comment cd entry disk number start 0 cd entry internal file attributes 1 cd entry external file attributes 0x81b60020 cd entry relative offset of local header start offset cd entry filename entry filename if entry len extra field 0 cd entry extra field entry extra field cd entry comment new byte cd entry len comment memcpy cd entry comment zip comment cd entry len comment central directory entries add tail cd entry else delete entry filename if entry len extra field 0 delete entry extra field ret val true catch c file exception error error delete catch assert 0 return ret val carchiverecovery processzipentry cfile zipinput cfile zipoutput ctypedptrlist cptrlist zip_centraldirectory centraldirectoryentries retval startoffset zipoutput getposition readuint32 zipinput zip_local_header_magic zip_entry versiontoextract readuint16 zipinput generalpurposeflag readuint16 zipinput compressionmethod readuint16 zipinput lastmodfiletime readuint16 zipinput lastmodfiledate readuint16 zipinput readuint32 zipinput lencompressed readuint32 zipinput lenuncompressed readuint32 zipinput lenfilename readuint16 zipinput lenextrafield readuint16 zipinput lencompressed lenuncompressed lenfilename lencompressed lenuncompressed lenfilename lenfilename lenextrafield lencompressed zipinput lenfilename lenextrafield lencompressed cfile lenfilename max_path lenfilename zipinput lenfilename lenfilename lenextrafield extrafield lenextrafield zipinput extrafield lenextrafield writeuint32 zipoutput zip_local_header_magic writeuint16 zipoutput versiontoextract writeuint16 zipoutput generalpurposeflag writeuint16 zipoutput compressionmethod writeuint16 zipoutput lastmodfiletime writeuint16 zipoutput lastmodfiledate writeuint32 zipoutput writeuint32 zipoutput lencompressed writeuint32 zipoutput lenuncompressed writeuint16 zipoutput lenfilename writeuint16 zipoutput lenextrafield lenfilename zipoutput lenfilename lenextrafield zipoutput extrafield lenextrafield lenchunk lencompressed lenchunk lencompressed lenchunk lenchunk lenchunk zipinput lenchunk lenchunk lenchunk zipoutput lenchunk zipoutput centraldirectoryentries zip_centraldirectory cdentry zip_centraldirectory cdentry zip_cd_magic cdentry versionmadeby versiontoextract cdentry versiontoextract versiontoextract cdentry generalpurposeflag generalpurposeflag cdentry compressionmethod compressionmethod cdentry lastmodfiletime lastmodfiletime cdentry lastmodfiledate lastmodfiledate cdentry cdentry lencompressed lencompressed cdentry lenunompressed lenuncompressed cdentry lenfilename lenfilename cdentry lenextrafield lenextrafield cdentry lencomment zip_comment cdentry disknumberstart cdentry internalfileattributes cdentry externalfileattributes cdentry relativeoffsetoflocalheader startoffset cdentry lenextrafield cdentry extrafield extrafield cdentry cdentry lencomment cdentry zip_comment cdentry lencomment centraldirectoryentries addtail cdentry lenextrafield extrafield retval cfileexception retval bool c archive recovery read zip central directory c file zip input c typed ptr list c ptr list zip centraldirectory central directory entries c typed ptr list c ptr list gap struct filled bool ret val false try ideally this zip file will not have a comment and the end cd will be easy to find zip input seek 22 c file end if readu int32 zip input zip end cd magic have to look for it comment could be up to 65535 chars but only try with less than 1k zip input seek 1046 c file end if scan for zip marker zip input uint32 zip end cd magic 1046 return false skip it again readu int32 zip input found end cd only interested in offset of first cd zip input seek 12 c file current uint32 start offset readu int32 zip input if is filled start offset uint zip input get length filled return false goto first cd and start reading zip input seek start offset c file begin zip centraldirectory cd entry while readu int32 zip input zip cd magic cd entry new zip centraldirectory cd entry version made by readu int16 zip input cd entry version to extract readu int16 zip input cd entry general purpose flag readu int16 zip input cd entry compression method readu int16 zip input cd entry last mod file time readu int16 zip input cd entry last mod file date readu int16 zip input cd entry crc32 readu int32 zip input cd entry len compressed readu int32 zip input cd entry len unompressed readu int32 zip input cd entry len filename readu int16 zip input cd entry len extra field readu int16 zip input cd entry len comment readu int16 zip input cd entry disk number start readu int16 zip input cd entry internal file attributes readu int16 zip input cd entry external file attributes readu int32 zip input cd entry relative offset of local header readu int32 zip input if cd entry len filename 0 cd entry filename new byte cd entry len filename zip input read cd entry filename cd entry len filename if cd entry len extra field 0 cd entry extra field new byte cd entry len extra field zip input read cd entry extra field cd entry len extra field if cd entry len comment 0 cd entry comment new byte cd entry len comment zip input read cd entry comment cd entry len comment central directory entries add tail cd entry ret val true catch c file exception error error delete catch assert 0 return ret val carchiverecovery readzipcentraldirectory cfile zipinput ctypedptrlist cptrlist zip_centraldirectory centraldirectoryentries ctypedptrlist cptrlist gap_struct retval zipinput cfile readuint32 zipinput zip_end_cd_magic zipinput cfile scanforzipmarker zipinput zip_end_cd_magic readuint32 zipinput zipinput cfile startoffset readuint32 zipinput isfilled startoffset zipinput getlength zipinput startoffset cfile zip_centraldirectory cdentry readuint32 zipinput zip_cd_magic cdentry zip_centraldirectory cdentry versionmadeby readuint16 zipinput cdentry versiontoextract readuint16 zipinput cdentry generalpurposeflag readuint16 zipinput cdentry compressionmethod readuint16 zipinput cdentry lastmodfiletime readuint16 zipinput cdentry lastmodfiledate readuint16 zipinput cdentry readuint32 zipinput cdentry lencompressed readuint32 zipinput cdentry lenunompressed readuint32 zipinput cdentry lenfilename readuint16 zipinput cdentry lenextrafield readuint16 zipinput cdentry lencomment readuint16 zipinput cdentry disknumberstart readuint16 zipinput cdentry internalfileattributes readuint16 zipinput cdentry externalfileattributes readuint32 zipinput cdentry relativeoffsetoflocalheader readuint32 zipinput cdentry lenfilename cdentry cdentry lenfilename zipinput cdentry cdentry lenfilename cdentry lenextrafield cdentry extrafield cdentry lenextrafield zipinput cdentry extrafield cdentry lenextrafield cdentry lencomment cdentry cdentry lencomment zipinput cdentry cdentry lencomment centraldirectoryentries addtail cdentry retval cfileexception retval rar blockfile c archive recovery scan for rar file header c file input uint32 available rar blockfile ret val null try int len chunk 51200 50k buffer byte chunk 51200 byte found pos null int pos 0 ulonglong search offset ulonglong found offset uint16 headcrc byte checkcrc sizeof rarfilehdr 8 sizeof dword 2 512 unsigned checkcr csize 0 uint16 len file name byte file name uint32 crc while available 0 len chunk input read chunk len chunk 0 available len chunk found pos chunk 0 search offset input get position len chunk move back one will be incremented in loop found pos while found pos null find rar head block marker found pos byte memchr found pos 1 rar head file len chunk found pos 1 chunk 0 if found pos null continue move back 2 bytes to get crc and read block pos int found pos chunk 0 2 input seek pos len chunk c file current found offset input get position crc of fields from head type to attr filename ext stuff headcrc readu int16 input rarfilehdr hdr rarfilehdr checkcrc input read checkcrc sizeof hdr checkcr csize sizeof hdr get high parts of 64 bit file size fields if hdr flags 0x0100 lhd large input read checkcrc checkcr csize sizeof dword 2 checkcr csize sizeof dword 2 get filename len file name hdr name size file name new byte len file name input read file name len file name get encryption params unsigned salt pos 0 if hdr flags 0x0400 lhd salt salt pos checkcr csize input read checkcrc checkcr csize 8 checkcr csize 8 get ext file date time unsigned ext time pos 0 unsigned ext time size 0 if hdr flags 0x1000 lhd exttime try ext time pos checkcr csize if checkcr csize sizeof word sizeof checkcrc throw 1 input read checkcrc checkcr csize sizeof word unsigned short flags word checkcrc checkcr csize checkcr csize sizeof word for int i 0 i 4 i unsigned int rmode flags 3 i 4 if rmode 8 0 continue if i 0 if checkcr csize sizeof dword sizeof checkcrc throw 1 input read checkcrc checkcr csize sizeof dword checkcr csize sizeof dword int count rmode 3 for int j 0 j count j if checkcr csize sizeof byte sizeof checkcrc throw 1 input read checkcrc checkcr csize sizeof byte checkcr csize sizeof byte ext time size checkcr csize ext time pos catch int ex void ex ext time pos 0 ext time size 0 crc crc32 0 checkcrc sizeof hdr crc crc32 crc file name len file name if checkcr csize sizeof hdr crc crc32 crc checkcrc sizeof hdr checkcr csize sizeof hdr if crc 0xffff headcrc found valid crc build block and return note that it may still be invalid data so more checks should be performed ret val new rar blockfile ret val head crc headcrc ret val head type 0x74 ret val head flags calcu int16 checkcrc 1 ret val head size calcu int16 checkcrc 3 ret val pack size calcu int32 checkcrc 5 ret val unp size calcu int32 checkcrc 9 ret val host os checkcrc 13 ret val file crc calcu int32 checkcrc 14 ret val ftime calcu int32 checkcrc 18 ret val unp ver checkcrc 22 ret val method checkcrc 23 ret val name size len file name ret val attr calcu int32 checkcrc 26 optional values present only if bit 0x100 in head flags is set if ret val head flags 0x100 0x100 ret val high pack size calcu int32 checkcrc 30 ret val high unp size calcu int32 checkcrc 34 ret val file name file name if salt pos 0 memcpy ret val salt checkcrc salt pos sizeof ret val salt if ext time pos 0 ext time size 0 ret val ext date new byte ext time size memcpy ret val ext date checkcrc ext time pos ext time size ret val ext date size ext time size run some quick checks if validate rar file block ret val set some useful markers in the block ret val offset data input get position uint32 data length ret val pack size if comment present find length if ret val head flags 0x08 0x08 skip start of comment block input seek 5 c file current read comment length data length readu int16 input ret val data length data length return ret val if not valid return to original position re read and continue searching delete file name delete ret val ret val null input seek search offset c file begin input read chunk len chunk catch c file exception error error delete catch assert 0 return false rar_blockfile carchiverecovery scanforrarfileheader cfile rar_blockfile retval lenchunk foundpos searchoffset foundoffset checkcrcsize lenfilename filename lenchunk lenchunk lenchunk foundpos searchoffset getposition lenchunk foundpos foundpos foundpos foundpos rar_head_file lenchunk foundpos foundpos foundpos lenchunk cfile foundoffset getposition head_type readuint16 checkcrcsize lhd_large checkcrcsize checkcrcsize lenfilename namesize filename lenfilename filename lenfilename saltpos lhd_salt saltpos checkcrcsize checkcrcsize checkcrcsize exttimepos exttimesize lhd_exttime exttimepos checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize checkcrcsize exttimesize checkcrcsize exttimepos exttimepos exttimesize filename lenfilename checkcrcsize checkcrcsize retval rar_blockfile retval head_crc retval head_type retval head_flags calcuint16 retval head_size calcuint16 retval pack_size calcuint32 retval unp_size calcuint32 retval host_os retval file_crc calcuint32 retval calcuint32 retval unp_ver retval retval name_size lenfilename retval calcuint32 head_flags retval head_flags retval high_pack_size calcuint32 retval high_unp_size calcuint32 retval file_name filename saltpos retval saltpos retval exttimepos exttimesize retval ext_date exttimesize retval ext_date exttimepos exttimesize retval ext_date_size exttimesize validaterarfileblock retval retval offsetdata getposition datalength retval pack_size retval head_flags cfile datalength readuint16 retval datalength datalength retval filename retval retval searchoffset cfile lenchunk cfileexception bool c archive recovery validate rar file block rar blockfile block if block head type 0x74 return false if block head flags 0x0400 lhd salt 0 block unp size block pack size return false if block host os 5 return false switch block method case 0x30 storing case 0x31 fastest compression case 0x32 fast compression case 0x33 normal compression case 0x34 good compression case 0x35 best compression break default return false if block name size max path return false check directory entry has no size if block head flags 0xe0 0xe0 block pack size block unp size block file crc 0 return false return true carchiverecovery validaterarfileblock rar_blockfile head_type head_flags lhd_salt unp_size pack_size host_os name_size max_path head_flags pack_size unp_size file_crc void c archive recovery write rar block c file input c file output rar blockfile block ulonglong offset start output get position try writeu int16 output block head crc output write block head type 1 writeu int16 output block head flags writeu int16 output block head size writeu int32 output block pack size writeu int32 output block unp size output write block host os 1 writeu int32 output block file crc writeu int32 output block ftime output write block unp ver 1 output write block method 1 writeu int16 output block name size writeu int32 output block attr optional values present only if bit 0x100 in head flags is set if block head flags 0x100 0x100 writeu int32 output block high pack size writeu int32 output block high unp size output write block file name block name size if block head flags 0x0400 lhd salt output write block salt sizeof block salt output write block ext date block ext date size now copy compressed data from input file uint32 len to copy block data length if len to copy 0 input seek block offset data c file begin uint32 written 0 byte chunk 4096 uint32 len chunk 4096 while written len to copy len chunk len to copy written if len chunk 4096 len chunk 4096 len chunk input read chunk len chunk if len chunk 0 break written len chunk output write chunk len chunk output flush catch c file exception error error delete try output set length offset start catch assert 0 catch assert 0 try output set length offset start catch assert 0 carchiverecovery writerarblock cfile cfile rar_blockfile offsetstart getposition writeuint16 head_crc head_type writeuint16 head_flags writeuint16 head_size writeuint32 pack_size writeuint32 unp_size host_os writeuint32 file_crc writeuint32 unp_ver writeuint16 name_size writeuint32 head_flags head_flags writeuint32 high_pack_size writeuint32 high_unp_size file_name name_size head_flags lhd_salt ext_date ext_date_size lentocopy datalength lentocopy offsetdata cfile lenchunk lentocopy lenchunk lentocopy lenchunk lenchunk lenchunk lenchunk lenchunk lenchunk lenchunk cfileexception setlength offsetstart setlength offsetstart bool c archive recovery copy file c part file part file c typed ptr list c ptr list gap struct filled c string temp file name bool ret val false try c file src file if src file open part file get file path c file mode read c file share deny none return false open destination file and set length to last filled end position c file dest file dest file open temp file name c file mode write c file share deny write c file mode create gap struct fill filled get tail dest file set length fill end byte buffer 4096 uint32 read uint32 copied loop through filled areas and copy data part file m bpreviewing true position pos filled get head position while pos null fill filled get next pos copied 0 src file seek fill start c file begin dest file seek fill start c file begin while read src file read buffer 4096 0 dest file write buffer read copied read stop when finished fill don t worry about extra if fill start copied fill end break dest file close src file close part file m bpreviewing false ret val true catch c file exception error error delete catch assert 0 return ret val carchiverecovery copyfile cpartfile partfile ctypedptrlist cptrlist gap_struct cstring tempfilename retval cfile srcfile srcfile partfile getfilepath cfile moderead cfile sharedenynone cfile destfile destfile tempfilename cfile modewrite cfile sharedenywrite cfile modecreate gap_struct gettail destfile setlength partfile m_bpreviewing getheadposition getnext srcfile cfile destfile cfile srcfile destfile destfile srcfile partfile m_bpreviewing retval cfileexception retval void c archive recovery delete memory thread param tp position pos tp filled get head position while pos null delete tp filled get next pos tp filled remove all delete tp filled delete tp carchiverecovery deletememory threadparam getheadposition getnext removeall bool c archive recovery is filled uint32 start uint32 end c typed ptr list c ptr list gap struct filled position pos filled get head position gap struct fill while pos null fill filled get next pos if fill start start return false if fill end end return true return false carchiverecovery isfilled ctypedptrlist cptrlist gap_struct getheadposition gap_struct getnext uint16 c archive recovery readu int16 c file input uint16 ret val 0 byte b 2 if input read b 2 0 ret val b 1 8 b 0 return ret val carchiverecovery readuint16 cfile retval retval retval uint32 c archive recovery readu int32 c file input uint32 ret val 0 byte b 4 if input read b 4 0 ret val b 3 24 b 2 16 b 1 8 b 0 return ret val carchiverecovery readuint32 cfile retval retval retval uint16 c archive recovery calcu int16 byte input return uint16 input 1 8 uint16 input 0 carchiverecovery calcuint16 uint32 c archive recovery calcu int32 byte input return uint32 input 3 24 uint32 input 2 16 uint32 input 1 8 uint32 input 0 carchiverecovery calcuint32 void c archive recovery writeu int16 c file output uint16 val byte b 2 b 0 byte val 0x000000ff b 1 byte val 0x0000ff00 8 output write b 2 carchiverecovery writeuint16 cfile void c archive recovery writeu int32 c file output uint32 val byte b 4 b 0 byte val 0x000000ff b 1 byte val 0x0000ff00 8 b 2 byte val 0x00ff0000 16 b 3 byte val 0xff000000 24 output write b 4 carchiverecovery writeuint32 cfile there is no such frame at that index name operator param index the index of the frame that is to be retrieved see get frame num id3 frame id3 tag operator size t index const return this get frame num index getframenum id3_frame id3_tag size_t getframenum iterator impl id3 frameimpl frame cur frame begin end frame end iteratorimpl id3_frameimpl _cur _end id3 field get next id3 field next null while next null cur end next cur cur return next id3_field getnext id3_field _cur _end _cur _cur bool id3 tag has tag type id3 tagtype tt const return impl has tag type tt id3_tag hastagtype id3_tagtype _impl hastagtype id3 v2spec id3 tag get spec const return impl get spec bool id3 tag set spec id3 v2spec spec return impl set spec spec id3_v2spec id3_tag getspec _impl getspec id3_tag setspec id3_v2spec _impl setspec const iterator impl id3 frameimpl frame cur frame begin end frame end constiteratorimpl id3_frameimpl _cur _end const id3 field get next id3 field next null while next null cur end next cur cur return next id3_field getnext id3_field _cur _end _cur _cur public ced2k file types qsort aed2kfiletypes arrsize aed2kfiletypes sizeof aed2kfiletypes 0 comparee2dk file type ifdef debug check for duplicate entries lpctstr psz last aed2kfiletypes 0 psz ext for int i 1 i arrsize aed2kfiletypes i assert tcscmp psz last aed2kfiletypes i psz ext 0 psz last aed2kfiletypes i psz ext endif ced2kfiletypes _aed2kfiletypes _aed2kfiletypes _aed2kfiletypes comparee2dkfiletype _debug pszlast _aed2kfiletypes pszext _aed2kfiletypes _tcscmp pszlast _aed2kfiletypes pszext pszlast _aed2kfiletypes pszext c mule toolbar ctrl c mule toolbar ctrl m sizbtnbmp cx the prefs get toolbar icon size cx m sizbtnbmp cy the prefs get toolbar icon size cy m ipreviousheight 0 m ilastpressedbutton 1 m buttoncount 0 memset tb buttons 0 sizeof tb buttons memset tb strings 0 sizeof tb strings m elabeltype no labels cmuletoolbarctrl cmuletoolbarctrl m_sizbtnbmp theprefs gettoolbariconsize m_sizbtnbmp theprefs gettoolbariconsize m_ipreviousheight m_ilastpressedbutton m_buttoncount tbbuttons tbbuttons tbstrings tbstrings m_elabeltype nolabels c mule toolbar ctrl c mule toolbar ctrl if m bmpback m hobject verify m bmpback delete object cmuletoolbarctrl cmuletoolbarctrl m_bmpback m_hobject m_bmpback deleteobject void c mule toolbar ctrl refresh set all buttons width auto size causes a toolbar to be resized if the app emuledlg m ctlmaintoprebar m hwnd the app emuledlg remove anchor the app emuledlg m ctlmaintoprebar m hwnd rebarbandinfo rbbi 0 c size size bar get max size size bar assert size bar cx 0 size bar cy 0 rbbi cb size sizeof rbbi rbbi f mask rbbim childsize rbbim idealsize rbbi cx min child size bar cy rbbi cy min child size bar cy rbbi cx ideal size bar cx verify the app emuledlg m ctlmaintoprebar set band info mule toolbar band nr rbbi the app emuledlg add anchor the app emuledlg m ctlmaintoprebar m hwnd top left top right c rect r toolbar rect get window rect r toolbar rect if m ipreviousheight r toolbar rect height invalidate redraw window else m ipreviousheight r toolbar rect height c rect r client rect the app emuledlg get client rect r client rect c rect r statusbar rect the app emuledlg statusbar get window rect r statusbar rect r client rect top r toolbar rect height r client rect bottom r statusbar rect height c wnd wnds the app emuledlg serverwnd the app emuledlg kademliawnd the app emuledlg transferwnd the app emuledlg sharedfileswnd the app emuledlg searchwnd the app emuledlg chatwnd the app emuledlg ircwnd the app emuledlg statisticswnd for int i 0 i arrsize wnds i wnds i set window pos null r client rect left r client rect top r client rect width r client rect height swp nozorder the app emuledlg remove anchor wnds i m hwnd the app emuledlg add anchor wnds i m hwnd top left bottom right the app emuledlg invalidate the app emuledlg redraw window cmuletoolbarctrl setallbuttonswidth autosize theapp m_ctlmaintoprebar m_hwnd theapp removeanchor theapp m_ctlmaintoprebar m_hwnd csize sizebar getmaxsize sizebar sizebar sizebar cbsize fmask rbbim_childsize rbbim_idealsize cxminchild sizebar cyminchild sizebar cxideal sizebar theapp m_ctlmaintoprebar setbandinfo mule_toolbar_band_nr theapp addanchor theapp m_ctlmaintoprebar m_hwnd top_left top_right crect rtoolbarrect getwindowrect rtoolbarrect m_ipreviousheight rtoolbarrect redrawwindow m_ipreviousheight rtoolbarrect crect rclientrect theapp getclientrect rclientrect crect rstatusbarrect theapp getwindowrect rstatusbarrect rclientrect rtoolbarrect rclientrect rstatusbarrect cwnd theapp theapp theapp theapp theapp theapp theapp theapp setwindowpos rclientrect rclientrect rclientrect rclientrect swp_nozorder theapp removeanchor m_hwnd theapp addanchor m_hwnd top_left bottom_right theapp theapp redrawwindow void c mule toolbar ctrl save cur height c rect rc wnd get window rect rc wnd m ipreviousheight rc wnd height cmuletoolbarctrl savecurheight crect rcwnd getwindowrect rcwnd m_ipreviousheight rcwnd void c mule toolbar ctrl update background if the app emuledlg m ctlmaintoprebar hbitmap hbmp the app load image t main tool bar bk t bmp if hbmp rebarbandinfo rbbi 0 rbbi cb size sizeof rbbi rbbi f mask rbbim style if the app emuledlg m ctlmaintoprebar get band info mule toolbar band nr rbbi rbbi f mask rbbim style rbbim background rbbi f style rbbs fixedbmp rbbi hbm back hbmp if the app emuledlg m ctlmaintoprebar set band info mule toolbar band nr rbbi if m bmpback m hobject verify m bmpback delete object m bmpback attach hbmp hbmp null if hbmp verify delete object hbmp else rebarbandinfo rbbi 0 rbbi cb size sizeof rbbi rbbi f mask rbbim style if the app emuledlg m ctlmaintoprebar get band info mule toolbar band nr rbbi rbbi f mask rbbim style rbbim background rbbi f style rbbs fixedbmp rbbi hbm back null if the app emuledlg m ctlmaintoprebar set band info mule toolbar band nr rbbi if m bmpback m hobject verify m bmpback delete object cmuletoolbarctrl updatebackground theapp m_ctlmaintoprebar theapp loadimage _t maintoolbarbk _t cbsize fmask rbbim_style theapp m_ctlmaintoprebar getbandinfo mule_toolbar_band_nr fmask rbbim_style rbbim_background fstyle rbbs_fixedbmp hbmback theapp m_ctlmaintoprebar setbandinfo mule_toolbar_band_nr m_bmpback m_hobject m_bmpback deleteobject m_bmpback deleteobject cbsize fmask rbbim_style theapp m_ctlmaintoprebar getbandinfo mule_toolbar_band_nr fmask rbbim_style rbbim_background fstyle rbbs_fixedbmp hbmback theapp m_ctlmaintoprebar setbandinfo mule_toolbar_band_nr m_bmpback m_hobject m_bmpback deleteobject void c mule toolbar ctrl press mule button int nid customization might splits up the button group so we have to un press them on our own if m ilastpressedbutton 1 check button m ilastpressedbutton false check button nid true m ilastpressedbutton nid cmuletoolbarctrl pressmulebutton m_ilastpressedbutton checkbutton m_ilastpressedbutton checkbutton m_ilastpressedbutton void c mule toolbar ctrl change toolbar bitmap const c string path bool b refresh bool b result false c image list image list c en bitmap bitmap if path is empty bitmap load image path bitmap bm 0 bitmap get object sizeof bm bm if bm bm width num button bitmaps m sizbtnbmp cx bm bm height m sizbtnbmp cy bool b alpha bm bm bits pixel 24 if image list create m sizbtnbmp cx bm bm height b alpha ilc color32 the app m idfltimagelistcolorflags ilc mask 0 1 image list add bitmap b alpha 0xff000000 rgb 255 0 255 c image list piml old set image list image list image list detach if piml old piml old delete image list b result true bitmap delete object if image file loading or image list creation failed create default image list if b result load from icon ressources image list create m sizbtnbmp cx m sizbtnbmp cy the app m idfltimagelistcolorflags ilc mask 0 1 image list add c temp icon loader t connect m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t disconnect m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t stopconnecting m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t kademlia m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t server m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t transfer m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t search m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t shared files m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t messages m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t irc m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t statistics m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t preferences m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t tools m sizbtnbmp cx m sizbtnbmp cy image list add c temp icon loader t help m sizbtnbmp cx m sizbtnbmp cy assert image list get image count num button bitmaps c image list piml old set image list image list image list detach if piml old piml old delete image list if b refresh update background invalidate refresh cmuletoolbarctrl changetoolbarbitmap cstring brefresh bresult cimagelist imagelist cenbitmap isempty loadimage getobject bmwidth num_button_bitmaps m_sizbtnbmp bmheight m_sizbtnbmp balpha bmbitspixel imagelist m_sizbtnbmp bmheight balpha ilc_color32 theapp m_idfltimagelistcolorflags ilc_mask imagelist balpha cimagelist pimlold setimagelist imagelist imagelist pimlold pimlold deleteimagelist bresult deleteobject bresult imagelist m_sizbtnbmp m_sizbtnbmp theapp m_idfltimagelistcolorflags ilc_mask imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t sharedfiles m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist ctempiconloader _t m_sizbtnbmp m_sizbtnbmp imagelist getimagecount num_button_bitmaps cimagelist pimlold setimagelist imagelist imagelist pimlold pimlold deleteimagelist brefresh updatebackground void c mule toolbar ctrl change text label style e toolbar label type e label type bool b refresh bool b force update buttons if m elabeltype e label type b force update buttons switch e label type case no labels set style get style tbstyle list set max text rows 0 break case labels below set style get style tbstyle list set max text rows 1 break case labels right set style get style tbstyle list set max text rows 1 break for int i 0 i m buttoncount i tbbuttoninfo tbbi 0 tbbi cb size sizeof tbbi tbbi dw mask tbif style get button info idc toolbarbutton i tbbi if e label type labels right tbbi fs style tbstyle autosize else tbbi fs style tbstyle autosize set button info idc toolbarbutton i tbbi m elabeltype e label type if b refresh refresh cmuletoolbarctrl changetextlabelstyle etoolbarlabeltype elabeltype brefresh bforceupdatebuttons m_elabeltype elabeltype bforceupdatebuttons elabeltype nolabels setstyle getstyle tbstyle_list setmaxtextrows labelsbelow setstyle getstyle tbstyle_list setmaxtextrows labelsright setstyle getstyle tbstyle_list setmaxtextrows m_buttoncount cbsize dwmask tbif_style getbuttoninfo idc_toolbarbutton elabeltype labelsright fsstyle tbstyle_autosize fsstyle tbstyle_autosize setbuttoninfo idc_toolbarbutton m_elabeltype elabeltype brefresh void c mule toolbar ctrl update ideal size if the app emuledlg m ctlmaintoprebar m hwnd let the rebar know what s our new current ideal size so the chevron is handled correctly c size size bar get max size size bar assert size bar cx 0 size bar cy 0 rebarbandinfo rbbi 0 rbbi cb size sizeof rbbi rbbi f mask rbbim idealsize rbbi cx ideal size bar cx verify the app emuledlg m ctlmaintoprebar set band info mule toolbar band nr rbbi cmuletoolbarctrl updateidealsize theapp m_ctlmaintoprebar m_hwnd csize sizebar getmaxsize sizebar sizebar sizebar cbsize fmask rbbim_idealsize cxideal sizebar theapp m_ctlmaintoprebar setbandinfo mule_toolbar_band_nr void c mule toolbar ctrl set all buttons strings static const int tb stringi ds ids em kademlia ids em server ids em trans ids em search ids em files ids em messages ids irc ids em statistic ids em prefs ids tools ids em help tbbuttoninfo tbi tbi dw mask tbif text tbi cb size sizeof tbbuttoninfo c string buffer if the app serverconnect is connected buffer get res string ids main btn disconnect else if the app serverconnect is connecting buffer get res string ids main btn cancel else buffer get res string ids main btn connect sntprintf tb strings 0 arrsize tb strings 0 t s buffer tbi psz text tb strings 0 set button info idc toolbarbutton 0 tbi for int i 1 i m buttoncount i sntprintf tb strings i arrsize tb strings 0 t s get res string tb stringi ds i 1 tbi psz text tb strings i set button info idc toolbarbutton i tbi cmuletoolbarctrl setallbuttonsstrings tbstringids ids_em_kademlia ids_em_server ids_em_trans ids_em_search ids_em_files ids_em_messages ids_irc ids_em_statistic ids_em_prefs ids_tools ids_em_help dwmask tbif_text cbsize cstring theapp isconnected getresstring ids_main_btn_disconnect theapp isconnecting getresstring ids_main_btn_cancel getresstring ids_main_btn_connect _sntprintf tbstrings tbstrings _t psztext tbstrings setbuttoninfo idc_toolbarbutton m_buttoncount _sntprintf tbstrings tbstrings _t getresstring tbstringids psztext tbstrings setbuttoninfo idc_toolbarbutton void c mule toolbar ctrl set all buttons width if get button count 0 return if m elabeltype labels below cdc pdc getdc c font p fnt get font c font p old fnt pdc select object p fnt c rect r 0 0 0 0 calculate the max possible button size int i calc size 0 for int i 0 i m buttoncount i if is button hidden idc toolbarbutton i pdc draw text tb strings i 1 r dt singleline dt calcrect if r width i calc size i calc size r width i calc size 10 pdc select object p old fnt releasedc pdc if the prefs get use re bar toolbar get client rect r int bc get button count if bc 0 bc 1 int i max possible r width bc if the buttons are to big reduze their size if i calc size i max possible i calc size i max possible else if i calc size 56 i calc size 56 else if i calc size 70 i calc size 70 set button width i calc size i calc size else const int i small icons button height 28 if m elabeltype no labels dword dw size get button size int i fixed button width int i fixed button height hiword dw size if m sizbtnbmp cx 16 i fixed button width 28 i fixed button height i small icons button height else i fixed button width 56 it seems that the control updates itself more properly if set button width id called before set button size set button width i fixed button width i fixed button width set button size c size i fixed button width i fixed button height else int i fixed button height 0 if m sizbtnbmp cx 16 i fixed button height i small icons button height it seems that the control updates itself more properly if set button width id called before set button size set button width 0 0 set button size c size 0 i fixed button height cmuletoolbarctrl setallbuttonswidth getbuttoncount m_elabeltype labelsbelow cfont pfnt getfont cfont poldfnt selectobject pfnt crect icalcsize m_buttoncount isbuttonhidden idc_toolbarbutton drawtext tbstrings dt_singleline dt_calcrect icalcsize icalcsize icalcsize selectobject poldfnt theprefs getuserebartoolbar getclientrect getbuttoncount imaxpossible icalcsize imaxpossible icalcsize imaxpossible icalcsize icalcsize icalcsize icalcsize setbuttonwidth icalcsize icalcsize ismalliconsbuttonheight m_elabeltype nolabels dwsize getbuttonsize ifixedbuttonwidth ifixedbuttonheight dwsize m_sizbtnbmp ifixedbuttonwidth ifixedbuttonheight ismalliconsbuttonheight ifixedbuttonwidth setbuttonwidth setbuttonsize setbuttonwidth ifixedbuttonwidth ifixedbuttonwidth setbuttonsize csize ifixedbuttonwidth ifixedbuttonheight ifixedbuttonheight m_sizbtnbmp ifixedbuttonheight ismalliconsbuttonheight setbuttonwidth setbuttonsize setbuttonwidth setbuttonsize csize ifixedbuttonheight void c mule toolbar ctrl force recalc layout force a recalc of the toolbar s layout to work around a comctl bug int i text rows get max text rows set redraw false set max text rows i text rows 1 set max text rows i text rows set redraw true cmuletoolbarctrl forcerecalclayout itextrows getmaxtextrows setredraw setmaxtextrows itextrows setmaxtextrows itextrows setredraw void c mule toolbar ctrl auto size c tool bar ctrl auto size ifdef debug dump endif cmuletoolbarctrl autosize ctoolbarctrl autosize _debug bool c mule toolbar ctrl on command wparam w param lparam l param switch w param case mp selecttoolbarbitmapdir tchar buffer max path sntprintf buffer arrsize buffer t s the prefs get toolbar bitmap folder settings if select dir m hwnd buffer get res string ids selecttoolbarbitmapdir the prefs set toolbar bitmap folder settings buffer break case mp customizetoolbar customize break case mp selecttoolbarbitmap we could also load jpg here but because of the typical non solid background of jp gs this doesn t make sense here c string str filter t e mule toolbar bitmap files for int f 0 f arrsize apsztbfiles f if f 0 str filter t str filter apsztbfiles f str filter t for int f 0 f arrsize apsztbfiles f if f 0 str filter t str filter apsztbfiles f str filter t c file dialog dialog true emultb baseext t bmp null ofn hidereadonly ofn pathmustexist ofn filemustexist str filter null 0 if idok dialog do modal if the prefs get toolbar bitmap settings dialog get path name change toolbar bitmap dialog get path name true the prefs set toolbar bitmap settings dialog get path name break case mp largeicons m sizbtnbmp cx m sizbtnbmp cy 32 force recalc layout change toolbar bitmap the prefs get toolbar bitmap settings true the prefs set toolbar icon size m sizbtnbmp break case mp smallicons m sizbtnbmp cx m sizbtnbmp cy 16 force recalc layout change toolbar bitmap the prefs get toolbar bitmap settings true the prefs set toolbar icon size m sizbtnbmp break case mp notextlabels force recalc layout change text label style no labels true the prefs set toolbar label settings no labels break case mp textlabels force recalc layout change text label style labels below true the prefs set toolbar label settings labels below break case mp textlabelsonright force recalc layout change text label style labels right true the prefs set toolbar label settings labels right break case mp select skin dir tchar buffer max path sntprintf buffer arrsize buffer t s the prefs get skin profile dir if select dir m hwnd buffer get res string ids selskinprofiledir the prefs set skin profile dir buffer break case mp select skin file c string str filter t e mule skin files for int f 0 f arrsize apszskinfiles f if f 0 str filter t str filter apszskinfiles f str filter t for int f 0 f arrsize apszskinfiles f if f 0 str filter t str filter apszskinfiles f str filter t c file dialog dialog true emulskin baseext t ini null ofn hidereadonly ofn pathmustexist ofn filemustexist str filter null 0 if dialog do modal idok if the prefs get skin profile compare no case dialog get path name 0 the app apply skin dialog get path name break default if w param mp toolbarbitmap w param mp toolbarbitmap max toolbar files if the prefs get toolbar bitmap settings compare no case m astrtoolbarpaths w param mp toolbarbitmap 0 change toolbar bitmap m astrtoolbarpaths w param mp toolbarbitmap true the prefs set toolbar bitmap settings m astrtoolbarpaths w param mp toolbarbitmap else if w param mp skin profile w param mp skin profile max skin files if the prefs get skin profile compare no case m astrskinpaths w param mp skin profile 0 the app apply skin m astrskinpaths w param mp skin profile return true cmuletoolbarctrl oncommand wparam lparam wparam mp_selecttoolbarbitmapdir max_path _sntprintf _t theprefs gettoolbarbitmapfoldersettings selectdir m_hwnd getresstring ids_selecttoolbarbitmapdir theprefs settoolbarbitmapfoldersettings mp_customizetoolbar mp_selecttoolbarbitmap jpgs cstring strfilter _t emule _apsztbfiles strfilter _t strfilter _apsztbfiles strfilter _t _apsztbfiles strfilter _t strfilter _apsztbfiles strfilter _t cfiledialog emultb_baseext _t ofn_hidereadonly ofn_pathmustexist ofn_filemustexist strfilter domodal theprefs gettoolbarbitmapsettings getpathname changetoolbarbitmap getpathname theprefs settoolbarbitmapsettings getpathname mp_largeicons m_sizbtnbmp m_sizbtnbmp forcerecalclayout changetoolbarbitmap theprefs gettoolbarbitmapsettings theprefs settoolbariconsize m_sizbtnbmp mp_smallicons m_sizbtnbmp m_sizbtnbmp forcerecalclayout changetoolbarbitmap theprefs gettoolbarbitmapsettings theprefs settoolbariconsize m_sizbtnbmp mp_notextlabels forcerecalclayout changetextlabelstyle nolabels theprefs settoolbarlabelsettings nolabels mp_textlabels forcerecalclayout changetextlabelstyle labelsbelow theprefs settoolbarlabelsettings labelsbelow mp_textlabelsonright forcerecalclayout changetextlabelstyle labelsright theprefs settoolbarlabelsettings labelsright mp_select_skin_dir max_path _sntprintf _t theprefs getskinprofiledir selectdir m_hwnd getresstring ids_selskinprofiledir theprefs setskinprofiledir mp_select_skin_file cstring strfilter _t emule _apszskinfiles strfilter _t strfilter _apszskinfiles strfilter _t _apszskinfiles strfilter _t strfilter _apszskinfiles strfilter _t cfiledialog emulskin_baseext _t ofn_hidereadonly ofn_pathmustexist ofn_filemustexist strfilter domodal theprefs getskinprofile comparenocase getpathname theapp applyskin getpathname wparam mp_toolbarbitmap wparam mp_toolbarbitmap max_toolbar_files theprefs gettoolbarbitmapsettings comparenocase m_astrtoolbarpaths wparam mp_toolbarbitmap changetoolbarbitmap m_astrtoolbarpaths wparam mp_toolbarbitmap theprefs settoolbarbitmapsettings m_astrtoolbarpaths wparam mp_toolbarbitmap wparam mp_skin_profile wparam mp_skin_profile max_skin_files theprefs getskinprofile comparenocase m_astrskinpaths wparam mp_skin_profile theapp applyskin m_astrskinpaths wparam mp_skin_profile void c mule toolbar ctrl on size uint n type int cx int cy c tool bar ctrl on size n type cx cy set all buttons width auto size cmuletoolbarctrl onsize ntype ctoolbarctrl onsize ntype setallbuttonswidth autosize void c mule toolbar ctrl on sys color change c tool bar ctrl on sys color change change toolbar bitmap the prefs get toolbar bitmap settings true cmuletoolbarctrl onsyscolorchange ctoolbarctrl onsyscolorchange changetoolbarbitmap theprefs gettoolbarbitmapsettings void c mule toolbar ctrl onnm rclick nmhdr pnmhdr lresult p result if get key state vk control 0x8000 if the prefs get toolbar bitmap settings is empty change toolbar bitmap the prefs get toolbar bitmap settings true if the prefs get skin profile is empty the app apply skin the prefs get skin profile p result true return toolbar bitmap sub menu c menu menu bitmaps menu bitmaps create menu menu bitmaps append menu mf string mp selecttoolbarbitmap get res string ids selecttoolbarbitmap menu bitmaps append menu mf string mp selecttoolbarbitmapdir get res string ids selecttoolbarbitmapdir menu bitmaps append menu mf separator menu bitmaps append menu mf string mp toolbarbitmap get res string ids default m astrtoolbarpaths remove all c string current bitmap settings the prefs get toolbar bitmap settings bool checked false if current bitmap settings is empty menu bitmaps check menu item mp toolbarbitmap mf checked menu bitmaps enable menu item mp toolbarbitmap mf disabled checked true m astrtoolbarpaths add t dummy entry for default menu item int i 1 if the prefs get toolbar bitmap folder settings is empty c string array astr toolbar files for int f 0 f arrsize apsztbfiles f win32 find data file data handle h search find first file the prefs get toolbar bitmap folder settings c string t apsztbfiles f file data if h search invalid handle value do astr toolbar files add file data c file name while astr toolbar files get count max toolbar files find next file h search file data find close h search if astr toolbar files get count 0 sort astr toolbar files for int f 0 f astr toolbar files get count f const c string bitmap file name astr toolbar files get at f c string bitmap base name lpctstr psz tb base ext stristr bitmap file name emultb baseext if psz tb base ext bitmap base name bitmap file name left psz tb base ext lpctstr bitmap file name 1 else bitmap base name bitmap file name menu bitmaps append menu mf string mp toolbarbitmap i bitmap base name m astrtoolbarpaths add the prefs get toolbar bitmap folder settings c string t bitmap file name if checked current bitmap settings compare no case m astrtoolbarpaths i 0 menu bitmaps check menu item mp toolbarbitmap i mf checked menu bitmaps enable menu item mp toolbarbitmap i mf disabled checked true i assert i 1 astr toolbar files get count if checked menu bitmaps append menu mf string mp toolbarbitmap i current bitmap settings menu bitmaps check menu item mp toolbarbitmap i mf checked menu bitmaps enable menu item mp toolbarbitmap i mf disabled m astrtoolbarpaths add current bitmap settings skin profile sub menu c menu menu skins menu skins create menu menu skins append menu mf string mp select skin file get res string ids sel skin menu skins append menu mf string mp select skin dir get res string ids sel skindir menu skins append menu mf separator menu skins append menu mf string mp skin profile get res string ids default m astrskinpaths remove all c string current skin the prefs get skin profile checked false if current skin is empty menu skins check menu item mp skin profile mf checked menu skins enable menu item mp skin profile mf disabled checked true m astrskinpaths add t dummy entry for default menu item i 1 if the prefs get skin profile dir is empty c string array astr skin files for int f 0 f arrsize apszskinfiles f win32 find data file data handle h search find first file the prefs get skin profile dir c string t apszskinfiles f file data if h search invalid handle value do astr skin files add file data c file name while astr skin files get count max skin files find next file h search file data find close h search if astr skin files get count 0 sort astr skin files for int f 0 f astr skin files get count f const c string skin file name astr skin files get at f c string skin base name lpctstr psz skin base ext stristr skin file name t emulskin baseext t ini if psz skin base ext skin base name skin file name left psz skin base ext lpctstr skin file name else skin base name skin file name menu skins append menu mf string mp skin profile i skin base name m astrskinpaths add the prefs get skin profile dir c string t skin file name if checked current skin compare no case m astrskinpaths i 0 menu skins check menu item mp skin profile i mf checked menu skins enable menu item mp skin profile i mf disabled checked true i assert i 1 astr skin files get count if checked menu skins append menu mf string mp skin profile i current skin menu skins check menu item mp skin profile i mf checked menu skins enable menu item mp skin profile i mf disabled m astrskinpaths add current skin text label sub menu c menu menu text labels menu text labels create menu assert mp notextlabels mp textlabels 1 mp notextlabels mp textlabelsonright 2 assert mp notextlabels int no labels mp notextlabels assert mp notextlabels int labels below mp textlabels assert mp notextlabels int labels right mp textlabelsonright menu text labels append menu mf string mf enabled mp notextlabels get res string ids notextlabels menu text labels append menu mf string mf enabled mp textlabels get res string ids enabletextlabels menu text labels append menu mf string mf enabled mp textlabelsonright get res string ids textlabelsonright menu text labels check menu radio item mp notextlabels mp textlabelsonright mp notextlabels int the prefs get toolbar label settings mf bycommand menu text labels enable menu item mp notextlabels int the prefs get toolbar label settings mf bycommand mf disabled menu text labels append menu mf separator menu text labels append menu mf string mp largeicons get res string ids largeicons menu text labels append menu mf string mp smallicons get res string ids smallicons assert mp largeicons mp smallicons 1 menu text labels check menu radio item mp largeicons mp smallicons m sizbtnbmp cx 16 mp smallicons mp largeicons mf bycommand menu text labels enable menu item m sizbtnbmp cx 16 mp smallicons mp largeicons mf bycommand mf disabled toolbar context menu c menu menu toolbar menu toolbar create popup menu menu toolbar append menu mf string mf popup uint ptr menu bitmaps m hmenu get res string ids toolbarskins menu toolbar append menu mf string mf popup uint ptr menu skins m hmenu get res string ids skin prof menu toolbar append menu mf string mf popup uint ptr menu text labels m hmenu get res string ids textlabels menu toolbar append menu mf string mp customizetoolbar get res string ids customizetoolbar c point point get cursor pos point menu toolbar track popup menu tpm leftalign tpm rightbutton point x point y this p result true cmuletoolbarctrl onnmrclick presult getkeystate vk_control theprefs gettoolbarbitmapsettings isempty changetoolbarbitmap theprefs gettoolbarbitmapsettings theprefs getskinprofile isempty theapp applyskin theprefs getskinprofile presult cmenu menubitmaps menubitmaps createmenu menubitmaps appendmenu mf_string mp_selecttoolbarbitmap getresstring ids_selecttoolbarbitmap menubitmaps appendmenu mf_string mp_selecttoolbarbitmapdir getresstring ids_selecttoolbarbitmapdir menubitmaps appendmenu mf_separator menubitmaps appendmenu mf_string mp_toolbarbitmap getresstring ids_default m_astrtoolbarpaths removeall cstring currentbitmapsettings theprefs gettoolbarbitmapsettings currentbitmapsettings isempty menubitmaps checkmenuitem mp_toolbarbitmap mf_checked menubitmaps enablemenuitem mp_toolbarbitmap mf_disabled m_astrtoolbarpaths _t theprefs gettoolbarbitmapfoldersettings isempty cstringarray astrtoolbarfiles _apsztbfiles win32_find_data filedata hsearch findfirstfile theprefs gettoolbarbitmapfoldersettings cstring _t _apsztbfiles filedata hsearch invalid_handle_value astrtoolbarfiles filedata cfilename astrtoolbarfiles getcount max_toolbar_files findnextfile hsearch filedata findclose hsearch astrtoolbarfiles getcount astrtoolbarfiles astrtoolbarfiles getcount cstring bitmapfilename astrtoolbarfiles getat cstring bitmapbasename psztbbaseext bitmapfilename emultb_baseext psztbbaseext bitmapbasename bitmapfilename psztbbaseext bitmapfilename bitmapbasename bitmapfilename menubitmaps appendmenu mf_string mp_toolbarbitmap bitmapbasename m_astrtoolbarpaths theprefs gettoolbarbitmapfoldersettings cstring _t bitmapfilename currentbitmapsettings comparenocase m_astrtoolbarpaths menubitmaps checkmenuitem mp_toolbarbitmap mf_checked menubitmaps enablemenuitem mp_toolbarbitmap mf_disabled astrtoolbarfiles getcount menubitmaps appendmenu mf_string mp_toolbarbitmap currentbitmapsettings menubitmaps checkmenuitem mp_toolbarbitmap mf_checked menubitmaps enablemenuitem mp_toolbarbitmap mf_disabled m_astrtoolbarpaths currentbitmapsettings cmenu menuskins menuskins createmenu menuskins appendmenu mf_string mp_select_skin_file getresstring ids_sel_skin menuskins appendmenu mf_string mp_select_skin_dir getresstring ids_sel_skindir menuskins appendmenu mf_separator menuskins appendmenu mf_string mp_skin_profile getresstring ids_default m_astrskinpaths removeall cstring currentskin theprefs getskinprofile currentskin isempty menuskins checkmenuitem mp_skin_profile mf_checked menuskins enablemenuitem mp_skin_profile mf_disabled m_astrskinpaths _t theprefs getskinprofiledir isempty cstringarray astrskinfiles _apszskinfiles win32_find_data filedata hsearch findfirstfile theprefs getskinprofiledir cstring _t _apszskinfiles filedata hsearch invalid_handle_value astrskinfiles filedata cfilename astrskinfiles getcount max_skin_files findnextfile hsearch filedata findclose hsearch astrskinfiles getcount astrskinfiles astrskinfiles getcount cstring skinfilename astrskinfiles getat cstring skinbasename pszskinbaseext skinfilename _t emulskin_baseext _t pszskinbaseext skinbasename skinfilename pszskinbaseext skinfilename skinbasename skinfilename menuskins appendmenu mf_string mp_skin_profile skinbasename m_astrskinpaths theprefs getskinprofiledir cstring _t skinfilename currentskin comparenocase m_astrskinpaths menuskins checkmenuitem mp_skin_profile mf_checked menuskins enablemenuitem mp_skin_profile mf_disabled astrskinfiles getcount menuskins appendmenu mf_string mp_skin_profile currentskin menuskins checkmenuitem mp_skin_profile mf_checked menuskins enablemenuitem mp_skin_profile mf_disabled m_astrskinpaths currentskin cmenu menutextlabels menutextlabels createmenu mp_notextlabels mp_textlabels mp_notextlabels mp_textlabelsonright mp_notextlabels nolabels mp_notextlabels mp_notextlabels labelsbelow mp_textlabels mp_notextlabels labelsright mp_textlabelsonright menutextlabels appendmenu mf_string mf_enabled mp_notextlabels getresstring ids_notextlabels menutextlabels appendmenu mf_string mf_enabled mp_textlabels getresstring ids_enabletextlabels menutextlabels appendmenu mf_string mf_enabled mp_textlabelsonright getresstring ids_textlabelsonright menutextlabels checkmenuradioitem mp_notextlabels mp_textlabelsonright mp_notextlabels theprefs gettoolbarlabelsettings mf_bycommand menutextlabels enablemenuitem mp_notextlabels theprefs gettoolbarlabelsettings mf_bycommand mf_disabled menutextlabels appendmenu mf_separator menutextlabels appendmenu mf_string mp_largeicons getresstring ids_largeicons menutextlabels appendmenu mf_string mp_smallicons getresstring ids_smallicons mp_largeicons mp_smallicons menutextlabels checkmenuradioitem mp_largeicons mp_smallicons m_sizbtnbmp mp_smallicons mp_largeicons mf_bycommand menutextlabels enablemenuitem m_sizbtnbmp mp_smallicons mp_largeicons mf_bycommand mf_disabled cmenu menutoolbar menutoolbar createpopupmenu menutoolbar appendmenu mf_string mf_popup uint_ptr menubitmaps m_hmenu getresstring ids_toolbarskins menutoolbar appendmenu mf_string mf_popup uint_ptr menuskins m_hmenu getresstring ids_skin_prof menutoolbar appendmenu mf_string mf_popup uint_ptr menutextlabels m_hmenu getresstring ids_textlabels menutoolbar appendmenu mf_string mp_customizetoolbar getresstring ids_customizetoolbar cpoint getcursorpos menutoolbar trackpopupmenu tpm_leftalign tpm_rightbutton presult void c mule toolbar ctrl on tbn query delete nmhdr pnmhdr lresult p result p result true cmuletoolbarctrl ontbnquerydelete presult presult void c mule toolbar ctrl on tbn query insert nmhdr pnmhdr lresult p result p result true cmuletoolbarctrl ontbnqueryinsert presult presult void c mule toolbar ctrl on tbn get button info nmhdr pnmhdr lresult p result lpnmtoolbar pnmtb reinterpret cast lpnmtoolbar pnmhdr if pnmtb i item arrsize tb buttons p result false else c string str text tb strings pnmtb i item str text remove t tcsncpy pnmtb psz text str text pnmtb cch text 1 pnmtb psz text pnmtb cch text 1 t 0 pnmtb tb button tb buttons pnmtb i item if m elabeltype labels right pnmtb tb button fs style tbstyle autosize p result true cmuletoolbarctrl ontbngetbuttoninfo presult reinterpret_cast iitem tbbuttons presult cstring strtext tbstrings iitem strtext _t _tcsncpy psztext strtext cchtext psztext cchtext _t tbbutton tbbuttons iitem m_elabeltype labelsright tbbutton fsstyle tbstyle_autosize presult void c mule toolbar ctrl on tbn toolbar change nmhdr pnmhdr lresult p result c string config for int i 0 i get button count i tbbutton buttoninfo if get button i buttoninfo config append format t 02i buttoninfo id command 0 buttoninfo id command idc toolbarbutton 99 the prefs set toolbar settings config localize the app emuledlg show connection state set all buttons width auto size p result 0 cmuletoolbarctrl ontbntoolbarchange presult cstring getbuttoncount getbutton appendformat _t idcommand idcommand idc_toolbarbutton theprefs settoolbarsettings theapp showconnectionstate setallbuttonswidth autosize presult void c mule toolbar ctrl on tbn reset nmhdr pnmhdr lresult p result first get rid of old buttons while saving their states for int i get button count 1 i 0 i tbbutton button get button i button for int j 0 j m buttoncount j if tb buttons j id command button id command tb buttons j fs state button fs state tb buttons j fs style button fs style tb buttons j i string button i string delete button i tbbutton sep button sep button id command 0 sep button fs style tbstyle sep sep button fs state tbstate enabled sep button i string 1 sep button i bitmap 1 set default configuration c string config str default toolbar for i 0 i config get length i 2 int index tstoi config mid i 2 if index 99 add buttons 1 sep button continue add buttons 1 tb buttons index save new default configuration the prefs set toolbar settings config localize we have to localize the button text the app emuledlg show connection state change text label style the prefs get toolbar label settings false true set all buttons width then calc and set the button width auto size cmuletoolbarctrl ontbnreset presult getbuttoncount getbutton m_buttoncount tbbuttons idcommand idcommand tbbuttons fsstate fsstate tbbuttons fsstyle fsstyle tbbuttons istring istring deletebutton sepbutton sepbutton idcommand sepbutton fsstyle tbstyle_sep sepbutton fsstate tbstate_enabled sepbutton istring sepbutton ibitmap cstring strdefaulttoolbar getlength _tstoi addbuttons sepbutton addbuttons tbbuttons theprefs settoolbarsettings theapp showconnectionstate changetextlabelstyle theprefs gettoolbarlabelsettings setallbuttonswidth autosize void c mule toolbar ctrl on tbn init customize nmhdr pnmhdr lresult p result p result tbnrf hidehelp cmuletoolbarctrl ontbninitcustomize presult presult tbnrf_hidehelp void c mule toolbar ctrl on tbn end adjust nmhdr lresult p result update ideal size p result 0 return value is ignored cmuletoolbarctrl ontbnendadjust presult updateidealsize presult c en bitmap c en bitmap cenbitmap cenbitmap c en bitmap c en bitmap cenbitmap cenbitmap bool c en bitmap load image lpctstr sz image path colorref cr back assert m hobject null only attach once detach on destroy if m hobject null return false if gdi is available use that api because it supports more file formats and images with alpha channels that dll is installed with winxp is available as redistributable from microsoft for win98 as this dll may not be available on some os but we have to link statically to it we have to take some special care note do not forget to specify delayload gdiplus dll as link parameter static int bgdiplusinstalled 1 if bgdiplusinstalled 1 bgdiplusinstalled 0 hmodule h lib load library t gdiplus dll if h lib null bgdiplusinstalled get proc address h lib gdiplus startup null free library h lib if bgdiplusinstalled 0 c image img if succeeded img load sz image path c bitmap attach img detach return true bool b result false c file c file c file exception e if c file open sz image path c file mode read c file type binary c file share deny write e int n size int c file get length byte p buff new byte n size if c file read p buff n size 0 i picture p picture load from buffer p buff n size if p picture b result attach p picture cr back p picture release delete p buff return b result cenbitmap loadimage szimagepath crback m_hobject m_hobject _bgdiplusinstalled _bgdiplusinstalled _bgdiplusinstalled hlib loadlibrary _t hlib _bgdiplusinstalled getprocaddress hlib gdiplusstartup freelibrary hlib _bgdiplusinstalled cimage szimagepath cbitmap bresult cfile cfile cfileexception cfile szimagepath cfile moderead cfile typebinary cfile sharedenywrite nsize cfile getlength pbuff nsize cfile pbuff nsize ipicture ppicture loadfrombuffer pbuff nsize ppicture bresult ppicture crback ppicture pbuff bresult bool c en bitmap load image uint uid res lpctstr psz resource type hmodule h inst colorref cr back return load image makeintresource uid res psz resource type h inst cr back cenbitmap loadimage uidres pszresourcetype hinst crback loadimage uidres pszresourcetype hinst crback bool c en bitmap load image lpctstr lpsz resource name lpctstr sz resource type hmodule h inst colorref cr back assert m hobject null only attach once detach on destroy if m hobject null return false byte p buff null int n size 0 bool b result false first call is to get buffer size if get resource lpsz resource name sz resource type h inst 0 n size if n size 0 p buff new byte n size this loads it if get resource lpsz resource name sz resource type h inst p buff n size i picture p picture load from buffer p buff n size if p picture b result attach p picture cr back p picture release delete p buff return b result cenbitmap loadimage lpszresourcename szresourcetype hinst crback m_hobject m_hobject pbuff nsize bresult getresource lpszresourcename szresourcetype hinst nsize nsize pbuff nsize getresource lpszresourcename szresourcetype hinst pbuff nsize ipicture ppicture loadfrombuffer pbuff nsize ppicture bresult ppicture crback ppicture pbuff bresult bool c en bitmap get resource lpctstr lp name lpctstr lp type hmodule h inst void p resource int n buf size hrsrc h res info handle h res lpstr lp res null bool b result false find the resource h res info find resource h inst lp name lp type if h res info null return false load the resource h res load resource h inst h res info if h res null return false lock the resource lp res char lock resource h res if lp res null if p resource null n buf size sizeof resource h inst h res info b result true else if n buf size int sizeof resource h inst h res info memcpy p resource lp res n buf size b result true unlock resource h res free the resource free resource h res return b result cenbitmap getresource lpname lptype hinst presource nbufsize hresinfo hres lpres bresult hresinfo findresource hinst lpname lptype hresinfo hres loadresource hinst hresinfo hres lpres lockresource hres lpres presource nbufsize sizeofresource hinst hresinfo bresult nbufsize sizeofresource hinst hresinfo presource lpres nbufsize bresult unlockresource hres freeresource hres bresult i picture c en bitmap load from buffer byte p buff int n size i picture p picture null hglobal h global global alloc gmem moveable n size if h global null void p data global lock h global if p data null memcpy p data p buff n size global unlock h global i stream p stream null if create stream onh global h global true f delete on release p stream s ok not sure what the keep original format property is really used for but if ole load picture is invoked with f runmode false the function always creates a temporary file which even does not get deleted when all com pointers were released it eventually gets deleted only when process terminated using f runmode true does prevent this behaviour and does not seem to have any other side effects verify ole load picture p stream n size true false iid ipicture lpvoid p picture s ok p stream release else global free h global else global free h global return p picture caller releases ipicture cenbitmap loadfrombuffer pbuff nsize ipicture ppicture hglobal globalalloc gmem_moveable nsize hglobal pdata globallock hglobal pdata pdata pbuff nsize globalunlock hglobal istream pstream createstreamonhglobal hglobal fdeleteonrelease pstream s_ok keeporiginalformat oleloadpicture frunmode frunmode oleloadpicture pstream nsize iid_ipicture ppicture s_ok pstream globalfree hglobal globalfree hglobal ppicture bool c en bitmap attach i picture p picture colorref cr back assert m hobject null only attach once detach on destroy if m hobject null return false assert p picture if p picture return false bool b result false cdc dc mem cdc pdc c wnd get desktop window getdc if dc mem create compatibledc pdc long hm width long hm height p picture get width hm width p picture get height hm height int n width mul div hm width pdc get device caps logpixelsx himetric inch int n height mul div hm height pdc get device caps logpixelsy himetric inch c bitmap bm mem if bm mem create compatible bitmap pdc n width n height c bitmap p oldbm dc mem select object bm mem if cr back 1 dc mem fill solid rect 0 0 n width n height cr back hresult hr p picture render dc mem 0 0 n width n height 0 hm height hm width hm height null dc mem select object p oldbm if hr s ok b result c bitmap attach bm mem detach c wnd get desktop window releasedc pdc return b result cenbitmap ipicture ppicture crback m_hobject m_hobject ppicture ppicture bresult dcmem cwnd getdesktopwindow dcmem createcompatibledc hmwidth hmheight ppicture get_width hmwidth ppicture get_height hmheight nwidth muldiv hmwidth getdevicecaps himetric_inch nheight muldiv hmheight getdevicecaps himetric_inch cbitmap bmmem bmmem createcompatiblebitmap nwidth nheight cbitmap poldbm dcmem selectobject bmmem crback dcmem fillsolidrect nwidth nheight crback ppicture dcmem nwidth nheight hmheight hmwidth hmheight dcmem selectobject poldbm s_ok bresult cbitmap bmmem cwnd getdesktopwindow bresult void c input box on context menu c wnd p wnd c point point cax2 nothing to see here cinputbox oncontextmenu cwnd pwnd cpoint void set colors colorref cr text colorref crlb colorref crrt m crtextcolor cr text m crcolorlb crlb m crcolorrt crrt setcolors crtext m_crtextcolor crtext m_crcolorlb m_crcolorrt c gradient static c gradient static m binit true m bhorizontal true m binvert false m crcolorlb rgb 0 0 0 m crcolorrt rgb 255 255 255 m crtextcolor rgb 127 127 127 cgradientstatic cgradientstatic m_binit m_bhorizontal m_binvert m_crcolorlb m_crcolorrt m_crtextcolor void c gradient static set font c font p font logfont lf font p font get log font lf font if m cffont get safe handle m cffont delete object m cffont create font indirect lf font cgradientstatic setfont cfont pfont lffont pfont getlogfont lffont m_cffont getsafehandle m_cffont deleteobject m_cffont createfontindirect lffont c gradient static c gradient static if m mem dc get safe hdc m mem pold m mem dc select object m mem pold if m mem bmp get safe handle m mem bmp delete object if m mem dc get safe hdc m mem dc deletedc cgradientstatic cgradientstatic m_mem getsafehdc m_mem m_mem selectobject m_mem m_mem getsafehandle m_mem deleteobject m_mem getsafehdc m_mem void c gradient static on paint c paintdc dc this device context for painting c rect r client get client rect r client if m binit create gradient dc r client m binit false dc bit blt 0 0 m mem cx m mem cy m mem dc 0 0 srccopy cgradientstatic onpaint cpaintdc crect rclient getclientrect rclient m_binit creategradient rclient m_binit bitblt m_mem m_mem m_mem void c gradient static draw vertical text c rect p rect c font p old font null logfont lf font if m cffont get safe handle m cffont get log font lf font else c font p font get font p font get log font lf font tcscpy lf font lf face name t arial some fonts won t turn lf font lf escapement 900 c font font font create font indirect lf font p old font m mem dc select object font c string str text get window text str text m mem dc set text color m crtextcolor m mem dc set bk color transparent c rect r text p rect r text bottom 5 draw rotated text m mem dc m hdc str text r text 90 m mem dc select object p old font cgradientstatic drawverticaltext crect prect cfont poldfont lffont m_cffont getsafehandle m_cffont getlogfont lffont cfont pfont getfont pfont getlogfont lffont _tcscpy lffont lffacename _t lffont lfescapement cfont createfontindirect lffont poldfont m_mem selectobject cstring strtext getwindowtext strtext m_mem settextcolor m_crtextcolor m_mem setbkcolor crect rtext prect rtext drawrotatedtext m_mem m_hdc strtext rtext m_mem selectobject poldfont void c gradient static draw horizontal text c rect p rect c font p old font null if m cffont get safe handle p old font m mem dc select object m cffont c string str text get window text str text m mem dc set text color m crtextcolor m mem dc set bk mode transparent m mem dc draw text str text p rect dt left dt singleline dt vcenter dt end ellipsis if p old font m mem dc select object p old font cgradientstatic drawhorizontaltext crect prect cfont poldfont m_cffont getsafehandle poldfont m_mem selectobject m_cffont cstring strtext getwindowtext strtext m_mem settextcolor m_crtextcolor m_mem setbkmode m_mem drawtext strtext prect dt_left dt_singleline dt_vcenter dt_end_ellipsis poldfont m_mem selectobject poldfont void c gradient static draw vertical gradient double dbl rstep getr value m crcolorlb getr value m crcolorrt static cast double m mem cy double dbl gstep getg value m crcolorlb getg value m crcolorrt static cast double m mem cy double dbl bstep getb value m crcolorlb getb value m crcolorrt static cast double m mem cy double r getr value m crcolorrt double g getg value m crcolorrt double b getb value m crcolorrt for int y 0 y m mem cy y c pen pen ps solid 1 rgb r g b p old p old m mem dc select object pen m mem dc move to 0 y m mem dc line to m mem cx y m mem dc select object p old r dbl rstep g dbl gstep b dbl bstep cgradientstatic drawverticalgradient dblrstep getrvalue m_crcolorlb getrvalue m_crcolorrt static_cast m_mem dblgstep getgvalue m_crcolorlb getgvalue m_crcolorrt static_cast m_mem dblbstep getbvalue m_crcolorlb getbvalue m_crcolorrt static_cast m_mem getrvalue m_crcolorrt getgvalue m_crcolorrt getbvalue m_crcolorrt m_mem cpen ps_solid pold pold m_mem selectobject m_mem moveto m_mem lineto m_mem m_mem selectobject pold dblrstep dblgstep dblbstep void c gradient static draw horizontal gradient double dbl rstep getr value m crcolorrt getr value m crcolorlb static cast double m mem cx double dbl gstep getg value m crcolorrt getg value m crcolorlb static cast double m mem cx double dbl bstep getb value m crcolorrt getb value m crcolorlb static cast double m mem cx double r getr value m crcolorlb double g getg value m crcolorlb double b getb value m crcolorlb for int x 0 x m mem cx x c pen pen ps solid 1 rgb r g b c pen p old m mem dc select object pen m mem dc move to x 0 m mem dc line to x m mem cy m mem dc select object p old r dbl rstep g dbl gstep b dbl bstep cgradientstatic drawhorizontalgradient dblrstep getrvalue m_crcolorrt getrvalue m_crcolorlb static_cast m_mem dblgstep getgvalue m_crcolorrt getgvalue m_crcolorlb static_cast m_mem dblbstep getbvalue m_crcolorrt getbvalue m_crcolorlb static_cast m_mem getrvalue m_crcolorlb getgvalue m_crcolorlb getbvalue m_crcolorlb m_mem cpen ps_solid cpen pold m_mem selectobject m_mem moveto m_mem lineto m_mem m_mem selectobject pold dblrstep dblgstep dblbstep void c gradient static create gradient cdc pdc c rect p rect m mem cx p rect width m mem cy p rect height if m mem dc get safe hdc if m mem bmp get safe handle m mem pold m mem dc select object m mem pold m mem dc deletedc m mem dc create compatibledc pdc if m mem bmp get safe handle m mem bmp delete object m mem bmp create compatible bitmap pdc m mem cx m mem cy m mem pold m mem dc select object m mem bmp if m bhorizontal draw horizontal gradient draw horizontal text p rect else draw vertical gradient draw vertical text p rect cgradientstatic creategradient crect prect m_mem prect m_mem prect m_mem getsafehdc m_mem getsafehandle m_mem m_mem selectobject m_mem m_mem m_mem createcompatibledc m_mem getsafehandle m_mem deleteobject m_mem createcompatiblebitmap m_mem m_mem m_mem m_mem selectobject m_mem m_bhorizontal drawhorizontalgradient drawhorizontaltext prect drawverticalgradient drawverticaltext prect c dialog c mule systray dlg idd p parent if i cur down unlimited i cur down 0 if i cur up unlimited i cur up 0 afx data init c mule systray dlg m ndownspeedtxt i max down i cur down i max down i cur down m nupspeedtxt i max up i cur up i max up i cur up afx data init m imaxup i max up m imaxdown i max down m ptinitialposition pt m huparrow null m hdownarrow null m nexitcode 0 m bclosingdown false cdialog cmulesystraydlg pparent icurdown icurdown icurup icurup afx_data_init cmulesystraydlg m_ndownspeedtxt imaxdown icurdown imaxdown icurdown m_nupspeedtxt imaxup icurup imaxup icurup afx_data_init m_imaxup imaxup m_imaxdown imaxdown m_ptinitialposition m_huparrow m_hdownarrow m_nexitcode m_bclosingdown c mule systray dlg c mule systray dlg if m huparrow destroy icon m huparrow if m hdownarrow destroy icon m hdownarrow cmulesystraydlg cmulesystraydlg m_huparrow destroyicon m_huparrow m_hdownarrow destroyicon m_hdownarrow void c mule systray dlg do data exchange c data exchange pdx c dialog do data exchange pdx afx data map c mule systray dlg ddx control pdx idc trayup m ctrluparrow ddx control pdx idc traydown m ctrldownarrow ddx control pdx idc sidebar m ctrlsidebar ddx control pdx idc upsld m ctrlupspeedsld ddx control pdx idc downsld m ctrldownspeedsld ddx control pdx idc downtxt m downspeedinput ddx control pdx idc uptxt m upspeedinput ddx text pdx idc downtxt m ndownspeedtxt ddx text pdx idc uptxt m nupspeedtxt afx data map cmulesystraydlg dodataexchange cdataexchange cdialog dodataexchange afx_data_map cmulesystraydlg ddx_control idc_trayup m_ctrluparrow ddx_control idc_traydown m_ctrldownarrow ddx_control idc_sidebar m_ctrlsidebar ddx_control idc_upsld m_ctrlupspeedsld ddx_control idc_downsld m_ctrldownspeedsld ddx_control idc_downtxt m_downspeedinput ddx_control idc_uptxt m_upspeedinput ddx_text idc_downtxt m_ndownspeedtxt ddx_text idc_uptxt m_nupspeedtxt afx_data_map bool c mule systray dlg on command wparam w param lparam l param if hiword w param bn clicked release capture m nexitcode loword w param end dialog m nexitcode m bclosingdown true return c dialog on command w param l param cmulesystraydlg oncommand wparam lparam wparam bn_clicked releasecapture m_nexitcode wparam enddialog m_nexitcode m_bclosingdown cdialog oncommand wparam lparam void c mule systray dlg on mouse move uint n flags c point point c wnd p wnd child window from point point cwp skipinvisible cwp skipdisabled if p wnd if p wnd this p wnd m ctrlsidebar set capture me myself and i else release capture sweet child of mine else set capture i m on the outside i m looking in c dialog on mouse move n flags point cmulesystraydlg onmousemove nflags cpoint cwnd pwnd childwindowfrompoint cwp_skipinvisible cwp_skipdisabled pwnd pwnd pwnd m_ctrlsidebar setcapture releasecapture setcapture cdialog onmousemove nflags bool c mule systray dlg on init dialog c dialog on init dialog m bclosingdown false c rect r c wnd p m huparrow the app load icon t upload m hdownarrow the app load icon t download m ctrluparrow set icon m huparrow m ctrldownarrow set icon m hdownarrow bool b valid font false logfont lf static font 0 p get dlg item idc speed if p p get font get log font lf static font b valid font true p get dlg item idc speed if p p get window rect r screen to client r m ctrlspeed create null null ws child ws visible r this idc speed m ctrlspeed m nbtnid idc speed p get window text m ctrlspeed m strtext m ctrlspeed m strtext get res string ids traydlg speed m ctrlspeed m strtext remove t m ctrlspeed m buseicon true m ctrlspeed m sicon cx 16 m ctrlspeed m sicon cy 16 m ctrlspeed m hicon the app load icon t speed m ctrlspeed m sicon cx m ctrlspeed m sicon cy m ctrlspeed m bparentcapture true if b valid font logfont lf font lf static font lf font lf weight 200 make it bold m ctrlspeed m cffont create font indirect lf font m ctrlspeed m bnohover true p get dlg item idc tomax if p p get window rect r screen to client r m ctrlalltomax create null null ws child ws visible r this idc tomax m ctrlalltomax m nbtnid idc tomax p get window text m ctrlalltomax m strtext m ctrlalltomax m strtext get res string ids pw ua m ctrlalltomax m strtext remove t m ctrlalltomax m buseicon true m ctrlalltomax m sicon cx 16 m ctrlalltomax m sicon cy 16 m ctrlalltomax m hicon the app load icon t speedmax m ctrlalltomax m sicon cx m ctrlalltomax m sicon cy m ctrlalltomax m bparentcapture true if b valid font m ctrlalltomax m cffont create font indirect lf static font p get dlg item idc tomin if p p get window rect r screen to client r m ctrlalltomin create null null ws child ws visible r this idc tomin m ctrlalltomin m nbtnid idc tomin p get window text m ctrlalltomin m strtext m ctrlalltomin m strtext get res string ids pw pa m ctrlalltomin m strtext remove t m ctrlalltomin m buseicon true m ctrlalltomin m sicon cx 16 m ctrlalltomin m sicon cy 16 m ctrlalltomin m hicon the app load icon t speedmin m ctrlalltomin m sicon cx m ctrlalltomin m sicon cy m ctrlalltomin m bparentcapture true if b valid font m ctrlalltomin m cffont create font indirect lf static font p get dlg item idc restore if p p get window rect r screen to client r m ctrlrestore create null null ws child ws visible r this idc restore m ctrlrestore m nbtnid idc restore p get window text m ctrlrestore m strtext m ctrlrestore m strtext get res string ids main popup restore m ctrlrestore m strtext remove t m ctrlrestore m buseicon true m ctrlrestore m sicon cx 16 m ctrlrestore m sicon cy 16 m ctrlrestore m hicon the app load icon t restorewindow m ctrlrestore m sicon cx m ctrlrestore m sicon cy m ctrlrestore m bparentcapture true if b valid font logfont lf font lf static font lf font lf weight 200 make it bold m ctrlrestore m cffont create font indirect lf font p get dlg item idc connect if p p get window rect r screen to client r m ctrlconnect create null null ws child ws visible r this idc connect m ctrlconnect m nbtnid idc connect p get window text m ctrlconnect m strtext m ctrlconnect m strtext get res string ids main btn connect m ctrlconnect m strtext remove t m ctrlconnect m buseicon true m ctrlconnect m sicon cx 16 m ctrlconnect m sicon cy 16 m ctrlconnect m hicon the app load icon t connect m ctrlconnect m sicon cx m ctrlconnect m sicon cy m ctrlconnect m bparentcapture true if b valid font m ctrlconnect m cffont create font indirect lf static font p get dlg item idc disconnect if p p get window rect r screen to client r m ctrldisconnect create null null ws child ws visible r this idc disconnect m ctrldisconnect m nbtnid idc disconnect p get window text m ctrldisconnect m strtext m ctrldisconnect m strtext get res string ids main btn disconnect m ctrldisconnect m strtext remove t m ctrldisconnect m buseicon true m ctrldisconnect m sicon cx 16 m ctrldisconnect m sicon cy 16 m ctrldisconnect m hicon the app load icon t disconnect m ctrldisconnect m sicon cx m ctrldisconnect m sicon cy m ctrldisconnect m bparentcapture true if b valid font m ctrldisconnect m cffont create font indirect lf static font p get dlg item idc preferences if p p get window rect r screen to client r m ctrlpreferences create null null ws child ws visible r this idc preferences m ctrlpreferences m nbtnid idc preferences p get window text m ctrlpreferences m strtext m ctrlpreferences m strtext get res string ids em prefs m ctrlpreferences m strtext remove t m ctrlpreferences m buseicon true m ctrlpreferences m sicon cx 16 m ctrlpreferences m sicon cy 16 m ctrlpreferences m hicon the app load icon t preferences m ctrlpreferences m sicon cx m ctrlpreferences m sicon cy m ctrlpreferences m bparentcapture true if b valid font m ctrlpreferences m cffont create font indirect lf static font p get dlg item idc tray exit if p p get window rect r screen to client r m ctrlexit create null null ws child ws visible r this idc exit m ctrlexit m nbtnid idc exit p get window text m ctrlexit m strtext m ctrlexit m strtext get res string ids exit m ctrlexit m strtext remove t m ctrlexit m buseicon true m ctrlexit m sicon cx 16 m ctrlexit m sicon cy 16 m ctrlexit m hicon the app load icon t exit m ctrlexit m sicon cx m ctrlexit m sicon cy m ctrlexit m bparentcapture true if b valid font m ctrlexit m cffont create font indirect lf static font if p get dlg item idc downlbl null p set window text get res string ids pw con downlbl if p get dlg item idc uplbl null p set window text get res string ids pw con uplbl if p get dlg item idc downkb null p set window text get res string ids kbytespersec if p get dlg item idc upkb null p set window text get res string ids kbytespersec m ctrldownspeedsld set range 0 m imaxdown m ctrldownspeedsld set pos m ndownspeedtxt m ctrlupspeedsld set range 0 m imaxup m ctrlupspeedsld set pos m nupspeedtxt m downspeedinput enable window m ndownspeedtxt 0 m upspeedinput enable window m nupspeedtxt 0 c font font font create font 16 0 900 0 700 0 0 0 0 3 2 1 34 t tahoma uint winver the prefs get windows version if winver winver 95 winver winver nt4 g blowcolordesktop m ctrlsidebar set colors get sys color color captiontext get sys color color activecaption get sys color color activecaption else m ctrlsidebar set colors get sys color color captiontext get sys color color activecaption get sys color color gradientactivecaption m ctrlsidebar set horizontal false m ctrlsidebar set font font m ctrlsidebar set window text t e mule the app m strcurversionlong c rect r desktop c wnd p desktop wnd get desktop window p desktop wnd get client rect r desktop c point pt m ptinitialposition p desktop wnd screen to client pt int xpos ypos get window rect r if m ptinitialposition x r width r desktop right xpos pt x else xpos pt x r width if m ptinitialposition y r height r desktop top ypos pt y else ypos pt y r height move window xpos ypos r width r height set capture return true return true unless you set the focus to a control exception ocx property pages should return false cmulesystraydlg oninitdialog cdialog oninitdialog m_bclosingdown crect cwnd m_huparrow theapp loadicon _t m_hdownarrow theapp loadicon _t m_ctrluparrow seticon m_huparrow m_ctrldownarrow seticon m_hdownarrow bvalidfont lfstaticfont getdlgitem idc_speed getfont getlogfont lfstaticfont bvalidfont getdlgitem idc_speed getwindowrect screentoclient m_ctrlspeed ws_child ws_visible idc_speed m_ctrlspeed m_nbtnid idc_speed getwindowtext m_ctrlspeed m_strtext m_ctrlspeed m_strtext getresstring ids_traydlg_speed m_ctrlspeed m_strtext _t m_ctrlspeed m_buseicon m_ctrlspeed m_sicon m_ctrlspeed m_sicon m_ctrlspeed m_hicon theapp loadicon _t m_ctrlspeed m_sicon m_ctrlspeed m_sicon m_ctrlspeed m_bparentcapture bvalidfont lffont lfstaticfont lffont lfweight m_ctrlspeed m_cffont createfontindirect lffont m_ctrlspeed m_bnohover getdlgitem idc_tomax getwindowrect screentoclient m_ctrlalltomax ws_child ws_visible idc_tomax m_ctrlalltomax m_nbtnid idc_tomax getwindowtext m_ctrlalltomax m_strtext m_ctrlalltomax m_strtext getresstring ids_pw_ua m_ctrlalltomax m_strtext _t m_ctrlalltomax m_buseicon m_ctrlalltomax m_sicon m_ctrlalltomax m_sicon m_ctrlalltomax m_hicon theapp loadicon _t m_ctrlalltomax m_sicon m_ctrlalltomax m_sicon m_ctrlalltomax m_bparentcapture bvalidfont m_ctrlalltomax m_cffont createfontindirect lfstaticfont getdlgitem idc_tomin getwindowrect screentoclient m_ctrlalltomin ws_child ws_visible idc_tomin m_ctrlalltomin m_nbtnid idc_tomin getwindowtext m_ctrlalltomin m_strtext m_ctrlalltomin m_strtext getresstring ids_pw_pa m_ctrlalltomin m_strtext _t m_ctrlalltomin m_buseicon m_ctrlalltomin m_sicon m_ctrlalltomin m_sicon m_ctrlalltomin m_hicon theapp loadicon _t m_ctrlalltomin m_sicon m_ctrlalltomin m_sicon m_ctrlalltomin m_bparentcapture bvalidfont m_ctrlalltomin m_cffont createfontindirect lfstaticfont getdlgitem idc_restore getwindowrect screentoclient m_ctrlrestore ws_child ws_visible idc_restore m_ctrlrestore m_nbtnid idc_restore getwindowtext m_ctrlrestore m_strtext m_ctrlrestore m_strtext getresstring ids_main_popup_restore m_ctrlrestore m_strtext _t m_ctrlrestore m_buseicon m_ctrlrestore m_sicon m_ctrlrestore m_sicon m_ctrlrestore m_hicon theapp loadicon _t m_ctrlrestore m_sicon m_ctrlrestore m_sicon m_ctrlrestore m_bparentcapture bvalidfont lffont lfstaticfont lffont lfweight m_ctrlrestore m_cffont createfontindirect lffont getdlgitem idc_connect getwindowrect screentoclient m_ctrlconnect ws_child ws_visible idc_connect m_ctrlconnect m_nbtnid idc_connect getwindowtext m_ctrlconnect m_strtext m_ctrlconnect m_strtext getresstring ids_main_btn_connect m_ctrlconnect m_strtext _t m_ctrlconnect m_buseicon m_ctrlconnect m_sicon m_ctrlconnect m_sicon m_ctrlconnect m_hicon theapp loadicon _t m_ctrlconnect m_sicon m_ctrlconnect m_sicon m_ctrlconnect m_bparentcapture bvalidfont m_ctrlconnect m_cffont createfontindirect lfstaticfont getdlgitem idc_disconnect getwindowrect screentoclient m_ctrldisconnect ws_child ws_visible idc_disconnect m_ctrldisconnect m_nbtnid idc_disconnect getwindowtext m_ctrldisconnect m_strtext m_ctrldisconnect m_strtext getresstring ids_main_btn_disconnect m_ctrldisconnect m_strtext _t m_ctrldisconnect m_buseicon m_ctrldisconnect m_sicon m_ctrldisconnect m_sicon m_ctrldisconnect m_hicon theapp loadicon _t m_ctrldisconnect m_sicon m_ctrldisconnect m_sicon m_ctrldisconnect m_bparentcapture bvalidfont m_ctrldisconnect m_cffont createfontindirect lfstaticfont getdlgitem idc_preferences getwindowrect screentoclient m_ctrlpreferences ws_child ws_visible idc_preferences m_ctrlpreferences m_nbtnid idc_preferences getwindowtext m_ctrlpreferences m_strtext m_ctrlpreferences m_strtext getresstring ids_em_prefs m_ctrlpreferences m_strtext _t m_ctrlpreferences m_buseicon m_ctrlpreferences m_sicon m_ctrlpreferences m_sicon m_ctrlpreferences m_hicon theapp loadicon _t m_ctrlpreferences m_sicon m_ctrlpreferences m_sicon m_ctrlpreferences m_bparentcapture bvalidfont m_ctrlpreferences m_cffont createfontindirect lfstaticfont getdlgitem idc_tray_exit getwindowrect screentoclient m_ctrlexit ws_child ws_visible idc_exit m_ctrlexit m_nbtnid idc_exit getwindowtext m_ctrlexit m_strtext m_ctrlexit m_strtext getresstring ids_exit m_ctrlexit m_strtext _t m_ctrlexit m_buseicon m_ctrlexit m_sicon m_ctrlexit m_sicon m_ctrlexit m_hicon theapp loadicon _t m_ctrlexit m_sicon m_ctrlexit m_sicon m_ctrlexit m_bparentcapture bvalidfont m_ctrlexit m_cffont createfontindirect lfstaticfont getdlgitem idc_downlbl setwindowtext getresstring ids_pw_con_downlbl getdlgitem idc_uplbl setwindowtext getresstring ids_pw_con_uplbl getdlgitem idc_downkb setwindowtext getresstring ids_kbytespersec getdlgitem idc_upkb setwindowtext getresstring ids_kbytespersec m_ctrldownspeedsld setrange m_imaxdown m_ctrldownspeedsld setpos m_ndownspeedtxt m_ctrlupspeedsld setrange m_imaxup m_ctrlupspeedsld setpos m_nupspeedtxt m_downspeedinput enablewindow m_ndownspeedtxt m_upspeedinput enablewindow m_nupspeedtxt cfont createfont _t theprefs getwindowsversion _winver_95_ _winver_nt4_ g_blowcolordesktop m_ctrlsidebar setcolors getsyscolor color_captiontext getsyscolor color_activecaption getsyscolor color_activecaption m_ctrlsidebar setcolors getsyscolor color_captiontext getsyscolor color_activecaption getsyscolor color_gradientactivecaption m_ctrlsidebar sethorizontal m_ctrlsidebar setfont m_ctrlsidebar setwindowtext _t emule theapp m_strcurversionlong crect rdesktop cwnd pdesktopwnd getdesktopwindow pdesktopwnd getclientrect rdesktop cpoint m_ptinitialposition pdesktopwnd screentoclient getwindowrect m_ptinitialposition rdesktop m_ptinitialposition rdesktop movewindow setcapture void c mule systray dlg on change downtxt update data if the prefs get max graph download rate unlimited cax2 shouldn t be anymore if m ndownspeedtxt 64 cax2 why 64 m ndownspeedtxt 64 else if m ndownspeedtxt the prefs get max graph download rate m ndownspeedtxt the prefs get max graph download rate m ctrldownspeedsld set pos m ndownspeedtxt if m ndownspeedtxt 1 m ndownspeedtxt 0 m downspeedinput enable window false the prefs set max download m ndownspeedtxt 0 unlimited m ndownspeedtxt update data false cmulesystraydlg onchangedowntxt updatedata theprefs getmaxgraphdownloadrate m_ndownspeedtxt m_ndownspeedtxt m_ndownspeedtxt theprefs getmaxgraphdownloadrate m_ndownspeedtxt theprefs getmaxgraphdownloadrate m_ctrldownspeedsld setpos m_ndownspeedtxt m_ndownspeedtxt m_ndownspeedtxt m_downspeedinput enablewindow theprefs setmaxdownload m_ndownspeedtxt m_ndownspeedtxt updatedata void c mule systray dlg on change uptxt update data if the prefs get max graph upload rate true unlimited if m nupspeedtxt 16 m nupspeedtxt 16 else if m nupspeedtxt the prefs get max graph upload rate true m nupspeedtxt the prefs get max graph upload rate true m ctrlupspeedsld set pos m nupspeedtxt if m nupspeedtxt 1 m nupspeedtxt 0 m upspeedinput enable window false the prefs set max upload m nupspeedtxt 0 unlimited m nupspeedtxt update data false cmulesystraydlg onchangeuptxt updatedata theprefs getmaxgraphuploadrate m_nupspeedtxt m_nupspeedtxt m_nupspeedtxt theprefs getmaxgraphuploadrate m_nupspeedtxt theprefs getmaxgraphuploadrate m_ctrlupspeedsld setpos m_nupspeedtxt m_nupspeedtxt m_nupspeedtxt m_upspeedinput enablewindow theprefs setmaxupload m_nupspeedtxt m_nupspeedtxt updatedata void c mule systray dlg onh scroll uint nsb code uint n pos c scroll bar p scroll bar if p scroll bar c scroll bar m ctrldownspeedsld m ndownspeedtxt m ctrldownspeedsld get pos if m ndownspeedtxt 1 m ndownspeedtxt 0 m downspeedinput enable window false else m downspeedinput enable window true update data false the prefs set max download m ndownspeedtxt 0 unlimited m ndownspeedtxt else if p scroll bar c scroll bar m ctrlupspeedsld m nupspeedtxt m ctrlupspeedsld get pos if m nupspeedtxt 1 m nupspeedtxt 0 m upspeedinput enable window false else m upspeedinput enable window true update data false the prefs set max upload m nupspeedtxt 0 unlimited m nupspeedtxt c dialog onh scroll nsb code n pos p scroll bar cmulesystraydlg onhscroll nsbcode npos cscrollbar pscrollbar pscrollbar cscrollbar m_ctrldownspeedsld m_ndownspeedtxt m_ctrldownspeedsld getpos m_ndownspeedtxt m_ndownspeedtxt m_downspeedinput enablewindow m_downspeedinput enablewindow updatedata theprefs setmaxdownload m_ndownspeedtxt m_ndownspeedtxt pscrollbar cscrollbar m_ctrlupspeedsld m_nupspeedtxt m_ctrlupspeedsld getpos m_nupspeedtxt m_nupspeedtxt m_upspeedinput enablewindow m_upspeedinput enablewindow updatedata theprefs setmaxupload m_nupspeedtxt m_nupspeedtxt cdialog onhscroll nsbcode npos pscrollbar void c mule systray dlg onl button up uint n flags c point point release capture end dialog m nexitcode m bclosingdown true c dialog onl button up n flags point cmulesystraydlg onlbuttonup nflags cpoint releasecapture enddialog m_nexitcode m_bclosingdown cdialog onlbuttonup nflags void c mule systray dlg onr button down uint n flags c point point c rect systray rect get client rect systray rect if point x systray rect left point x systray rect right point y systray rect top point y systray rect bottom release capture end dialog m nexitcode m bclosingdown true c dialog onr button down n flags point cmulesystraydlg onrbuttondown nflags cpoint crect systrayrect getclientrect systrayrect systrayrect systrayrect systrayrect systrayrect releasecapture enddialog m_nexitcode m_bclosingdown cdialog onrbuttondown nflags void c mule systray dlg on kill focus c wnd p new wnd c dialog on kill focus p new wnd if m bclosingdown release capture end dialog m nexitcode m bclosingdown true cmulesystraydlg onkillfocus cwnd pnewwnd cdialog onkillfocus pnewwnd m_bclosingdown releasecapture enddialog m_nexitcode m_bclosingdown void c mule systray dlg on show window bool b show uint n status if b show m bclosingdown release capture end dialog m nexitcode m bclosingdown true c dialog on show window b show n status cmulesystraydlg onshowwindow bshow nstatus bshow m_bclosingdown releasecapture enddialog m_nexitcode m_bclosingdown cdialog onshowwindow bshow nstatus void c mule systray dlg on capture changed c wnd p wnd if p wnd p wnd this is child p wnd end dialog m nexitcode m bclosingdown true c dialog on capture changed p wnd cmulesystraydlg oncapturechanged cwnd pwnd pwnd pwnd ischild pwnd enddialog m_nexitcode m_bclosingdown cdialog oncapturechanged pwnd c kad contact list ctrl c kad contact list ctrl set general purpose find true set name t on contact list ctrl ckadcontactlistctrl ckadcontactlistctrl setgeneralpurposefind setname _t oncontactlistctrl c kad contact list ctrl c kad contact list ctrl ckadcontactlistctrl ckadcontactlistctrl bool c kad contact list ctrl contact add const kademlia c contact contact bool b result false try assert contact null int i item insert item lvif text lvif param get item count null 0 0 0 lparam contact if i item 0 b result true trying to update all the columns causes one of the connection freezes in win98 contact ref contact if it still doesn t work under win98 uncomment the afx data b win95 term if afx data b win95 i item 0 update contact i item contact update kad contact count catch assert 0 return b result ckadcontactlistctrl contactadd ccontact bresult iitem insertitem lvif_text lvif_param getitemcount iitem bresult contactref afxdata bwin95 afxdata bwin95 iitem updatecontact iitem updatekadcontactcount bresult void c kad contact list ctrl contact rem const kademlia c contact contact try assert contact null lvfindinfo find find flags lvfi param find l param lparam contact int i item find item find if i item 1 delete item i item update kad contact count catch assert 0 ckadcontactlistctrl contactrem ccontact lvfi_param lparam iitem finditem iitem deleteitem iitem updatekadcontactcount void c kad contact list ctrl contact ref const kademlia c contact contact try assert contact null lvfindinfo find find flags lvfi param find l param lparam contact int i item find item find if i item 1 update contact i item contact catch assert 0 ckadcontactlistctrl contactref ccontact lvfi_param lparam iitem finditem iitem updatecontact iitem void c kad contact list ctrl init set extended style lvs ex fullrowselect lvs ex infotip insert column colid get res string ids id lvcfmt left 100 insert column col type get res string ids type lvcfmt left 50 insert column col distance get res string ids kaddistance lvcfmt left 50 set all icons localize load settings int i sort item get sort item bool b sort ascending get sort ascending set sort arrow i sort item b sort ascending sort items sort proc makelong i sort item b sort ascending 0 0x0001 ckadcontactlistctrl setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip insertcolumn getresstring ids_id lvcfmt_left insertcolumn coltype getresstring ids_type lvcfmt_left insertcolumn coldistance getresstring ids_kaddistance lvcfmt_left setallicons loadsettings isortitem getsortitem bsortascending getsortascending setsortarrow isortitem bsortascending sortitems sortproc isortitem bsortascending void c kad contact list ctrl localize c header ctrl p header ctrl get header ctrl hditem hdi hdi mask hdi text c string str res for int icol 0 icol p header ctrl get item count icol switch icol case colid str res get res string ids id break case col type str res get res string ids type break case col distance str res get res string ids kaddistance break hdi psz text const cast lptstr lpctstr str res p header ctrl set item icol hdi int i items get item count for int i 0 i i items i update contact i kademlia c contact get item data i true ckadcontactlistctrl cheaderctrl pheaderctrl getheaderctrl hdi_text cstring strres pheaderctrl getitemcount strres getresstring ids_id coltype strres getresstring ids_type coldistance strres getresstring ids_kaddistance psztext const_cast strres pheaderctrl setitem iitems getitemcount iitems updatecontact ccontact getitemdata void c kad contact list ctrl save all settings save settings ckadcontactlistctrl saveallsettings savesettings void c kad contact list ctrl update kad contact count c string id id format t s i get res string ids kadcontactlab get item count the app emuledlg kademliawnd get dlg item idc kadcontactlab set window text id ckadcontactlistctrl updatekadcontactcount cstring _t getresstring ids_kadcontactlab getitemcount theapp getdlgitem idc_kadcontactlab setwindowtext void c kad contact list ctrl update contact int i item const kademlia c contact contact bool b localize c string id if b localize update the following fields only if really needed it s quite expensive to always update them contact get clientid id set item text i item colid id id format t i u contact get type contact get version set item text i item col type id contact get distance id set item text i item col distance id set item i item 0 lvif image 0 contact get type 4 4 contact get type 0 0 0 0 ckadcontactlistctrl updatecontact iitem ccontact blocalize cstring blocalize getclientid setitemtext iitem _t gettype getversion setitemtext iitem coltype getdistance setitemtext iitem coldistance setitem iitem lvif_image gettype gettype void c kad contact list ctrl set all icons c image list iml iml create 16 16 the app m idfltimagelistcolorflags ilc mask 0 1 iml set bk color clr none iml add c temp icon loader t contact0 iml add c temp icon loader t contact1 iml add c temp icon loader t contact2 iml add c temp icon loader t contact3 iml add c temp icon loader t contact4 assert get style lvs shareimagelists 0 himagelist himl apply image list iml detach if himl imagelist destroy himl ckadcontactlistctrl setallicons cimagelist theapp m_idfltimagelistcolorflags ilc_mask setbkcolor clr_none ctempiconloader _t ctempiconloader _t ctempiconloader _t ctempiconloader _t ctempiconloader _t getstyle lvs_shareimagelists applyimagelist imagelist_destroy int c kad contact list ctrl sort proc lparam l param1 lparam l param2 lparam l param sort kademlia c contact item1 kademlia c contact l param1 kademlia c contact item2 kademlia c contact l param2 if item1 null item2 null return 0 int i result switch loword l param sort case colid kademlia cu int128 i1 kademlia cu int128 i2 item1 get clientid i1 item2 get clientid i2 i result i1 compare to i2 break case col type i result item1 get type item2 get type break case col distance kademlia cu int128 distance1 distance2 item1 get distance distance1 item2 get distance distance2 i result distance1 compare to distance2 break default return 0 if hiword l param sort i result i result return i result ckadcontactlistctrl sortproc lparam1 lparam2 lparamsort ccontact ccontact lparam1 ccontact ccontact lparam2 iresult lparamsort cuint128 cuint128 getclientid getclientid iresult compareto coltype iresult gettype gettype coldistance cuint128 getdistance getdistance iresult compareto lparamsort iresult iresult iresult bool c kad contact list ctrl on command wparam w param lparam l param return true ckadcontactlistctrl oncommand wparam lparam void c kad contact list ctrl on sys color change c mule list ctrl on sys color change set all icons ckadcontactlistctrl onsyscolorchange cmulelistctrl onsyscolorchange setallicons void c kad contact list ctrl on column click nmhdr pnmhdr lresult p result nm listview pnm list view nm listview pnmhdr determine ascending based on whether already sorted on this column int i sort item get sort item bool b old sort ascending get sort ascending bool b sort ascending i sort item pnm list view i sub item true b old sort ascending item is column clicked i sort item pnm list view i sub item sort table update sort history makelong i sort item b sort ascending 0 0x0001 set sort arrow i sort item b sort ascending sort items sort proc makelong i sort item b sort ascending 0 0x0001 p result 0 ckadcontactlistctrl oncolumnclick presult nm_listview pnmlistview nm_listview isortitem getsortitem boldsortascending getsortascending bsortascending isortitem pnmlistview isubitem boldsortascending isortitem pnmlistview isubitem updatesorthistory isortitem bsortascending setsortarrow isortitem bsortascending sortitems sortproc isortitem bsortascending presult m strfindtext t m plistview null m isearchcolumn 0 m icnwnd null m bcansearchinallcolumns true m_strfindtext _t m_plistview m_isearchcolumn m_icnwnd m_bcansearchinallcolumns c list view search dlg c list view search dlg if m icnwnd verify destroy icon m icnwnd clistviewsearchdlg clistviewsearchdlg m_icnwnd destroyicon m_icnwnd void c list view search dlg update controls get dlg item idok enable window get dlg item idc listview search text get window text length 0 clistviewsearchdlg updatecontrols getdlgitem enablewindow getdlgitem idc_listview_search_text getwindowtextlength bool c list view search dlg on init dialog c dialog on init dialog set icon m icnwnd the app load icon t search false init window styles this set window text get res string ids sw searchbox set dlg item text idc listview search text lbl get res string ids search text t set dlg item text idc listview search column lbl get res string ids search column t set dlg item text idcancel get res string ids cancel if m bcansearchinallcolumns m isearchcolumn 0 if m plistview null tchar sz col title 256 lvcolumn lvc lvc mask lvcf text lvc cch text max sizeof sz col title sizeof sz col title 0 lvc psz text sz col title int i col 0 while m plistview get column i col lvc m ctlsearchcol add string lvc psz text if m bcansearchinallcolumns break if uint m isearchcolumn uint m ctlsearchcol get count m isearchcolumn 0 else m ctlsearchcol enable window false m ctlsearchcol show window sw hide m isearchcolumn 0 m ctlsearchcol set cur sel m isearchcolumn update controls return true clistviewsearchdlg oninitdialog cdialog oninitdialog seticon m_icnwnd theapp loadicon _t initwindowstyles setwindowtext getresstring ids_sw_searchbox setdlgitemtext idc_listview_search_text_lbl getresstring ids_search_text _t setdlgitemtext idc_listview_search_column_lbl getresstring ids_search_column _t setdlgitemtext getresstring ids_cancel m_bcansearchinallcolumns m_isearchcolumn m_plistview szcoltitle lvcf_text cchtextmax szcoltitle szcoltitle psztext szcoltitle icol m_plistview getcolumn icol m_ctlsearchcol addstring psztext m_bcansearchinallcolumns m_isearchcolumn m_ctlsearchcol getcount m_isearchcolumn m_ctlsearchcol enablewindow m_ctlsearchcol showwindow sw_hide m_isearchcolumn m_ctlsearchcol setcursel m_isearchcolumn updatecontrols void c list view search dlg do data exchange c data exchange pdx c dialog do data exchange pdx ddx control pdx idc listview search column m ctlsearchcol ddx cbindex pdx idc listview search column m isearchcolumn ddx text pdx idc listview search text m strfindtext clistviewsearchdlg dodataexchange cdataexchange cdialog dodataexchange ddx_control idc_listview_search_column m_ctlsearchcol ddx_cbindex idc_listview_search_column m_isearchcolumn ddx_text idc_listview_search_text m_strfindtext void c list view search dlg on en change search text update controls clistviewsearchdlg onenchangesearchtext updatecontrols void write string c string write c stringa stra write write string stra writestring cstring cstringa writestring void write string c string write c stringa stra write write string stra writestring cstring cstringa writestring uint8 read byte uint8 buf read buf 1 return buf readbyte uint16 read short uint16 buf read buf 2 return buf readshort uint32 read int uint32 buf read buf 4 return buf readint uint64 read int64 uint64 buf read buf 8 return buf readint64 c string read string uint8 buf char str 256 buf read byte read str buf return c string str buf cstring readstring readbyte cstring uint8 read byte uint8 buf read buf 1 return buf readbyte uint16 read short uint16 buf read buf 2 return buf readshort uint32 read int uint32 buf read buf 4 return buf readint uint64 read int64 uint64 buf read buf 8 return buf readint64 c string read string uint8 buf char str 256 buf read byte read str buf return c string str buf cstring readstring readbyte cstring cmm socket cmm socket cmm server p owner m powner p owner m pbuf null m dwrecv 0 m dwbufsize 0 m dwhttpheaderlen 0 m dwhttpcontentlen 0 m bclosed false m psendbuffer null m nsendlen 0 m nsent 0 m dwtimedshutdown 0 cmmsocket cmmsocket cmmserver powner m_powner powner m_pbuf m_dwrecv m_dwbufsize m_dwhttpheaderlen m_dwhttpcontentlen m_bclosed m_psendbuffer m_nsendlen m_nsent m_dwtimedshutdown cmm socket cmm socket void delete m pbuf while m packetqueue is empty delete m packetqueue remove head delete m psendbuffer cmmsocket cmmsocket m_pbuf m_packetqueue isempty m_packetqueue removehead m_psendbuffer bool cmm socket send packet cmm packet packet bool b queue first if m psendbuffer null m packetqueue add tail packet return false else char sz buf 0x1000 int n len if packet m bspecialheader n len wsprintfa sz buf http 1 1 200 ok r n connection close r n content type s r n content length ld r n r n m powner get content type packet m pbuffer get length else n len wsprintfa sz buf content length ld r n r n packet m pbuffer get length m nsendlen n len uint packet m pbuffer get length m psendbuffer new char m nsendlen memcpy m psendbuffer sz buf n len packet m pbuffer seek to begin packet m pbuffer read m psendbuffer n len uint packet m pbuffer get length m nsent send m psendbuffer m nsendlen if m nsent socket error delete m psendbuffer m psendbuffer null m nsendlen 0 if get last error wsaewouldblock if b queue first m packetqueue add head packet else m packetqueue add tail packet else delete packet close return false else if m nsent m nsendlen delete m psendbuffer m psendbuffer null m nsendlen 0 delete packet check for closing return true else delete packet return false cmmsocket sendpacket cmmpacket bqueuefirst m_psendbuffer m_packetqueue addtail szbuf nlen m_bspecialheader nlen szbuf nconnection ncontent ncontent m_powner getcontenttype m_pbuffer getlength nlen szbuf m_pbuffer getlength m_nsendlen nlen m_pbuffer getlength m_psendbuffer m_nsendlen m_psendbuffer szbuf nlen m_pbuffer seektobegin m_pbuffer m_psendbuffer nlen m_pbuffer getlength m_nsent m_psendbuffer m_nsendlen m_nsent socket_error m_psendbuffer m_psendbuffer m_nsendlen getlasterror bqueuefirst m_packetqueue addhead m_packetqueue addtail m_nsent m_nsendlen m_psendbuffer m_psendbuffer m_nsendlen checkforclosing void cmm socket on receive int n error code static char global read buffer 10240 if n error code 0 return const uint size preserve 0x1000 uint32 read max sizeof global read buffer uint32 dw size receive global read buffer read max if dw size socket error dw size 0 return if m dwbufsize dw size m dwrecv reallocate char p new buf new char m dwbufsize dw size m dwrecv size preserve if p new buf shutdown m hsocket sd both close return if m pbuf copy memory p new buf m pbuf m dwrecv delete m pbuf m pbuf p new buf copy memory m pbuf m dwrecv global read buffer dw size m dwrecv dw size check if we have all that we want if m dwhttpheaderlen try to find it bool b prev endl false for dword dw pos 0 dw pos m dwrecv dw pos if n m pbuf dw pos if b prev endl we just found the end of the http header now write the message s position into two first dwor ds of the buffer m dwhttpheaderlen dw pos 1 for dw pos 0 dw pos m dwhttpheaderlen char p ptr char memchr m pbuf dw pos n m dwhttpheaderlen dw pos if p ptr break dword dw next pos p ptr m pbuf check this header char sz match content length if strnicmp m pbuf dw pos sz match sizeof sz match 1 dw pos sizeof sz match 1 p ptr char memchr m pbuf dw pos m dwhttpheaderlen dw pos if p ptr m dwhttpcontentlen atol p ptr 1 break dw pos dw next pos 1 break else b prev endl true else if r m pbuf dw pos b prev endl false if m dwhttpheaderlen m dwhttpcontentlen m dwhttpcontentlen m dwrecv m dwhttpheaderlen if m dwhttpheaderlen m dwhttpcontentlen m dwrecv m dwhttpcontentlen m dwhttpheaderlen m dwhttpcontentlen m dwrecv on request received m pbuf m dwhttpheaderlen m pbuf m dwhttpheaderlen m dwhttpcontentlen if m dwrecv m dwhttpheaderlen m dwhttpcontentlen move our data m dwrecv m dwhttpheaderlen m dwhttpcontentlen move memory m pbuf m pbuf m dwhttpheaderlen m dwhttpcontentlen m dwrecv else m dwrecv 0 m dwhttpheaderlen 0 m dwhttpcontentlen 0 cmmsocket onreceive nerrorcode globalreadbuffer nerrorcode size_preserve readmax globalreadbuffer dwsize globalreadbuffer readmax dwsize socket_error dwsize m_dwbufsize dwsize m_dwrecv pnewbuf m_dwbufsize dwsize m_dwrecv size_preserve pnewbuf m_hsocket sd_both m_pbuf copymemory pnewbuf m_pbuf m_dwrecv m_pbuf m_pbuf pnewbuf copymemory m_pbuf m_dwrecv globalreadbuffer dwsize m_dwrecv dwsize m_dwhttpheaderlen bprevendl dwpos dwpos m_dwrecv dwpos m_pbuf dwpos bprevendl dwords m_dwhttpheaderlen dwpos dwpos dwpos m_dwhttpheaderlen pptr m_pbuf dwpos m_dwhttpheaderlen dwpos pptr dwnextpos pptr m_pbuf szmatch m_pbuf dwpos szmatch szmatch dwpos szmatch pptr m_pbuf dwpos m_dwhttpheaderlen dwpos pptr m_dwhttpcontentlen pptr dwpos dwnextpos bprevendl m_pbuf dwpos bprevendl m_dwhttpheaderlen m_dwhttpcontentlen m_dwhttpcontentlen m_dwrecv m_dwhttpheaderlen m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwhttpcontentlen m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv onrequestreceived m_pbuf m_dwhttpheaderlen m_pbuf m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen movememory m_pbuf m_pbuf m_dwhttpheaderlen m_dwhttpcontentlen m_dwrecv m_dwrecv m_dwhttpheaderlen m_dwhttpcontentlen void cmm socket on close int n error code m bclosed true if m powner m ppendingcommandsocket this m powner m ppendingcommandsocket null cmmsocket onclose nerrorcode m_bclosed m_powner m_ppendingcommandsocket m_powner m_ppendingcommandsocket void cmm socket close if m hsocket invalid socket m hsocket null this async select 0 c async socket close m bclosed true cmmsocket m_hsocket invalid_socket m_hsocket asyncselect casyncsocket m_bclosed void cmm socket on request received char p header dword dw header len char p data dword dw data len c string s header p header dw header len if s header left 4 post return if m powner pre process packet p data dw data len this return try if dw data len 3 try cmm data data p data 3 dw data len 3 switch p data 0 case mmp hello m powner process hello packet data this break case mmp filecommandreq m powner process file command data this break case mmp filedetailreq m powner process detail request data this break case mmp commandreq m powner process command request data this break case mmp searchreq m powner process search request data this break case mmp downloadreq m powner process download request data this break case mmp previewreq m powner process preview request data this break case mmp changelimit m powner process change limit request data this break case mmp statisticsreq m powner process statistics request data this break catch c file exception error assert false remove later if the prefs get verbose add debug log line false t corrupt mobile mule packet received error delete else switch p data 0 case mmp statusreq m powner process status request this break case mmp filelistreq m powner process file list request this break case mmp finishedreq m powner process finished list request this break catch assert false remove later if the prefs get verbose add debug log line false t unexpected error while processing mobile mule packet cmmsocket onrequestreceived pheader dwheaderlen pdata dwdatalen cstring sheader pheader dwheaderlen sheader m_powner preprocesspacket pdata dwdatalen dwdatalen cmmdata pdata dwdatalen pdata mmp_hello m_powner processhellopacket mmp_filecommandreq m_powner processfilecommand mmp_filedetailreq m_powner processdetailrequest mmp_commandreq m_powner processcommandrequest mmp_searchreq m_powner processsearchrequest mmp_downloadreq m_powner processdownloadrequest mmp_previewreq m_powner processpreviewrequest mmp_changelimit m_powner processchangelimitrequest mmp_statisticsreq m_powner processstatisticsrequest cfileexception theprefs getverbose adddebuglogline _t mobilemule pdata mmp_statusreq m_powner processstatusrequest mmp_filelistreq m_powner processfilelistrequest mmp_finishedreq m_powner processfinishedlistrequest theprefs getverbose adddebuglogline _t mobilemule void cmm socket on send int n error code if m psendbuffer null uint32 res send m psendbuffer m nsent m nsendlen m nsent if res socket error if get last error wsaewouldblock close return else m nsent res if m nsent m nsendlen delete m psendbuffer m psendbuffer null m nsendlen 0 check for closing else return while m packetqueue is empty cmm packet packet m packetqueue remove head if send packet packet true return cmmsocket onsend nerrorcode m_psendbuffer m_psendbuffer m_nsent m_nsendlen m_nsent socket_error getlasterror m_nsent m_nsent m_nsendlen m_psendbuffer m_psendbuffer m_nsendlen checkforclosing m_packetqueue isempty cmmpacket m_packetqueue removehead sendpacket void cmm socket check for closing if m nsendlen 0 m packetqueue is empty m bclosed m dwtimedshutdown get tick count 1000 cmmsocket checkforclosing m_nsendlen m_packetqueue isempty m_bclosed m_dwtimedshutdown gettickcount c listenmm socket c listenmm socket cmm server p owner m powner p owner clistenmmsocket clistenmmsocket cmmserver powner m_powner powner c listenmm socket c listenmm socket void while m socket list is empty delete m socket list remove head clistenmmsocket clistenmmsocket m_socket_list isempty m_socket_list removehead bool c listenmm socket create return c async socket create the prefs getmm port sock stream fd accept listen clistenmmsocket casyncsocket theprefs getmmport sock_stream fd_accept void c listenmm socket process delete closed sockets clistenmmsocket deleteclosedsockets void c listenmm socket on accept int n error code if n error code cmm socket newclient new cmm socket m powner if accept newclient delete newclient else newclient async select fd write fd read fd close m socket list add tail newclient linger linger 1 7 verify newclient set sock opt so linger linger sizeof linger sol socket delete closed sockets clistenmmsocket onaccept nerrorcode nerrorcode cmmsocket cmmsocket m_powner asyncselect fd_write fd_read fd_close m_socket_list addtail setsockopt so_linger sol_socket deleteclosedsockets void c listenmm socket delete closed sockets position pos2 pos1 for pos1 m socket list get head position pos2 pos1 null m socket list get next pos1 cmm socket cur sock m socket list get at pos2 if cur sock m bclosed m socket list remove at pos2 delete cur sock if cur sock m dwtimedshutdown cur sock m dwtimedshutdown get tick count cur sock shut down sd send cur sock m dwtimedshutdown 0 clistenmmsocket deleteclosedsockets m_socket_list getheadposition m_socket_list getnext cmmsocket cur_sock m_socket_list getat cur_sock m_bclosed m_socket_list removeat cur_sock cur_sock m_dwtimedshutdown cur_sock m_dwtimedshutdown gettickcount cur_sock shutdown sd_send cur_sock m_dwtimedshutdown cmm server cmm server void m sendsearchlist set size 0 h timer null m cpwfailed 0 m dwblocked 0 m psocket null m nsessionid 0 m ppendingcommandsocket null m nmaxdownloads 0 m nmaxbufdownloads 0 m bgrablistlogin false cmmserver cmmserver m_sendsearchlist setsize h_timer m_cpwfailed m_dwblocked m_psocket m_nsessionid m_ppendingcommandsocket m_nmaxdownloads m_nmaxbufdownloads m_bgrablistlogin cmm server cmm server void delete search files delete m psocket if h timer null kill timer 0 h timer cmmserver cmmserver deletesearchfiles m_psocket h_timer killtimer h_timer void cmm server init if the prefs ismm server enabled m psocket m psocket new c listenmm socket this if m psocket create stop server add log line false get res string ids mmfailed else add log line false get res string ids mmstarted the prefs getmm port t mm strversion cmmserver theprefs ismmserverenabled m_psocket m_psocket clistenmmsocket m_psocket stopserver addlogline getresstring ids_mmfailed addlogline getresstring ids_mmstarted theprefs getmmport _t mm_strversion void cmm server stop server delete m psocket m psocket null cmmserver stopserver m_psocket m_psocket bool cmm server pre process packet char p packet uint32 n size cmm socket sender if n size 3 uint16 n sessionid memcpy n sessionid p packet 1 sizeof n sessionid if m nsessionid n sessionid m nsessionid p packet 0 mmp hello return true else cmm packet packet new cmm packet mmp invalidid sender send packet packet m nsessionid 0 return false cmm packet packet new cmm packet mmp generalerror sender send packet packet return false cmmserver preprocesspacket ppacket nsize cmmsocket nsize nsessionid nsessionid ppacket nsessionid m_nsessionid nsessionid m_nsessionid ppacket mmp_hello cmmpacket cmmpacket mmp_invalidid sendpacket m_nsessionid cmmpacket cmmpacket mmp_generalerror sendpacket void cmm server process hello packet cmm data data cmm socket sender cmm packet packet new cmm packet mmp helloans if data read byte mm version packet write byte mmt wrongversion sender send packet packet return else if m dwblocked m dwblocked get tick count packet write byte mmt wrongpassword sender send packet packet return c string plainpw data read string c string test value md5 sum plainpw get hash if test value the prefs getmm pass plainpw get length 0 m dwblocked 0 packet write byte mmt wrongpassword sender send packet packet m cpwfailed if m cpwfailed 3 add log line false get res string ids mm block m cpwfailed 0 m dwblocked get tick count mms blocktime return else m busefakecontent data read byte 0 m nmaxdownloads data read short m nmaxbufdownloads data read short m bgrablistlogin data read byte 0 everything ok new sessionid add log line false get res string ids mm newuser packet write byte mmt ok m nsessionid uint16 rand packet write short m nsessionid packet write string the prefs get user nick packet write short uint16 the prefs get max upload unlimited 0 the prefs get max upload packet write short uint16 the prefs get max download unlimited 0 uint16 the prefs get max download process status request sender packet sender send packet packet cmmserver processhellopacket cmmdata cmmsocket cmmpacket cmmpacket mmp_helloans readbyte mm_version writebyte mmt_wrongversion sendpacket m_dwblocked m_dwblocked gettickcount writebyte mmt_wrongpassword sendpacket cstring readstring cstring testvalue md5sum gethash testvalue theprefs getmmpass getlength m_dwblocked writebyte mmt_wrongpassword sendpacket m_cpwfailed m_cpwfailed addlogline getresstring ids_mm_block m_cpwfailed m_dwblocked gettickcount mms_blocktime m_busefakecontent readbyte m_nmaxdownloads readshort m_nmaxbufdownloads readshort m_bgrablistlogin readbyte addlogline getresstring ids_mm_newuser writebyte mmt_ok m_nsessionid writeshort m_nsessionid writestring theprefs getusernick writeshort theprefs getmaxupload theprefs getmaxupload writeshort theprefs getmaxdownload theprefs getmaxdownload processstatusrequest sendpacket void cmm server process status request cmm socket sender cmm packet packet if packet null packet new cmm packet mmp statusanswer else packet write byte mmp statusanswer packet write short uint16 the app uploadqueue get datarate 100 packet write short uint16 the prefs get max graph upload rate true 1024 100 packet write short uint16 the app downloadqueue get datarate 100 packet write short uint16 the prefs get max graph download rate 1024 100 packet write byte uint8 the app downloadqueue get downloading file count packet write byte uint8 the app downloadqueue get paused file count packet write int uint32 the stats session received bytes 1048576 packet write short uint16 the stats get avg download rate 0 1024 100 if the app serverconnect is connected if the app serverconnect is lowid packet write byte 1 else packet write byte 2 if the app serverconnect get current server null packet write int the app serverconnect get current server get users packet write string the app serverconnect get current server get list name else packet write int 0 packet write string else packet write byte 0 packet write int 0 packet write string if the prefs get network kademlia if kademlia c kademlia is connected packet write byte 2 packet write int kademlia c kademlia get kademlia users else packet write byte 1 packet write int 0 else packet write byte 0 packet write int 0 sender send packet packet cmmserver processstatusrequest cmmsocket cmmpacket cmmpacket mmp_statusanswer writebyte mmp_statusanswer writeshort theapp getdatarate writeshort theprefs getmaxgraphuploadrate writeshort theapp getdatarate writeshort theprefs getmaxgraphdownloadrate writebyte theapp getdownloadingfilecount writebyte theapp getpausedfilecount writeint thestats sessionreceivedbytes writeshort thestats getavgdownloadrate theapp isconnected theapp islowid writebyte writebyte theapp getcurrentserver writeint theapp getcurrentserver getusers writestring theapp getcurrentserver getlistname writeint writestring writebyte writeint writestring theprefs getnetworkkademlia ckademlia isconnected writebyte writeint ckademlia getkademliausers writebyte writeint writebyte writeint sendpacket void cmm server process file list request cmm socket sender cmm packet packet if packet null packet new cmm packet mmp filelistans else packet write byte mmp filelistans int n count the prefs get cat count packet write byte uint8 n count for int i 0 i n count i packet write string the prefs get category i title n count the app downloadqueue get file count m nmaxdownloads m nmaxdownloads the app downloadqueue get file count m sentfilelist set size n count packet write byte uint8 n count for int i 0 i n count i while this is not the fastest method the trace this list it s not timecritical here c part file cur file the app downloadqueue get file by index i if cur file null delete packet packet new cmm packet mmp generalerror sender send packet packet assert false return m sentfilelist i cur file if cur file get status false ps paused packet write byte mmt paused else if cur file get transferring src count 0 packet write byte mmt downloading else packet write byte mmt waiting packet write string cur file get file name packet write byte uint8 cur file get category if i m nmaxbufdownloads packet write byte 1 write file info cur file packet else packet write byte 0 sender send packet packet cmmserver processfilelistrequest cmmsocket cmmpacket cmmpacket mmp_filelistans writebyte mmp_filelistans ncount theprefs getcatcount writebyte ncount ncount writestring theprefs getcategory ncount theapp getfilecount m_nmaxdownloads m_nmaxdownloads theapp getfilecount m_sentfilelist setsize ncount writebyte ncount ncount cpartfile cur_file theapp getfilebyindex cur_file cmmpacket mmp_generalerror sendpacket m_sentfilelist cur_file cur_file getstatus ps_paused writebyte mmt_paused cur_file gettransferringsrccount writebyte mmt_downloading writebyte mmt_waiting writestring cur_file getfilename writebyte cur_file getcategory m_nmaxbufdownloads writebyte writefileinfo cur_file writebyte sendpacket void cmm server process file command cmm data data cmm socket sender uint8 by command data read byte uint8 by file index data read byte if by file index m sentfilelist get size the app downloadqueue is part file m sentfilelist by file index cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return c part file sel file m sentfilelist by file index switch by command case mmt pause sel file pause file break case mmt resume sel file resume file break case mmt cancel switch sel file get status case ps waitingforhash case ps hashing case ps completing case ps complete break case ps paused sel file delete file break default the app downloadqueue start next file if prefs sel file get category sel file delete file break default cmm packet packet new cmm packet mmp generalerror sender send packet packet return cmm packet packet new cmm packet mmp filecommandans process file list request sender packet cmmserver processfilecommand cmmdata cmmsocket bycommand readbyte byfileindex readbyte byfileindex m_sentfilelist getsize theapp ispartfile m_sentfilelist byfileindex cmmpacket cmmpacket mmp_generalerror sendpacket cpartfile selfile m_sentfilelist byfileindex bycommand mmt_pause selfile pausefile mmt_resume selfile resumefile mmt_cancel selfile getstatus ps_waitingforhash ps_hashing ps_completing ps_complete ps_paused selfile deletefile theapp startnextfileifprefs selfile getcategory selfile deletefile cmmpacket cmmpacket mmp_generalerror sendpacket cmmpacket cmmpacket mmp_filecommandans processfilelistrequest void cmm server process detail request cmm data data cmm socket sender uint8 by file index data read byte if by file index m sentfilelist get size the app downloadqueue is part file m sentfilelist by file index cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return c part file sel file m sentfilelist by file index cmm packet packet new cmm packet mmp filedetailans write file info sel file packet sender send packet packet cmmserver processdetailrequest cmmdata cmmsocket byfileindex readbyte byfileindex m_sentfilelist getsize theapp ispartfile m_sentfilelist byfileindex cmmpacket cmmpacket mmp_generalerror sendpacket cpartfile selfile m_sentfilelist byfileindex cmmpacket cmmpacket mmp_filedetailans writefileinfo selfile sendpacket void cmm server process command request cmm data data cmm socket sender uint8 by command data read byte bool b success false bool b queue command false switch by command case mmt sdemule case mmt sdpc h timer set timer 0 0 5000 command timer if h timer b success true b queue command true break case mmt serverconnect the app serverconnect connect to any server b success true break if b success cmm packet packet new cmm packet mmp commandans sender send packet packet if b queue command m bypendingcommand by command else cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return cmmserver processcommandrequest cmmdata cmmsocket bycommand readbyte bsuccess bqueuecommand bycommand mmt_sdemule mmt_sdpc h_timer settimer commandtimer h_timer bsuccess bqueuecommand mmt_serverconnect theapp connecttoanyserver bsuccess bsuccess cmmpacket cmmpacket mmp_commandans sendpacket bqueuecommand m_bypendingcommand bycommand cmmpacket cmmpacket mmp_generalerror sendpacket void cmm server process search request cmm data data cmm socket sender delete search files s search params params params str expression data read string uint8 by type data read byte switch by type case 0 params str file type empty break case 1 params str file type ed2kftstr archive break case 2 params str file type ed2kftstr audio break case 3 params str file type ed2kftstr cdimage break case 4 params str file type ed2kftstr program break case 5 params str file type ed2kftstr video break case 6 params str file type ed2kftstr emulecollection break default assert false params str file type empty bool b server error false if the app serverconnect is connected cmm packet packet new cmm packet mmp searchans packet write byte mmt notconnected sender send packet packet return c safe mem file searchdata 100 bool b res search packet false try bool b server supports64 bit the app serverconnect get current server null the app serverconnect get current server gettcp flags srv tcpflg largefiles b res search packet get search packet searchdata params b server supports64 bit null catch c msg box exception ex ex delete if b res search packet searchdata get length 0 b server error true else h timer set timer 0 0 20000 command timer if h timer b server error true if b server error cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return m bypendingcommand mmt search m ppendingcommandsocket sender the app searchlist new search null params str file type mms searchid params e type true packet searchpacket new packet searchdata searchpacket opcode op searchrequest the stats add up data overhead server searchpacket size the app serverconnect send packet searchpacket true char buffer 500 wsprintfa buffer http 1 1 200 ok r n connection close r n content type s r n get content type sender send buffer strlen buffer cmmserver processsearchrequest cmmdata cmmsocket deletesearchfiles ssearchparams strexpression readstring bytype readbyte bytype strfiletype strfiletype ed2kftstr_archive strfiletype ed2kftstr_audio strfiletype ed2kftstr_cdimage strfiletype ed2kftstr_program strfiletype ed2kftstr_video strfiletype ed2kftstr_emulecollection strfiletype bservererror theapp isconnected cmmpacket cmmpacket mmp_searchans writebyte mmt_notconnected sendpacket csafememfile bressearchpacket bserversupports64bit theapp getcurrentserver theapp getcurrentserver gettcpflags srv_tcpflg_largefiles bressearchpacket getsearchpacket bserversupports64bit cmsgboxexception bressearchpacket getlength bservererror h_timer settimer commandtimer h_timer bservererror bservererror cmmpacket cmmpacket mmp_generalerror sendpacket m_bypendingcommand mmt_search m_ppendingcommandsocket theapp newsearch strfiletype mms_searchid etype op_searchrequest thestats addupdataoverheadserver theapp sendpacket nconnection ncontent getcontenttype void cmm server process preview request cmm data data cmm socket sender uint8 by file type data read byte uint8 by file index data read byte uint16 n display width data read short uint8 n number data read byte c known file knownfile null bool b error false if by file type mmt partfilfe if by file index m sentfilelist get size the app downloadqueue is part file m sentfilelist by file index b error true else knownfile m sentfilelist by file index else if by file type mmt finishedfile if by file index m sentfinishedlist get size the app knownfiles is known file m sentfinishedlist by file index b error true else knownfile m sentfinishedlist by file index if b error if h timer 0 b error true else h timer set timer 0 0 20000 command timer if h timer b error true else if n display width 140 n display width 140 m bypendingcommand mmt preview m ppendingcommandsocket sender if knownfile grab image 1 n number 1 50 0 true n display width this preview finished null 0 if b error cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return cmmserver processpreviewrequest cmmdata cmmsocket byfiletype readbyte byfileindex readbyte ndisplaywidth readshort nnumber readbyte cknownfile berror byfiletype mmt_partfilfe byfileindex m_sentfilelist getsize theapp ispartfile m_sentfilelist byfileindex berror m_sentfilelist byfileindex byfiletype mmt_finishedfile byfileindex m_sentfinishedlist getsize theapp isknownfile m_sentfinishedlist byfileindex berror m_sentfinishedlist byfileindex berror h_timer berror h_timer settimer commandtimer h_timer berror ndisplaywidth ndisplaywidth m_bypendingcommand mmt_preview m_ppendingcommandsocket grabimage nnumber ndisplaywidth previewfinished berror cmmpacket cmmpacket mmp_generalerror sendpacket void cmm server process download request cmm data data cmm socket sender uint8 by file index data read byte if by file index m sendsearchlist get size cmm packet packet new cmm packet mmp generalerror sender send packet packet assert false return c search file todownload m sendsearchlist by file index the app downloadqueue add search to download todownload 2 0 cmm packet packet new cmm packet mmp downloadans if the app downloadqueue get file byid todownload get file hash null packet write byte mmt ok else packet write byte mmt failed sender send packet packet cmmserver processdownloadrequest cmmdata cmmsocket byfileindex readbyte byfileindex m_sendsearchlist getsize cmmpacket cmmpacket mmp_generalerror sendpacket csearchfile m_sendsearchlist byfileindex theapp addsearchtodownload cmmpacket cmmpacket mmp_downloadans theapp getfilebyid getfilehash writebyte mmt_ok writebyte mmt_failed sendpacket void cmm server process change limit request cmm data data cmm socket sender uint16 n new upload data read short uint16 n new download data read short the prefs set max upload n new upload the prefs set max download n new download cmm packet packet new cmm packet mmp changelimitans packet write short uint16 the prefs get max upload unlimited 0 the prefs get max upload packet write short uint16 the prefs get max download unlimited 0 the prefs get max download sender send packet packet cmmserver processchangelimitrequest cmmdata cmmsocket nnewupload readshort nnewdownload readshort theprefs setmaxupload nnewupload theprefs setmaxdownload nnewdownload cmmpacket cmmpacket mmp_changelimitans writeshort theprefs getmaxupload theprefs getmaxupload writeshort theprefs getmaxdownload theprefs getmaxdownload sendpacket void cmm server process finished list request cmm socket sender cmm packet packet new cmm packet mmp finishedans int n count the prefs get cat count packet write byte uint8 n count for int i 0 i n count i packet write string the prefs get category i title n count m sentfinishedlist get count 30 30 m sentfinishedlist get count packet write byte uint8 n count for int i 0 i n count i c known file cur file m sentfinishedlist i packet write byte 0xff packet write string cur file get file name if cur file is part file packet write byte uint8 c part file cur file get category else packet write byte 0 sender send packet packet cmmserver processfinishedlistrequest cmmsocket cmmpacket cmmpacket mmp_finishedans ncount theprefs getcatcount writebyte ncount ncount writestring theprefs getcategory ncount m_sentfinishedlist getcount m_sentfinishedlist getcount writebyte ncount ncount cknownfile cur_file m_sentfinishedlist writebyte writestring cur_file getfilename cur_file ispartfile writebyte cpartfile cur_file getcategory writebyte sendpacket void cmm server process statistics request cmm data data cmm socket sender uint16 n width data read short c array up down raw data the app webserver get points for web int n raw data size raw data get size int n compress every n raw data size n width n raw data size n width 1 int n pos n raw data size n width n raw data size n width 0 int n add up n add down n add con i assert n pos n compress every n width n raw data size n pos 0 n raw data size n width cmm packet packet new cmm packet mmp statisticsans packet write short uint16 n raw data size n pos the prefs get traffico meter interval packet write short uint16 min n width n raw data size while n pos n raw data size n add up n add down n add con 0 for i 0 i n compress every i if n pos n raw data size assert false break else n add up int raw data element at n pos upload 1024 n add down int raw data element at n pos download 1024 n add con raw data element at n pos connections n pos packet write int uint32 round n add up i packet write int uint32 round n add down i packet write short uint16 round n add con i assert n pos n raw data size sender send packet packet cmmserver processstatisticsrequest cmmdata cmmsocket nwidth readshort carray updown rawdata theapp getpointsforweb nrawdatasize rawdata getsize ncompressevery nrawdatasize nwidth nrawdatasize nwidth npos nrawdatasize nwidth nrawdatasize nwidth naddup nadddown naddcon npos ncompressevery nwidth nrawdatasize npos nrawdatasize nwidth cmmpacket cmmpacket mmp_statisticsans writeshort nrawdatasize npos theprefs gettrafficometerinterval writeshort nwidth nrawdatasize npos nrawdatasize naddup nadddown naddcon ncompressevery npos nrawdatasize naddup rawdata elementat npos nadddown rawdata elementat npos naddcon rawdata elementat npos npos writeint naddup writeint nadddown writeshort naddcon npos nrawdatasize sendpacket void cmm server search finished bool b time out define maxresults 20 if h timer 0 kill timer 0 h timer h timer 0 if m ppendingcommandsocket null return if b time out cmm packet packet new cmm packet mmp searchans packet write byte mmt timedout packet m bspecialheader true m ppendingcommandsocket send packet packet else if the app searchlist get found files mms searchid 0 cmm packet packet new cmm packet mmp searchans packet write byte mmt noresults packet m bspecialheader true m ppendingcommandsocket send packet packet else uint results the app searchlist get found files mms searchid if results maxresults results maxresults m sendsearchlist set size results cmm packet packet new cmm packet mmp searchans packet m bspecialheader true packet write byte mmt ok packet write byte uint8 results for uint i 0 i results i c search file cur file the app searchlist detach next file mms searchid m sendsearchlist i cur file packet write string cur file get file name packet write short uint16 cur file get source count packet write int64 cur file get file size m ppendingcommandsocket send packet packet the app searchlist remove results mms searchid m ppendingcommandsocket null cmmserver searchfinished btimeout h_timer killtimer h_timer h_timer m_ppendingcommandsocket btimeout cmmpacket cmmpacket mmp_searchans writebyte mmt_timedout m_bspecialheader m_ppendingcommandsocket sendpacket theapp getfoundfiles mms_searchid cmmpacket cmmpacket mmp_searchans writebyte mmt_noresults m_bspecialheader m_ppendingcommandsocket sendpacket theapp getfoundfiles mms_searchid m_sendsearchlist setsize cmmpacket cmmpacket mmp_searchans m_bspecialheader writebyte mmt_ok writebyte csearchfile cur_file theapp detachnextfile mms_searchid m_sendsearchlist cur_file writestring cur_file getfilename writeshort cur_file getsourcecount writeint64 cur_file getfilesize m_ppendingcommandsocket sendpacket theapp removeresults mms_searchid m_ppendingcommandsocket void cmm server preview finished cx image img frames uint8 n count if h timer 0 kill timer 0 h timer h timer 0 if m bypendingcommand mmt preview return m bypendingcommand 0 if m ppendingcommandsocket null return cmm packet packet new cmm packet mmp previewans if img frames null n count 0 packet write byte mmt ok cx image cur frame img frames 0 if cur frame null assert false return byte aby result buffer null long n result size 0 if cur frame encode aby result buffer n result size cximage format png assert false return packet write int n result size packet m pbuffer write aby result buffer n result size free aby result buffer else packet write byte mmt failed m ppendingcommandsocket send packet packet m ppendingcommandsocket null cmmserver previewfinished cximage imgframes ncount h_timer killtimer h_timer h_timer m_bypendingcommand mmt_preview m_bypendingcommand m_ppendingcommandsocket cmmpacket cmmpacket mmp_previewans imgframes ncount writebyte mmt_ok cximage cur_frame imgframes cur_frame abyresultbuffer nresultsize cur_frame abyresultbuffer nresultsize cximage_format_png writeint nresultsize m_pbuffer abyresultbuffer nresultsize abyresultbuffer writebyte mmt_failed m_ppendingcommandsocket sendpacket m_ppendingcommandsocket void cmm server process if m psocket m psocket process cmmserver m_psocket m_psocket void cmm server delete search files for int i 0 i m sendsearchlist get size i delete m sendsearchlist i m sendsearchlist set size 0 cmmserver deletesearchfiles m_sendsearchlist getsize m_sendsearchlist m_sendsearchlist setsize void cmm server write file info c part file sel file cmm packet packet packet write int64 sel file get file size packet write int64 sel file get transferred packet write int64 sel file get completed size packet write short uint16 sel file get datarate 100 packet write short uint16 sel file get source count packet write short uint16 sel file get transferring src count if sel file is auto down priority packet write byte 4 else packet write byte sel file get down priority uint8 parts sel file mm create part status packet write short uint16 sel file get part count for uint i 0 i sel file get part count i packet write byte parts i delete parts cmmserver writefileinfo cpartfile selfile cmmpacket writeint64 selfile getfilesize writeint64 selfile gettransferred writeint64 selfile getcompletedsize writeshort selfile getdatarate writeshort selfile getsourcecount writeshort selfile gettransferringsrccount selfile isautodownpriority writebyte writebyte selfile getdownpriority selfile mmcreatepartstatus writeshort selfile getpartcount selfile getpartcount writebyte c string stream c string stream operator char psz str psz return this cstringstream cstringstream c string stream c string stream operator uint u val c string str val str val format t u u val str str val return this cstringstream cstringstream uval cstring strval strval _t uval strval c string stream c string stream operator int i val c string str val str val format t d i val str str val return this cstringstream cstringstream ival cstring strval strval _t ival strval c string stream c string stream operator double f val c string str val str val format t 3f f val str str val return this cstringstream cstringstream fval cstring strval strval _t fval strval void c mini dumper enable lpctstr psz app name bool b show errors if this assert fires then you have two instances of c mini dumper which is not allowed assert m szappname 0 t 0 tcsncpy m szappname psz app name arrsize m szappname minidumpwritedump pfn mini dump write dump null hmodule h dbg help dll get debug helper dll farproc pfn mini dump write dump b show errors if h dbg help dll if pfn mini dump write dump set unhandled exception filter top level filter free library h dbg help dll h dbg help dll null pfn mini dump write dump null cminidumper pszappname bshowerrors cminidumper m_szappname _t _tcsncpy m_szappname pszappname m_szappname pfnminidumpwritedump hdbghelpdll getdebughelperdll pfnminidumpwritedump bshowerrors hdbghelpdll pfnminidumpwritedump setunhandledexceptionfilter toplevelfilter freelibrary hdbghelpdll hdbghelpdll pfnminidumpwritedump hmodule c mini dumper get debug helper dll farproc ppfn mini dump write dump bool b show errors ppfn mini dump write dump null hmodule h dll load library t dbghelp dll if h dll null if b show errors do not localize that string in fact do not use mfc to load it message box null t dbghelp dll not found please install a dbghelp dll m szappname mb iconstop mb ok else ppfn mini dump write dump get proc address h dll mini dump write dump if ppfn mini dump write dump null if b show errors do not localize that string in fact do not use mfc to load it message box null t dbghelp dll found is too old please upgrade to a newer version of dbghelp dll m szappname mb iconstop mb ok return h dll cminidumper getdebughelperdll ppfnminidumpwritedump bshowerrors ppfnminidumpwritedump hdll loadlibrary _t hdll bshowerrors messagebox _t m_szappname mb_iconstop mb_ok ppfnminidumpwritedump getprocaddress hdll minidumpwritedump ppfnminidumpwritedump bshowerrors messagebox _t m_szappname mb_iconstop mb_ok hdll long c mini dumper top level filter struct exception pointers p exception info long l ret value exception continue search tchar sz result max path 1024 0 minidumpwritedump pfn mini dump write dump null hmodule h dll get debug helper dll farproc pfn mini dump write dump true if h dll if pfn mini dump write dump ask user if they want to save a dump file do not localize that string in fact do not use mfc to load it if message box null t e mule crashed r n r na diagnostic file can be created which will help the author to resolve this problem this file will be saved on your disk and not sent r n r n do you want to create this file now m szappname mb iconstop mb yesno idyes create full path for dump file tchar sz dump path max path 0 get module file name null sz dump path arrsize sz dump path lptstr psz file name tcsrchr sz dump path t if psz file name psz file name psz file name t 0 replace spaces and dots in file name tchar sz base name max path 0 tcsncat sz base name m szappname arrsize sz base name 1 lptstr psz sz base name while psz t 0 if psz t psz t else if psz t psz t psz tcsncat sz dump path sz base name arrsize sz dump path 1 tcsncat sz dump path t dmp arrsize sz dump path 1 handle h file create file sz dump path generic write file share write null create always file attribute normal null if h file invalid handle value minidump exception information ex info 0 ex info thread id get current thread id ex info exception pointers p exception info ex info client pointers null bool bok pfn mini dump write dump get current process get current process id h file mini dump normal ex info null null if bok do not localize that string in fact do not use mfc to load it sntprintf sz result arrsize sz result t saved dump file to s r n r n please send this file together with a detailed bug report to dumps emule project net r n r n thank you for helping to improve e mule sz dump path l ret value exception execute handler else do not localize that string in fact do not use mfc to load it sntprintf sz result arrsize sz result t failed to save dump file to s r n r n error u sz dump path get last error close handle h file else do not localize that string in fact do not use mfc to load it sntprintf sz result arrsize sz result t failed to create dump file s r n r n error u sz dump path get last error free library h dll h dll null pfn mini dump write dump null if sz result 0 t 0 message box null sz result m szappname mb iconinformation mb ok ifndef debug exit the process only in release builds so that in debug builds the exceptio is passed to a possible installed debugger exit process 0 else return l ret value endif cminidumper toplevelfilter _exception_pointers pexceptioninfo lretvalue exception_continue_search szresult _max_path pfnminidumpwritedump hdll getdebughelperdll pfnminidumpwritedump hdll pfnminidumpwritedump messagebox _t emule ndo m_szappname mb_iconstop mb_yesno szdumppath _max_path getmodulefilename szdumppath szdumppath pszfilename _tcsrchr szdumppath _t pszfilename pszfilename pszfilename _t szbasename _max_path _tcsncat szbasename m_szappname szbasename szbasename _t _t _t _t _t _ _tcsncat szdumppath szbasename szdumppath _tcsncat szdumppath _t szdumppath hfile createfile szdumppath generic_write file_share_write create_always file_attribute_normal hfile invalid_handle_value _minidump_exception_information exinfo exinfo threadid getcurrentthreadid exinfo exceptionpointers pexceptioninfo exinfo clientpointers pfnminidumpwritedump getcurrentprocess getcurrentprocessid hfile minidumpnormal exinfo _sntprintf szresult szresult _t nplease nthank emule szdumppath lretvalue exception_execute_handler _sntprintf szresult szresult _t nerror szdumppath getlasterror closehandle hfile _sntprintf szresult szresult _t nerror szdumppath getlasterror freelibrary hdll hdll pfnminidumpwritedump szresult _t messagebox szresult m_szappname mb_iconinformation mb_ok _debug exitprocess lretvalue c log edit ctrl c log edit ctrl m brichedit false m bautoscroll true m bnopaint false m benerrspace false m imaxlogbuff 0 m crforeground clr default m crbackground clr default clogeditctrl clogeditctrl m_brichedit m_bautoscroll m_bnopaint m_benerrspace m_imaxlogbuff m_crforeground clr_default m_crbackground clr_default c log edit ctrl c log edit ctrl clogeditctrl clogeditctrl void c log edit ctrl init lpctstr psz title lpctstr psz skin key char sz class name max path get class namea this sz class name arrsize sz class name m brichedit ascii stricmp sz class name edit 0 m strskinkey psz skin key set title psz title m logmenu create popup menu m logmenu add menu title get res string ids logentry m logmenu append menu mf string mp copyselected get res string ids copy m logmenu append menu mf separator m logmenu append menu mf string mp selectall get res string ids selectall m logmenu append menu mf string mp removeall get res string ids pw reset m logmenu append menu mf string mp savelog get res string ids savelog t m logmenu append menu mf separator m logmenu append menu mf string mp autoscroll get res string ids autoscroll verify send message em setundolimit 0 0 0 int i max log buff the prefs get max log buff if afx data b win95 limit text m imaxlogbuff i max log buff 0xffff 0xffff i max log buff else limit text m imaxlogbuff i max log buff i max log buff 128 1024 flush buffer clogeditctrl psztitle pszskinkey szclassname max_path getclassnamea szclassname szclassname m_brichedit __ascii_stricmp szclassname m_strskinkey pszskinkey settitle psztitle m_logmenu createpopupmenu m_logmenu addmenutitle getresstring ids_logentry m_logmenu appendmenu mf_string mp_copyselected getresstring ids_copy m_logmenu appendmenu mf_separator m_logmenu appendmenu mf_string mp_selectall getresstring ids_selectall m_logmenu appendmenu mf_string mp_removeall getresstring ids_pw_reset m_logmenu appendmenu mf_string mp_savelog getresstring ids_savelog _t m_logmenu appendmenu mf_separator m_logmenu appendmenu mf_string mp_autoscroll getresstring ids_autoscroll sendmessage em_setundolimit imaxlogbuff theprefs getmaxlogbuff afxdata bwin95 limittext m_imaxlogbuff imaxlogbuff imaxlogbuff limittext m_imaxlogbuff imaxlogbuff imaxlogbuff flushbuffer void c log edit ctrl set title lpctstr psz title m strtitle psz title clogeditctrl settitle psztitle m_strtitle psztitle void c log edit ctrl localize clogeditctrl void c log edit ctrl apply skin if m strskinkey is empty colorref cr if the app load skin color m strskinkey t fg cr m crforeground cr else m crforeground clr default if the app load skin color m strskinkey t bk cr m crbackground cr m brbackground delete object m brbackground create solid brush m crbackground else m crbackground clr default m brbackground delete object clogeditctrl applyskin m_strskinkey isempty theapp loadskincolor m_strskinkey _t m_crforeground m_crforeground clr_default theapp loadskincolor m_strskinkey _t m_crbackground m_brbackground deleteobject m_brbackground createsolidbrush m_crbackground m_crbackground clr_default m_brbackground deleteobject void c log edit ctrl add entry lpctstr psz msg c string str line psz msg str line t r n if m hwnd null m astrbuff add str line else flush buffer add line str line str line get length clogeditctrl addentry pszmsg cstring strline pszmsg strline _t m_hwnd m_astrbuff strline flushbuffer addline strline strline getlength void c log edit ctrl add lpctstr psz msg int i len if m hwnd null c string str line psz msg m astrbuff add str line else flush buffer add line psz msg i len clogeditctrl pszmsg ilen m_hwnd cstring strline pszmsg m_astrbuff strline flushbuffer addline pszmsg ilen void c log edit ctrl reset m astrbuff remove all set redraw false set window text t set redraw if m brichedit invalidate clogeditctrl m_astrbuff removeall setredraw setwindowtext _t setredraw m_brichedit c string c log edit ctrl get last log entry c string str log int i last line get line count 2 if i last line 0 get line i last line str log get buffer 1024 1024 str log release buffer return str log cstring clogeditctrl getlastlogentry cstring strlog ilastline getlinecount ilastline getline ilastline strlog getbuffer strlog releasebuffer strlog c string c log edit ctrl get all log entries c string str log get window text str log return str log cstring clogeditctrl getalllogentries cstring strlog getwindowtext strlog strlog bool c log edit ctrl save log lpctstr psz def name bool b result false c file dialog dlg false t log psz def name psz def name lpctstr m strtitle ofn hidereadonly ofn overwriteprompt t log files log log this 0 if dlg do modal idok file fp tfsopen dlg get path name t wb sh denywr if fp ifdef unicode write unicode byte order mark 0xfeff fputwc 0xfeff fp endif c string str text get window text str text fwrite str text sizeof tchar str text get length fp if ferror fp c string str error str error format t failed to write log file s s dlg get path name strerror errno afx message box str error mb iconerror else b result true fclose fp else c string str error str error format t failed to create log file s s dlg get path name strerror errno afx message box str error mb iconerror return b result clogeditctrl savelog pszdefname bresult cfiledialog _t pszdefname pszdefname m_strtitle ofn_hidereadonly ofn_overwriteprompt _t domodal _tfsopen getpathname _t _sh_denywr _unicode cstring strtext getwindowtext strtext strtext strtext getlength cstring strerror strerror _t getpathname afxmessagebox strerror mb_iconerror bresult cstring strerror strerror _t getpathname afxmessagebox strerror mb_iconerror bresult void c log edit ctrl add line lpctstr psz msg int i len int i msg len i len 1 tcslen psz msg i len if i msg len 0 return ifdef debug if psz msg i msg len 1 t n assert i msg len 2 psz msg i msg len 2 t r endif get edit contents dimensions and cursor position int i start char i end char get sel i start char i end char int i wnd txt len get window text length if i start char i wnd txt len i wnd txt len i end char the cursor resides at the end of text scrollinfo si si cb size sizeof si si f mask sif all if m bautoscroll get scroll info sb vert si si n pos int si n max si n page 1 not scrolled away safe add line i wnd txt len i msg len psz msg i start char i end char if m bautoscroll is window visible scroll to last line else reduce flicker by ignoring wm paint m bnopaint true bool b is visible is window visible if b is visible set redraw false remember where we are int n first line m bautoscroll get first visible line 0 select at the end of text and replace the selection this is a very fast way to add text to an edit control safe add line i wnd txt len i msg len psz msg i start char i end char set sel i start char i end char true restore our previous selection if m bautoscroll line scroll n first line get first visible line else scroll to last line m bnopaint false if b is visible set redraw if m brichedit invalidate else we should add the text anyway reduce flicker by ignoring wm paint m bnopaint true bool b is visible is window visible if b is visible set redraw false remember where we are int n first line m bautoscroll get first visible line 0 if i start char i end char if we are currently selecting some text we have to find out if the caret is near the beginning of this block or near the end note that this does not always work because of the em charfrompos message returning only 16 bits this will fail if the user has selected a block with a length dividable by 64k note this may cause a lot of terrible crashes within the rich edit control when used for a rich edit control to reproduce the crash click in the re control while it s drawing a line an start a selection if m brichedit c point pt get caret pos pt int n caret pos char from pos pt if abs i start char 0xffff n caret pos abs i end char 0xffff n caret pos n caret pos i start char i start char i end char i end char n caret pos note this will flicker if someone has a good idea how to prevent this let me know select at the end of text and replace the selection this is a very fast way to add text to an edit control safe add line i wnd txt len i msg len psz msg i start char i end char set sel i start char i end char true restore our previous selection if m bautoscroll line scroll n first line get first visible line else scroll to last line m bnopaint false if b is visible set redraw if m brichedit invalidate clogeditctrl addline pszmsg ilen imsglen ilen _tcslen pszmsg ilen imsglen _debug pszmsg imsglen _t imsglen pszmsg imsglen _t istartchar iendchar getsel istartchar iendchar iwndtxtlen getwindowtextlength istartchar iwndtxtlen iwndtxtlen iendchar cbsize fmask sif_all m_bautoscroll getscrollinfo sb_vert npos nmax npage safeaddline iwndtxtlen imsglen pszmsg istartchar iendchar m_bautoscroll iswindowvisible scrolltolastline wm_paint m_bnopaint bisvisible iswindowvisible bisvisible setredraw nfirstline m_bautoscroll getfirstvisibleline safeaddline iwndtxtlen imsglen pszmsg istartchar iendchar setsel istartchar iendchar m_bautoscroll linescroll nfirstline getfirstvisibleline scrolltolastline m_bnopaint bisvisible setredraw m_brichedit wm_paint m_bnopaint bisvisible iswindowvisible bisvisible setredraw nfirstline m_bautoscroll getfirstvisibleline istartchar iendchar em_charfrompos richedit richedit m_brichedit cpoint getcaretpos ncaretpos charfrompos istartchar ncaretpos iendchar ncaretpos ncaretpos istartchar istartchar iendchar iendchar ncaretpos safeaddline iwndtxtlen imsglen pszmsg istartchar iendchar setsel istartchar iendchar m_bautoscroll linescroll nfirstline getfirstvisibleline scrolltolastline m_bnopaint bisvisible setredraw m_brichedit void c log edit ctrl select all items set sel 0 1 true clogeditctrl selectallitems setsel void c log edit ctrl copy selected items copy clogeditctrl copyselecteditems void c log edit ctrl safe add line int n pos int i line len lpctstr psz line int i start char int i end char bool b old no paint false bool b is visible false bool b restore paint flag false try to determine if the current log line will exceed the limit of the edit control and free up enough space to add it if it would be done afterwards because of en errspace it may cost noticeable more cpu cycles int i text len n pos n pos already holds the current window text length if i text len i line len m imaxlogbuff delete the 1st 10 lines freeing up only 1 or 2 lines is still not enough peformance problem int i line0 len 0 for int i 0 i 10 i int i line len line length i line0 len if i line len 0 break i line0 len i line len 2 b old no paint m bnopaint m bnopaint true b restore paint flag true b is visible is window visible if b is visible set redraw false set sel 0 i line0 len true replace sel t update any possible available selection i start char i line0 len if i start char 0 i start char 0 i end char i line0 len if i end char 0 i end char 0 n pos i line0 len if n pos 0 n pos 0 m benerrspace false set sel n pos n pos true replace sel psz line if b restore paint flag m bnopaint b old no paint if b is visible m bnopaint set redraw if m brichedit invalidate if m benerrspace following code works properly but there is a performance problem if the control starts to rotate the text and if there is much to log cpu usage hits the roof to get around this we try to free the needed space for the current line and more before adding the line see code above actually the following code should not be executed any longer but is kept for fail safe handling bool b old no paint m bnopaint m bnopaint true bool b is visible is window visible if b is visible set redraw false remove the first line as long as we are capable of adding the new line int i safety counter 0 while m benerrspace i safety counter 10 delete the previous partially added line set sel n pos 1 true replace sel t delete 1st line int i line0 len line length 0 2 add nl character set sel 0 i line0 len true replace sel t update any possible available selection i start char i line0 len if i start char 0 i start char 0 i end char i line0 len if i end char 0 i end char 0 add the new line again n pos get window text length set sel n pos n pos true m benerrspace false replace sel psz line if m benerrspace n pos 0 should never happen if we tried to add the line another time in the 1st line there will be no chance to add the line at all avoid endless loop break i safety counter never ever create an endless loop m bnopaint b old no paint if b is visible m bnopaint set redraw if m brichedit invalidate clogeditctrl safeaddline npos ilinelen pszline istartchar iendchar boldnopaint bisvisible brestorepaintflag en_errspace itextlen npos npos itextlen ilinelen m_imaxlogbuff iline0len ilinelen linelength iline0len ilinelen iline0len ilinelen boldnopaint m_bnopaint m_bnopaint brestorepaintflag bisvisible iswindowvisible bisvisible setredraw setsel iline0len replacesel _t istartchar iline0len istartchar istartchar iendchar iline0len iendchar iendchar npos iline0len npos npos m_benerrspace setsel npos npos replacesel pszline brestorepaintflag m_bnopaint boldnopaint bisvisible m_bnopaint setredraw m_brichedit m_benerrspace boldnopaint m_bnopaint m_bnopaint bisvisible iswindowvisible bisvisible setredraw isafetycounter m_benerrspace isafetycounter setsel npos replacesel _t iline0len linelength setsel iline0len replacesel _t istartchar iline0len istartchar istartchar iendchar iline0len iendchar iendchar npos getwindowtextlength setsel npos npos m_benerrspace replacesel pszline m_benerrspace npos isafetycounter m_bnopaint boldnopaint bisvisible m_bnopaint setredraw m_brichedit void c log edit ctrl flush buffer if m astrbuff get size 0 flush buffer for int i 0 i m astrbuff get size i add line m astrbuff i m astrbuff i get length m astrbuff remove all clogeditctrl flushbuffer m_astrbuff getsize m_astrbuff getsize addline m_astrbuff m_astrbuff getlength m_astrbuff removeall void c log edit ctrl scroll to last line wm vscroll does not work correctly under win98 or older version of comctl dll send message wm vscroll sb bottom 0 line scroll get line count clogeditctrl scrolltolastline wm_vscroll sendmessage wm_vscroll sb_bottom linescroll getlinecount lresult c log edit ctrl window proc uint message wparam w param lparam l param switch message case wm erasebkgnd if m bnopaint return true case wm paint if m bnopaint return true return c edit window proc message w param l param clogeditctrl windowproc wparam lparam wm_erasebkgnd m_bnopaint wm_paint m_bnopaint cedit windowproc wparam lparam void c log edit ctrl on context menu c wnd p wnd c point point int i sel start i sel end get sel i sel start i sel end int i text len get window text length m logmenu enable menu item mp copyselected i sel end i sel start mf enabled mf grayed m logmenu enable menu item mp removeall i text len 0 mf enabled mf grayed m logmenu enable menu item mp selectall i text len 0 mf enabled mf grayed m logmenu enable menu item mp savelog i text len 0 mf enabled mf grayed m logmenu check menu item mp autoscroll m bautoscroll mf checked mf unchecked if point x 1 point y 1 point x 16 point y 32 client to screen point m logmenu track popup menu tpm leftalign tpm rightbutton point x point y this clogeditctrl oncontextmenu cwnd pwnd cpoint iselstart iselend getsel iselstart iselend itextlen getwindowtextlength m_logmenu enablemenuitem mp_copyselected iselend iselstart mf_enabled mf_grayed m_logmenu enablemenuitem mp_removeall itextlen mf_enabled mf_grayed m_logmenu enablemenuitem mp_selectall itextlen mf_enabled mf_grayed m_logmenu enablemenuitem mp_savelog itextlen mf_enabled mf_grayed m_logmenu checkmenuitem mp_autoscroll m_bautoscroll mf_checked mf_unchecked clienttoscreen m_logmenu trackpopupmenu tpm_leftalign tpm_rightbutton bool c log edit ctrl on command wparam w param lparam l param switch w param case mp copyselected copy selected items break case mp selectall select all items break case mp removeall reset break case mp savelog save log break case mp autoscroll m bautoscroll m bautoscroll break return true clogeditctrl oncommand wparam lparam wparam mp_copyselected copyselecteditems mp_selectall selectallitems mp_removeall mp_savelog savelog mp_autoscroll m_bautoscroll m_bautoscroll void c log edit ctrl on key down uint n char uint n rep cnt uint n flags if n char a get key state vk control 0x8000 ctrl a select all items select all items else if n char c get key state vk control 0x8000 ctrl c copy listview items to clipboard copy selected items c edit on key down n char n rep cnt n flags clogeditctrl onkeydown nchar nrepcnt nflags nchar getkeystate vk_control selectallitems nchar getkeystate vk_control copyselecteditems cedit onkeydown nchar nrepcnt nflags void c log edit ctrl on en errspace m benerrspace true clogeditctrl onenerrspace m_benerrspace void c log edit ctrl on en maxtext m benerrspace true clogeditctrl onenmaxtext m_benerrspace void c log edit ctrl on sys color change c edit on sys color change apply skin clogeditctrl onsyscolorchange cedit onsyscolorchange applyskin hbrush c log edit ctrl ctl color cdc pdc uint n ctl color if m crforeground clr default pdc set text color m crforeground else explicitly set the default text color needed for some contrast window color schemes pdc set text color get sys color color windowtext if m crbackground clr default m brbackground m hobject null pdc set bk color m crbackground return m brbackground else pdc set bk color get sys color color window return get sys color brush color window clogeditctrl ctlcolor nctlcolor m_crforeground clr_default settextcolor m_crforeground settextcolor getsyscolor color_windowtext m_crbackground clr_default m_brbackground m_hobject setbkcolor m_crbackground m_brbackground setbkcolor getsyscolor color_window getsyscolorbrush color_window c list boxst c list boxst no image list associated m pimagelist null zero memory m szimage sizeof m szimage by default hilight full list box item set row select st fullrowselect false clistboxst clistboxst m_pimagelist zeromemory m_szimage m_szimage setrowselect st_fullrowselect c list boxst c list boxst clistboxst clistboxst int c list boxst add string lpctstr lpsz item int n image int n index lb err n index c list box add string lpsz item if n index lb err n index lb errspace replace item data n index 0 null n image 0 mask all if return n index clistboxst addstring lpszitem nimage nindex lb_err nindex clistbox addstring lpszitem nindex lb_err nindex lb_errspace replaceitemdata nindex nimage mask_all nindex int c list boxst insert string int n index lpctstr lpsz string int n image int n new index lb err n new index c list box insert string n index lpsz string if n new index lb err n new index lb errspace replace item data n new index 0 null n image 0 mask all if return n new index clistboxst insertstring nindex lpszstring nimage nnewindex lb_err nnewindex clistbox insertstring nindex lpszstring nnewindex lb_err nnewindex lb_errspace replaceitemdata nnewindex nimage mask_all nnewindex int c list boxst delete string int n index int n ret value lb err delete item data n index n ret value c list box delete string n index return n ret value clistboxst deletestring nindex nretvalue lb_err deleteitemdata nindex nretvalue clistbox deletestring nindex nretvalue int c list boxst replace string int n index lpctstr lpsz string int n image int n ret value n ret value delete string n index if n ret value lb err n ret value insert string n index lpsz string n image if return n ret value clistboxst replacestring nindex lpszstring nimage nretvalue nretvalue deletestring nindex nretvalue lb_err nretvalue insertstring nindex lpszstring nimage nretvalue void c list boxst reset content free resources c list box reset content clistboxst resetcontent freeresources clistbox resetcontent int c list boxst set item data int n index dword dw item data return replace item data n index dw item data null 0 0 mask dwdata clistboxst setitemdata nindex dwitemdata replaceitemdata nindex dwitemdata mask_dwdata dword c list boxst get item data int n index struct lbdata lplb data null lplb data struct lbdata c list box get item data ptr n index if lplb data lpvoid 1l return lplb data dw item data return dword lb err clistboxst getitemdata nindex struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata dwitemdata lb_err int c list boxst set item data ptr int n index void p data return replace item data n index 0 p data 0 0 mask lpdata clistboxst setitemdataptr nindex pdata replaceitemdata nindex pdata mask_lpdata void c list boxst get item data ptr int n index struct lbdata lplb data null lplb data struct lbdata c list box get item data ptr n index if lplb data lpvoid 1l return lplb data p data return lpvoid 1l clistboxst getitemdataptr nindex struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata pdata void c list boxst enable item int n index bool b enable bool b repaint struct lbdata lplb data null get pointer to associated datas if any lplb data struct lbdata c list box get item data ptr n index if lplb data null lplb data lpvoid 1l if b enable replace item data n index 0 null 0 lplb data dw flags test bit0 mask dwflags else replace item data n index 0 null 0 lplb data dw flags test bit0 mask dwflags if b repaint invalidate if clistboxst enableitem nindex benable brepaint struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata benable replaceitemdata nindex lplbdata dwflags test_bit0 mask_dwflags replaceitemdata nindex lplbdata dwflags test_bit0 mask_dwflags brepaint bool c list boxst is item enabled int n index struct lbdata lplb data null get pointer to associated datas if any lplb data struct lbdata c list box get item data ptr n index if lplb data null lplb data lpvoid 1l return lplb data dw flags test bit0 test bit0 if lplb data b disabled return false if return true clistboxst isitemenabled nindex struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata lplbdata dwflags test_bit0 test_bit0 lplbdata bdisabled void c list boxst set row select byte by row select bool b repaint switch by row select case st fullrowselect case st fulltextselect case st textselect store new selection type m byrowselect by row select if b repaint invalidate break default bad value assert false break switch clistboxst setrowselect byrowselect brepaint byrowselect st_fullrowselect st_fulltextselect st_textselect m_byrowselect byrowselect brepaint void c list boxst set image list c image list p image list m pimagelist p image list get icons size if m pimagelist imagelist geticonsize m pimagelist lpint m szimage cx lpint m szimage cy else zero memory m szimage sizeof m szimage invalidate clistboxst setimagelist cimagelist pimagelist m_pimagelist pimagelist m_pimagelist imagelist_geticonsize m_pimagelist m_szimage m_szimage zeromemory m_szimage m_szimage void c list boxst set image int n index int n image bool b repaint replace item data n index 0 null n image 0 mask nimage if b repaint invalidate clistboxst setimage nindex nimage brepaint replaceitemdata nindex nimage mask_nimage brepaint void c list boxst get image int n index lpint lpn image struct lbdata lplb data null assert lpn image null if lpn image get pointer to associated datas if any lplb data struct lbdata c list box get item data ptr n index if lplb data null lplb data lpvoid 1l lpn image lplb data n image else lpn image 1l if clistboxst getimage nindex lpnimage struct_lbdata lplbdata lpnimage lpnimage lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata lpnimage lplbdata nimage lpnimage int c list boxst move up int n index bool b set cur sel int n ret value n index if n index 0 n ret value move n index n index 1 b set cur sel if return n ret value clistboxst moveup nindex bsetcursel nretvalue nindex nindex nretvalue nindex nindex bsetcursel nretvalue int c list boxst move down int n index bool b set cur sel int n ret value n index if n index get count 1 n ret value move n index n index 1 b set cur sel if return n ret value clistboxst movedown nindex bsetcursel nretvalue nindex nindex getcount nretvalue nindex nindex bsetcursel nretvalue int c list boxst move top int n index bool b set cur sel int n ret value n index if n index 0 n ret value move n index 0 b set cur sel if return n ret value clistboxst movetop nindex bsetcursel nretvalue nindex nindex nretvalue nindex bsetcursel nretvalue int c list boxst move bottom int n index bool b set cur sel int n ret value n index if n index get count 1 n ret value move n index get count 1 b set cur sel if return n ret value clistboxst movebottom nindex bsetcursel nretvalue nindex nindex getcount nretvalue nindex getcount bsetcursel nretvalue void c list boxst draw item lpdrawitemstruct pdi struct cdc pdc cdc from handle pdi struct hdc bool b is selected false bool b is focused false bool b is disabled false colorref cr normal get sys color color window colorref cr selected get sys color color highlight colorref cr text get sys color color windowtext colorref cr color rgb 0 0 0 c string s text list box item text struct lbdata lplb data null lplb data struct lbdata c list box get item data ptr pdi struct itemid if lplb data null lplb data lpvoid 1l return b is selected pdi struct item state ods selected b is focused pdi struct item state ods focus b is disabled pdi struct item state ods disabled lplb data dw flags test bit0 test bit0 c rect rc item pdi struct rc item c rect rc icon pdi struct rc item c rect rc text pdi struct rc item c rect rc centered text pdi struct rc item pdc set bk mode transparent only for debug c brush br btn shadow rgb 255 0 0 pdc frame rect rc item br btn shadow calculate rc icon if m pimagelist rc icon right rc icon left m szimage cx lbst cx border 2 rc icon bottom rc icon top m szimage cy lbst cy border 2 if else rc icon set rect 0 0 0 0 calculate rc text rc text left rc icon right calculate rc centered text get list box item text c list box get text pdi struct itemid s text rc centered text rc text pdc draw text s text 1 rc centered text dt wordbreak dt expandtabs dt calcrect lplb data n format rc centered text offset rect 0 rc text height rc centered text height 2 draw rc icon background if m pimagelist if b is selected m byrowselect st fullrowselect b is disabled cr color cr selected else cr color cr normal on draw icon background pdi struct itemid pdc rc item rc icon b is disabled b is selected cr color if draw rc text rc centered text background if b is disabled pdc set text color get sys color color graytext cr color cr normal if else if b is selected pdc set text color 0x00ffffff cr text cr color cr selected if else pdc set text color cr text cr color cr normal else else if m byrowselect st textselect pdc fill solid rect rc centered text cr color on draw text background pdi struct itemid pdc rc item rc centered text b is disabled b is selected cr color else pdc fill solid rect rc text cr color on draw text background pdi struct itemid pdc rc item rc text b is disabled b is selected cr color draw the icon if any if m pimagelist on draw icon pdi struct itemid pdc rc item rc icon lplb data n image b is disabled b is selected draw text pdc draw text s text 1 rc centered text dt wordbreak dt expandtabs lplb data n format draw focus rectangle if b is focused b is disabled switch m byrowselect case st fullrowselect pdc draw focus rect rc item break case st fulltextselect pdc draw focus rect rc text break case st textselect default pdc draw focus rect rc centered text break switch if clistboxst drawitem pdistruct fromhandle pdistruct bisselected bisfocused bisdisabled crnormal getsyscolor color_window crselected getsyscolor color_highlight crtext getsyscolor color_windowtext crcolor cstring stext struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr pdistruct lplbdata lplbdata bisselected pdistruct itemstate ods_selected bisfocused pdistruct itemstate ods_focus bisdisabled pdistruct itemstate ods_disabled lplbdata dwflags test_bit0 test_bit0 crect rcitem pdistruct rcitem crect rcicon pdistruct rcitem crect rctext pdistruct rcitem crect rccenteredtext pdistruct rcitem setbkmode cbrush brbtnshadow framerect rcitem brbtnshadow rcicon m_pimagelist rcicon rcicon m_szimage lbst_cx_border rcicon rcicon m_szimage lbst_cy_border rcicon setrect rctext rctext rcicon rccenteredtext clistbox gettext pdistruct stext rccenteredtext rctext drawtext stext rccenteredtext dt_wordbreak dt_expandtabs dt_calcrect lplbdata nformat rccenteredtext offsetrect rctext rccenteredtext rcicon m_pimagelist bisselected m_byrowselect st_fullrowselect bisdisabled crcolor crselected crcolor crnormal ondrawiconbackground pdistruct rcitem rcicon bisdisabled bisselected crcolor rctext rccenteredtext bisdisabled settextcolor getsyscolor color_graytext crcolor crnormal bisselected settextcolor crtext crcolor crselected settextcolor crtext crcolor crnormal m_byrowselect st_textselect fillsolidrect rccenteredtext crcolor ondrawtextbackground pdistruct rcitem rccenteredtext bisdisabled bisselected crcolor fillsolidrect rctext crcolor ondrawtextbackground pdistruct rcitem rctext bisdisabled bisselected crcolor m_pimagelist ondrawicon pdistruct rcitem rcicon lplbdata nimage bisdisabled bisselected drawtext stext rccenteredtext dt_wordbreak dt_expandtabs lplbdata nformat bisfocused bisdisabled m_byrowselect st_fullrowselect drawfocusrect rcitem st_fulltextselect drawfocusrect rctext st_textselect drawfocusrect rccenteredtext dword c list boxst on draw text background int n index cdc pdc c rect prc item c rect prc text bool b is disabled bool b is selected colorref cr suggested color pdc set bk color cr suggested color pdc fill solid rect prc text cr suggested color return 0 clistboxst ondrawtextbackground nindex crect prcitem crect prctext bisdisabled bisselected crsuggestedcolor setbkcolor crsuggestedcolor fillsolidrect prctext crsuggestedcolor void c list boxst on destroy free resources c list box on destroy clistboxst ondestroy freeresources clistbox ondestroy bool c list boxst on reflected dblclk int n index lb err bool b outside false dword dw pos get message pos c point point int short loword dw pos int short hiword dw pos screen to client point n index item from point point b outside if b outside return is item enabled n index return false clistboxst onreflecteddblclk nindex lb_err boutside dwpos getmessagepos cpoint dwpos dwpos screentoclient nindex itemfrompoint boutside boutside isitemenabled nindex dword c list boxst on draw icon background int n index cdc pdc c rect prc item c rect prc icon bool b is disabled bool b is selected colorref cr suggested color pdc set bk color cr suggested color pdc fill solid rect prc icon left prc icon top prc icon width prc item height cr suggested color return 0 clistboxst ondrawiconbackground nindex crect prcitem crect prcicon bisdisabled bisselected crsuggestedcolor setbkcolor crsuggestedcolor fillsolidrect prcicon prcicon prcicon prcitem crsuggestedcolor dword c list boxst on draw icon int n index cdc pdc c rect prc item c rect prc icon int n image bool b is disabled bool b is selected hicon h icon null h icon m pimagelist extract icon n image if h icon c point point prc icon left lbst cx border prc icon top lbst cy border c size size m szimage ole pdc draw state point size h icon b is disabled dss disabled dss normal c brush null destroy icon h icon if return 0 clistboxst ondrawicon nindex crect prcitem crect prcicon nimage bisdisabled bisselected hicon hicon m_pimagelist extracticon nimage hicon cpoint prcicon lbst_cx_border prcicon lbst_cy_border csize m_szimage drawstate hicon bisdisabled dss_disabled dss_normal cbrush destroyicon hicon void c list boxst measure item lpmeasureitemstruct lp measure item struct assert lp measure item struct ctl type odt listbox cdc pdc getdc int n height 0 c string s text c list box get text lp measure item struct itemid s text c rect cs rect 0 0 lp measure item struct item width lp measure item struct item height n height pdc draw text s text 1 cs rect dt wordbreak dt expandtabs dt calcrect if m pimagelist lp measure item struct item height max n height m szimage cy lbst cy border 2 else lp measure item struct item height n height lp measure item struct item height lbst cy border 2 releasedc pdc clistboxst measureitem lpmeasureitemstruct lpmeasureitemstruct ctltype odt_listbox nheight cstring stext clistbox gettext lpmeasureitemstruct stext crect csrect lpmeasureitemstruct itemwidth lpmeasureitemstruct itemheight nheight drawtext stext csrect dt_wordbreak dt_expandtabs dt_calcrect m_pimagelist lpmeasureitemstruct itemheight nheight m_szimage lbst_cy_border lpmeasureitemstruct itemheight nheight lpmeasureitemstruct itemheight lbst_cy_border int c list boxst move int n old index int n new index bool b set cur sel int n inserted index lb err c string s text struct lbdata lplb data null struct lbdata cslb data if index is out of range if uint n old index uint get count return lb err get item text get text n old index s text get associated data zero memory cslb data sizeof cslb data lplb data struct lbdata c list box get item data n old index if lplb data lpvoid 1l copy memory cslb data lplb data sizeof cslb data if delete string delete string n old index insert string at new position n inserted index insert string n new index s text restore associated data replace item data n inserted index cslb data dw item data cslb data p data cslb data n image cslb data dw flags mask all select item if b set cur sel n inserted index lb err n inserted index lb errspace set cur sel n inserted index return n inserted index clistboxst noldindex nnewindex bsetcursel ninsertedindex lb_err cstring stext struct_lbdata lplbdata struct_lbdata cslbdata noldindex getcount lb_err gettext noldindex stext zeromemory cslbdata cslbdata lplbdata struct_lbdata clistbox getitemdata noldindex lplbdata copymemory cslbdata lplbdata cslbdata deletestring noldindex ninsertedindex insertstring nnewindex stext replaceitemdata ninsertedindex cslbdata dwitemdata cslbdata pdata cslbdata nimage cslbdata dwflags mask_all bsetcursel ninsertedindex lb_err ninsertedindex lb_errspace setcursel ninsertedindex ninsertedindex void c list boxst free resources int n count 0 n count get count if n count lb err for n count 0 n count delete item data n count 1 for clistboxst freeresources ncount ncount getcount ncount lb_err ncount ncount deleteitemdata ncount int c list boxst replace item data int n index dword dw item data lpvoid p data int n image dword dw flags byte by mask struct lbdata lplb data null int n ret value lb err get pointer to associated datas if any lplb data struct lbdata c list box get item data ptr n index if no datas exist create a new one if lplb data null lplb data new struct lbdata if lplb data zero memory lplb data sizeof struct lbdata if if lplb data if by mask mask dwdata mask dwdata lplb data dw item data dw item data if by mask mask lpdata mask lpdata lplb data p data p data if by mask mask nimage mask nimage lplb data n image n image if by mask mask dwflags mask dwflags lplb data dw flags dw flags n ret value c list box set item data ptr n index lplb data if return n ret value clistboxst replaceitemdata nindex dwitemdata pdata nimage dwflags bymask struct_lbdata lplbdata nretvalue lb_err lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata struct_lbdata lplbdata zeromemory lplbdata struct_lbdata lplbdata bymask mask_dwdata mask_dwdata lplbdata dwitemdata dwitemdata bymask mask_lpdata mask_lpdata lplbdata pdata pdata bymask mask_nimage mask_nimage lplbdata nimage nimage bymask mask_dwflags mask_dwflags lplbdata dwflags dwflags nretvalue clistbox setitemdataptr nindex lplbdata nretvalue void c list boxst delete item data int n index struct lbdata lplb data null get pointer to associated datas if any lplb data struct lbdata c list box get item data ptr n index if datas exist if lplb data lpvoid 1l delete lplb data c list box set item data ptr n index null clistboxst deleteitemdata nindex struct_lbdata lplbdata lplbdata struct_lbdata clistbox getitemdataptr nindex lplbdata lplbdata clistbox setitemdataptr nindex c layered window helperst c layered window helperst load dll m hdll load library t user32 dll clayeredwindowhelperst clayeredwindowhelperst m_hdll loadlibrary _t c layered window helperst c layered window helperst unload dll if any if m hdll free library m hdll m hdll null clayeredwindowhelperst clayeredwindowhelperst m_hdll freelibrary m_hdll m_hdll long c layered window helperst add layered style hwnd h wnd return set window long h wnd gwl exstyle get window long h wnd gwl exstyle ws ex layered clayeredwindowhelperst addlayeredstyle hwnd setwindowlong hwnd gwl_exstyle getwindowlong hwnd gwl_exstyle ws_ex_layered long c layered window helperst remove layered style hwnd h wnd return set window long h wnd gwl exstyle get window long h wnd gwl exstyle ws ex layered clayeredwindowhelperst removelayeredstyle hwnd setwindowlong hwnd gwl_exstyle getwindowlong hwnd gwl_exstyle ws_ex_layered bool c layered window helperst set layered window attributes hwnd h wnd colorref cr key byte b alpha dword dw flags bool b ret value true if m hdll lpfn set layered window attributes p fn null p fn lpfn set layered window attributes get proc address m hdll set layered window attributes if p fn b ret value p fn h wnd cr key b alpha dw flags if else b ret value false if return b ret value clayeredwindowhelperst setlayeredwindowattributes hwnd crkey balpha dwflags bretvalue m_hdll lpfnsetlayeredwindowattributes pfn pfn lpfnsetlayeredwindowattributes getprocaddress m_hdll setlayeredwindowattributes pfn bretvalue pfn hwnd crkey balpha dwflags bretvalue bretvalue bool c layered window helperst set transparent percentage hwnd h wnd uint by percentage do not accept values greater than 100 if by percentage 100 by percentage 100 return set layered window attributes h wnd 0 byte 255 by percentage 100 lwa alpha clayeredwindowhelperst settransparentpercentage hwnd bypercentage bypercentage bypercentage setlayeredwindowattributes hwnd bypercentage lwa_alpha last common route finder last common route finder min upload 1 max upload ui32 max m upload ui32 max m curupload 1 m ipingtolerancemilliseconds 200 m busemillisecondpingtolerance false m inumberofpingsforaverage 0 m pingaverage 0 m lowestping 0 m lowestinitialpingallowed 20 ping delays total 0 m state t need more hosts false thread ended event new c event 0 1 new trace route host event new c event 0 0 prefs event new c event 0 0 m initiatefastreactionperiod false m enabled false do run true afx begin thread run proc lpvoid this lastcommonroutefinder lastcommonroutefinder minupload maxupload _ui32_max m_upload _ui32_max m_curupload m_ipingtolerancemilliseconds m_busemillisecondpingtolerance m_inumberofpingsforaverage m_pingaverage m_lowestping m_lowestinitialpingallowed pingdelaystotal m_state _t needmorehosts threadendedevent cevent newtraceroutehostevent cevent prefsevent cevent m_initiatefastreactionperiod m_enabled dorun afxbeginthread runproc last common route finder last common route finder delete thread ended event delete new trace route host event delete prefs event lastcommonroutefinder lastcommonroutefinder threadendedevent newtraceroutehostevent prefsevent void last common route finder end thread signal the thread to stop looping and exit do run false prefs event set event new trace route host event set event wait for the thread to signal that it has stopped looping thread ended event lock lastcommonroutefinder endthread dorun prefsevent setevent newtraceroutehostevent setevent threadendedevent bool last common route finder add host to check uint32 ip bool got enough hosts true if need more hosts is goodip ip true add host locker lock if need more hosts got enough hosts add host to check no lock ip add host locker unlock return got enough hosts lastcommonroutefinder addhosttocheck gotenoughhosts needmorehosts isgoodip addhostlocker needmorehosts gotenoughhosts addhosttochecknolock addhostlocker gotenoughhosts bool last common route finder add hosts to check c up down client ptr list list bool got enough hosts true if need more hosts add host locker lock if need more hosts position pos list get head position if pos uint32 start pos rand rand max min list get count 100 for uint32 skip counter 0 skip counter start pos pos null skip counter list get next pos if pos pos list get head position uint32 try count 0 while need more hosts try count uint32 list get count try count c up down client client list get next pos if pos pos list get head position uint32 ip client getip add host to check no lock ip got enough hosts need more hosts add host locker unlock return got enough hosts lastcommonroutefinder addhoststocheck cupdownclientptrlist gotenoughhosts needmorehosts addhostlocker needmorehosts getheadposition startpos rand_max getcount skipcounter skipcounter startpos skipcounter getnext getheadposition trycount needmorehosts trycount getcount trycount cupdownclient getnext getheadposition addhosttochecknolock gotenoughhosts needmorehosts addhostlocker gotenoughhosts current ping struct last common route finder get current ping current ping struct return val if m enabled ping locker lock return val state m state return val latency m pingaverage return val lowest m lowestping return val current limit m upload ping locker unlock else return val state t return val latency 0 return val lowest 0 return val current limit 0 return return val currentpingstruct lastcommonroutefinder getcurrentping currentpingstruct returnval m_enabled pinglocker returnval m_state returnval m_pingaverage returnval m_lowestping returnval currentlimit m_upload pinglocker returnval _t returnval returnval returnval currentlimit returnval bool last common route finder accept new client return accept new client m enabled if enabled then return accept new client otherwise return true lastcommonroutefinder acceptnewclient acceptnewclient m_enabled acceptnewclient void last common route finder set prefs bool p enabled uint32 p cur upload uint32 p min upload uint32 p max upload bool p use millisecond ping tolerance double p ping tolerance uint32 p ping tolerance milliseconds uint32 p going up divider uint32 p going down divider uint32 p number of pings for average uint64 p lowest initial ping allowed bool send event false prefs locker lock if p min upload 1024 min upload 1024 else min upload p min upload if p max upload 0 max upload p max upload if max upload min upload min upload max upload else max upload p cur upload 10 1024 ui32 max if p enabled m enabled false send event true this will show the area for ping info in status bar the app emuledlg set status bar parts size else if p enabled false if m enabled this will remove the area for ping info in status bar the app emuledlg set status bar parts size prefs event reset event send event true this will resize the area for ping info in status bar if m busemillisecondpingtolerance p use millisecond ping tolerance the app emuledlg set status bar parts size m enabled p enabled m busemillisecondpingtolerance p use millisecond ping tolerance m pingtolerance p ping tolerance m ipingtolerancemilliseconds p ping tolerance milliseconds m goingupdivider p going up divider m goingdowndivider p going down divider m curupload p cur upload m inumberofpingsforaverage p number of pings for average m lowestinitialpingallowed p lowest initial ping allowed upload locker lock if m upload max upload p enabled false m upload max upload upload locker unlock prefs locker unlock if send event prefs event set event lastcommonroutefinder setprefs penabled pcurupload pminupload pmaxupload pusemillisecondpingtolerance ppingtolerance ppingtolerancemilliseconds pgoingupdivider pgoingdowndivider pnumberofpingsforaverage plowestinitialpingallowed sendevent prefslocker pminupload minupload minupload pminupload pmaxupload maxupload pmaxupload maxupload minupload minupload maxupload maxupload pcurupload _ui32_max penabled m_enabled sendevent theapp setstatusbarpartssize penabled m_enabled theapp setstatusbarpartssize prefsevent resetevent sendevent m_busemillisecondpingtolerance pusemillisecondpingtolerance theapp setstatusbarpartssize m_enabled penabled m_busemillisecondpingtolerance pusemillisecondpingtolerance m_pingtolerance ppingtolerance m_ipingtolerancemilliseconds ppingtolerancemilliseconds m_goingupdivider pgoingupdivider m_goingdowndivider pgoingdowndivider m_curupload pcurupload m_inumberofpingsforaverage pnumberofpingsforaverage m_lowestinitialpingallowed plowestinitialpingallowed uploadlocker m_upload maxupload penabled m_upload maxupload uploadlocker prefslocker sendevent prefsevent setevent void last common route finder initiate fast reaction period prefs locker lock m initiatefastreactionperiod true prefs locker unlock lastcommonroutefinder initiatefastreactionperiod prefslocker m_initiatefastreactionperiod prefslocker uint32 last common route finder get upload uint32 return value upload locker lock return value m upload upload locker unlock return return value lastcommonroutefinder getupload returnvalue uploadlocker returnvalue m_upload uploadlocker returnvalue uint afx cdecl last common route finder run proc lpvoid p param dbg set thread name last common route finder init thread locale last common route finder last common route finder last common route finder p param return last common route finder run internal afx_cdecl lastcommonroutefinder runproc pparam dbgsetthreadname lastcommonroutefinder initthreadlocale lastcommonroutefinder lastcommonroutefinder lastcommonroutefinder pparam lastcommonroutefinder runinternal uint last common route finder run internal pinger pinger bool has succeeded at least once false while do run wait for updated prefs prefs event lock bool enabled m enabled retry loop enabled will be set to false in end of this loop if to many failures tries too large while do run enabled bool found last common host false uint32 last common host 0 uint32 last commonttl 0 uint32 host to ping 0 bool use udp false hosts to trace route remove all ping delays remove all ping delays total 0 ping locker lock m pingaverage 0 m lowestping 0 m state get res string ids uss state preparing ping locker unlock calculate a good starting value for the upload control if the user has entered a max upload value we use that otherwise 10 k bytes s int start upload max upload ui32 max max upload 10 1024 bool at least one ping succeded false while do run enabled found last common host false uint32 trace route tries 0 while do run enabled found last common host false trace route tries 5 has succeeded at least once trace route tries ui32 max hosts to trace route get count 10 has succeeded at least once trace route tries last common host 0 the app queue debug log line false t upload speed sense try i collecting hosts trace route tries add host locker lock need more hosts true add host locker unlock wait for hosts to traceroute new trace route host event lock the app queue debug log line false t upload speed sense got enough hosts listing the hosts that will be tracerouted position pos hosts to trace route get start position int counter 0 while pos null counter uint32 host to trace route dummy hosts to trace route get next assoc pos host to trace route dummy in addr st dest addr st dest addr s addr host to trace route the app queue debug log line false t upload speed sense host i s counter ipstr st dest addr find the last common host using traceroute the app queue debug log line false t upload speed sense starting traceroutes to find last common host for the tracerouting phase preparing we need to disable uploads so we get a faster traceroute and better ping values set upload 2 1024 sleep sec2ms 1 if m enabled false enabled false bool failed false uint32 cur host 0 for uint32 ttl 1 do run enabled cur host 0 ttl 64 cur host 0 ttl 5 found last common host false failed false ttl the app queue debug log line false t upload speed sense pinging for ttl i ttl use udp false pending get default value from prefs cur host 0 if m enabled false enabled false uint32 last succeding ping address 0 uint32 last destination address 0 uint32 hosts to trace route counter 0 bool failed this ttl false position pos hosts to trace route get start position while do run enabled failed false failed this ttl false pos null last destination address 0 last destination address cur host ping status success false ping status error ip req timed out ping status ping status 0 hosts to trace route counter this is the current address we send ping to in loop below pending don t confuse this with cur host which is unfortunately almost the same name will rename one of these variables as soon as possible to get more different names uint32 cur address dummy hosts to trace route get next assoc pos cur address dummy ping status success false for int counter 0 do run enabled counter 2 ping status success false ping status success true ping status status ip success ping status status ip ttl expired transit counter ping status pinger ping cur address ttl true use udp if do run enabled ping status success false ping status success true ping status status ip success ping status status ip ttl expired transit counter 3 1 in addr st dest addr st dest addr s addr cur address the app queue debug log line false t upload speed sense failure i to ping host ttl i ip s error i sleeping 1 sec before retry error info follows counter 1 ttl ipstr st dest addr ping status success ping status status ping status error pinger p icmp err ping status success ping status status ping status error sleep 1000 if m enabled false enabled false trying other ping method use udp use udp if ping status success true ping status status ip ttl expired transit if cur host 0 cur host ping status destination address at least one ping succeded true last succeding ping address cur address last destination address ping status destination address else failed to ping this host for some reason or we reached the actual host we are pinging we don t want that since it is too close remove it in addr st dest addr st dest addr s addr cur address if ping status success true ping status status ip success the app queue debug log line false t upload speed sense host was too close removing this host ttl i ip s status i removing this host and restarting host collection ttl ipstr st dest addr ping status status hosts to trace route remove key cur address else if ping status success true ping status status ip dest host unreachable the app queue debug log line false t upload speed sense host unreacheable ttl i ip s status i removing this host status info follows ttl ipstr st dest addr ping status status pinger p icmp err ping status status hosts to trace route remove key cur address else if ping status success true the app queue debug log line false t upload speed sense unknown ping status ttl i ip s status i reason follows changing ping method to see if it helps ttl ipstr st dest addr ping status status pinger p icmp err ping status status use udp use udp else if ping status error ip req timed out the app queue debug log line false t upload speed sense timeout when pinging a host ttl i ip s error i keeping host error info follows ttl ipstr st dest addr ping status error pinger p icmp err ping status error if hosts to trace route counter 2 last succeding ping address 0 several pings have timed out on this ttl probably we can t ping on this ttl at all failed this ttl true else the app queue debug log line false t upload speed sense unknown pinging error ttl i ip s status i reason follows changing ping method to see if it helps ttl ipstr st dest addr ping status error pinger p icmp err ping status error use udp use udp if hosts to trace route get size 8 the app queue debug log line false t upload speed sense to few hosts to traceroute left restarting host colletion failed true if failed false if cur host 0 last destination address 0 if last destination address cur host in addr st dest addr st dest addr s addr cur host the app queue debug log line false t upload speed sense host at ttl i s ttl ipstr st dest addr last common host cur host last commonttl ttl else if last succeding ping address 0 found last common host true host to ping last succeding ping address c string host to ping string ipstr host to ping if last common host 0 the app queue debug log line false t upload speed sense found differing host at ttl i s this will be the host to ping ttl host to ping string else c string last common host string ipstr last destination address last common host last destination address last commonttl ttl the app queue debug log line false t upload speed sense found differing host at ttl i but last ttl couldn t be pinged so we don t know last common host taking a chance and using first differing ip as last commonhost host to ping s faked last common host s ttl host to ping string last common host string else if ttl 4 the app queue debug log line false t upload speed sense could perform no ping at all at ttl i trying next ttl ttl else the app queue debug log li lastcommonroutefinder runinternal hassucceededatleastonce dorun prefsevent m_enabled dorun foundlastcommonhost lastcommonhost lastcommonttl hosttoping useudp hoststotraceroute removeall pingdelays removeall pingdelaystotal pinglocker m_pingaverage m_lowestping m_state getresstring ids_uss_state_preparing pinglocker kbytes startupload maxupload _ui32_max maxupload atleastonepingsucceded dorun foundlastcommonhost traceroutetries dorun foundlastcommonhost traceroutetries hassucceededatleastonce traceroutetries _ui32_max hoststotraceroute getcount hassucceededatleastonce traceroutetries lastcommonhost theapp queuedebuglogline _t uploadspeedsense traceroutetries addhostlocker needmorehosts addhostlocker newtraceroutehostevent theapp queuedebuglogline _t uploadspeedsense hoststotraceroute getstartposition hosttotraceroute hoststotraceroute getnextassoc hosttotraceroute in_addr stdestaddr stdestaddr s_addr hosttotraceroute theapp queuedebuglogline _t uploadspeedsense stdestaddr theapp queuedebuglogline _t uploadspeedsense setupload m_enabled curhost dorun curhost curhost foundlastcommonhost theapp queuedebuglogline _t uploadspeedsense useudp curhost m_enabled lastsuccedingpingaddress lastdestinationaddress hoststotraceroutecounter failedthisttl hoststotraceroute getstartposition dorun failedthisttl lastdestinationaddress lastdestinationaddress curhost pingstatus pingstatus ip_req_timed_out pingstatus pingstatus hoststotraceroutecounter curhost curaddress hoststotraceroute getnextassoc curaddress pingstatus dorun pingstatus pingstatus pingstatus ip_success pingstatus ip_ttl_expired_transit pingstatus curaddress useudp dorun pingstatus pingstatus pingstatus ip_success pingstatus ip_ttl_expired_transit in_addr stdestaddr stdestaddr s_addr curaddress theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus pingstatus pingstatus picmperr pingstatus pingstatus pingstatus m_enabled useudp useudp pingstatus pingstatus ip_ttl_expired_transit curhost curhost pingstatus destinationaddress atleastonepingsucceded lastsuccedingpingaddress curaddress lastdestinationaddress pingstatus destinationaddress in_addr stdestaddr stdestaddr s_addr curaddress pingstatus pingstatus ip_success theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus hoststotraceroute removekey curaddress pingstatus pingstatus ip_dest_host_unreachable theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus picmperr pingstatus hoststotraceroute removekey curaddress pingstatus theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus picmperr pingstatus useudp useudp pingstatus ip_req_timed_out theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus picmperr pingstatus hoststotraceroutecounter lastsuccedingpingaddress failedthisttl theapp queuedebuglogline _t uploadspeedsense stdestaddr pingstatus picmperr pingstatus useudp useudp hoststotraceroute getsize theapp queuedebuglogline _t uploadspeedsense curhost lastdestinationaddress lastdestinationaddress curhost in_addr stdestaddr stdestaddr s_addr curhost theapp queuedebuglogline _t uploadspeedsense stdestaddr lastcommonhost curhost lastcommonttl lastsuccedingpingaddress foundlastcommonhost hosttoping lastsuccedingpingaddress cstring hosttopingstring hosttoping lastcommonhost theapp queuedebuglogline _t uploadspeedsense hosttopingstring cstring lastcommonhoststring lastdestinationaddress lastcommonhost lastdestinationaddress lastcommonttl theapp queuedebuglogline _t uploadspeedsense lastcommonhost hosttopingstring lastcommonhoststring theapp queuedebuglogline _t uploadspeedsense theapp queuedebuglogli void last common route finder set upload uint32 new value upload locker lock m upload new value upload locker unlock lastcommonroutefinder setupload newvalue uploadlocker m_upload newvalue uploadlocker bool last common route finder add host to check no lock uint32 ip if need more hosts is goodip ip true hosts to trace route add tail ip hosts to trace route set at ip 0 if hosts to trace route get count 10 need more hosts false signal that there s hosts to fetch new trace route host event set event return need more hosts lastcommonroutefinder addhosttochecknolock needmorehosts isgoodip hoststotraceroute addtail hoststotraceroute setat hoststotraceroute getcount needmorehosts newtraceroutehostevent setevent needmorehosts uint32 last common route finder median u int32 clist list uint32 size list get count if size 1 return list get head else if size 2 return list get head list get tail 2 else if size 2 if more than 2 elements we need to sort them to find the middle uint32 arr new uint32 size uint32 counter 0 for position pos list get head position pos list get next pos arr counter list get at pos counter std sort arr arr size double return val if size 2 return val arr size 2 else return val arr size 2 1 arr size 2 2 delete arr return uint return val else undefined shouldn t be called with no elements in list return 0 lastcommonroutefinder uint32clist getcount gethead gethead gettail getheadposition getnext getat returnval returnval returnval returnval c frame grab thread c frame grab thread cframegrabthread cframegrabthread c frame grab thread c frame grab thread cframegrabthread cframegrabthread uint c frame grab thread grab frames define timebetweenframes 50 0 could be a param later if needed for int i 0 i n frames to grab i img results i null try hresult hr c com ptr i media det p det co initialize null hr p det co create instance uuidof media det if succeeded hr return 0 convert the file name to a bstr c combstr bstr filename str file name hr p det put filename bstr filename long l streams bool b found false hr p det get outputstreams l streams for long i 0 i l streams i guid major type hr p det put currentstream i hr p det get streamtype major type if major type mediatype video b found true break if b found return 0 double d length 0 p det get streamlength d length if d start time d length d start time 0 long width 0 height 0 am media type mt hr p det get streammediatype mt if mt formattype format videoinfo videoinfoheader p vih videoinfoheader mt pb format width p vih bmi header bi width height p vih bmi header bi height we want the absolute height don t care about orientation if height 0 height 1 else return 0 should not happen in theory free media type mt if mt cb format 0 co task mem free pvoid mt pb format mt cb format 0 mt pb format null if mt p unk null mt p unk release mt p unk null long size uint32 n frames grabbed for n frames grabbed 0 n frames grabbed n frames to grab n frames grabbed hr p det get bitmap bits d start time n frames grabbed timebetweenframes size null width height if succeeded hr we could also directly create a bitmap in memory however this caused problems failed with some movie files when i tried it for the mm preview while this method works always so i ll continue to use this one long n full buffer len sizeof bitmapfileheader size char buffer new char n full buffer len bitmapfileheader bfh memset bfh 0 sizeof bfh bfh bf type mb bfh bf size n full buffer len bfh bf off bits sizeof bitmapinfoheader sizeof bitmapfileheader memcpy buffer bfh sizeof bfh try hr p det get bitmap bits d start time n frames grabbed timebetweenframes null buffer sizeof bfh width height catch assert 0 hr e fail if succeeded hr decode cx image img result new cx image img result decode byte buffer n full buffer len cximage format bmp delete buffer if img result is valid delete img result break resize if needed if n max width 0 n max width width float scale float n max width img result get width int n max heigth int img result get height scale img result resample n max width n max heigth 0 decrease bpp if needed if b reduce color c quantizer q 256 8 q process image img result getdib rgbquad ppal rgbquad malloc 256 sizeof rgbquad q set color table ppal img result decrease bpp 8 true ppal free ppal c string test name test name format g testframe i png n frames grabbed img result save test name cximage format png done img results n frames grabbed img result else delete buffer break return n frames grabbed catch assert 0 return 0 cframegrabthread grabframes nframestograb imgresults ccomptr imediadet pdet coinitialize pdet cocreateinstance __uuidof mediadet ccombstr bstrfilename strfilename pdet put_filename bstrfilename lstreams bfound pdet get_outputstreams lstreams lstreams major_type pdet put_currentstream pdet get_streamtype major_type major_type mediatype_video bfound bfound dlength pdet get_streamlength dlength dstarttime dlength dstarttime am_media_type pdet get_streammediatype format_videoinfo pvih pbformat pvih bmiheader biwidth pvih bmiheader biheight freemediatype cbformat cotaskmemfree pbformat cbformat pbformat punk punk punk nframesgrabbed nframesgrabbed nframesgrabbed nframestograb nframesgrabbed pdet getbitmapbits dstarttime nframesgrabbed mmpreview nfullbufferlen nfullbufferlen bftype bfsize nfullbufferlen bfoffbits pdet getbitmapbits dstarttime nframesgrabbed e_fail cximage imgresult cximage imgresult nfullbufferlen cximage_format_bmp imgresult isvalid imgresult nmaxwidth nmaxwidth nmaxwidth imgresult getwidth nmaxheigth imgresult getheight imgresult nmaxwidth nmaxheigth breducecolor cquantizer processimage imgresult setcolortable imgresult decreasebpp cstring testname testname nframesgrabbed imgresult testname cximage_format_png imgresults nframesgrabbed imgresult nframesgrabbed bool c frame grab thread init instance dbg set thread name frame grab thread init thread locale return true cframegrabthread initinstance dbgsetthreadname framegrabthread initthreadlocale bool c frame grab thread run img results new cx image n frames to grab framegrabresult struct result new framegrabresult struct result n images grabbed uint8 grab frames result img results img results result p sender p sender verify post message the app emuledlg m hwnd tm framegrabfinished wparam p owner lparam result return 0 cframegrabthread imgresults cximage nframestograb framegrabresult_struct framegrabresult_struct nimagesgrabbed grabframes imgresults imgresults psender psender postmessage theapp m_hwnd tm_framegrabfinished powner void c frame grab thread set values const c known file in powner c string in strfilename uint8 in nframestograb double in dstarttime bool in breducecolor uint16 in nmaxwidth void in psender str file name in strfilename n frames to grab in nframestograb d start time in dstarttime b reduce color in breducecolor n max width in nmaxwidth p owner in powner p sender in psender cframegrabthread setvalues cknownfile in_powner cstring in_strfilename in_nframestograb in_dstarttime in_breducecolor in_nmaxwidth in_psender strfilename in_strfilename nframestograb in_nframestograb dstarttime in_dstarttime breducecolor in_breducecolor nmaxwidth in_nmaxwidth powner in_powner psender in_psender c kad contact histogram ctrl c kad contact histogram ctrl assert 1 kad contact hist needed bits kad contact hist size memset m ahist 0 sizeof m ahist m penaxis create pen ps solid 1 rgb 128 128 128 m penaux create pen ps dot 1 rgb 192 192 192 m penhist create pen ps solid 1 rgb 255 32 32 m fontlabel create point font 8 10 t ms shell dlg m imaxnumlabelwidth 3 8 m imaxlabelheight 8 m binitializedfontmetrics false ckadcontacthistogramctrl ckadcontacthistogramctrl kad_contact_hist_needed_bits kad_contact_hist_size m_ahist m_ahist m_penaxis createpen ps_solid m_penaux createpen ps_dot m_penhist createpen ps_solid m_fontlabel createpointfont _t m_imaxnumlabelwidth m_imaxlabelheight m_binitializedfontmetrics c kad contact histogram ctrl c kad contact histogram ctrl ckadcontacthistogramctrl ckadcontacthistogramctrl void c kad contact histogram ctrl localize m strxaxis get res string ids kademlia t get res string ids network m stryaxis get res string ids kadcontactlab if m hwnd invalidate ckadcontacthistogramctrl m_strxaxis getresstring ids_kademlia _t getresstring ids_network m_stryaxis getresstring ids_kadcontactlab m_hwnd bool c kad contact histogram ctrl contact add const kademlia c contact contact kademlia cu int128 distance contact get clientid distance uint u hist slot get hist slot distance m ahist u hist slot invalidate return true ckadcontacthistogramctrl contactadd ccontact cuint128 getclientid uhistslot gethistslot m_ahist uhistslot void c kad contact histogram ctrl contact rem const kademlia c contact contact kademlia cu int128 distance contact get clientid distance uint u hist slot get hist slot distance assert m ahist u hist slot 0 if m ahist u hist slot 0 m ahist u hist slot invalidate ckadcontacthistogramctrl contactrem ccontact cuint128 getclientid uhistslot gethistslot m_ahist uhistslot m_ahist uhistslot m_ahist uhistslot void c kad contact histogram ctrl on paint c paintdc dc this c rect rc clnt get client rect rc clnt if rc clnt is rect empty return dc fill solid rect rc clnt rgb 255 255 255 c font p old font dc select object m fontlabel if m binitializedfontmetrics textmetric tm dc get text metrics tm why is tm tm max char width and tm tm ave char width that wrong c rect rc label dc draw text t 888 3 rc label dt calcrect m imaxnumlabelwidth rc label width if m imaxnumlabelwidth 0 m imaxnumlabelwidth 3 8 m imaxlabelheight tm tm height if m imaxlabelheight 0 m imaxlabelheight 8 m binitializedfontmetrics true int i left border 1 m imaxnumlabelwidth 3 int i right border 8 int i top border m imaxlabelheight int i bottom border m imaxlabelheight int i base linex i left border int i base liney rc clnt bottom i bottom border uint u hist width rc clnt width i left border i right border if u hist width arrsize m ahist u hist width arrsize m ahist else if u hist width 0 dc select object p old font return uint u hist height rc clnt height i top border i bottom border if u hist height 0 dc select object p old font return int i 0 uint u max m ahist i while i arrsize m ahist if m ahist i u max u max m ahist i i lets take the average this will keep the cluster of closest contacts from streching the graph too far u max arrsize m ahist if u max 15 u max 15 u hist height uint u labels u hist height m imaxlabelheight m imaxlabelheight 2 if u labels 0 dc select object p old font return uint u step u max u labels 5 10 10 if u step 5 u step 5 c pen p old pen dc select object m penaxis dc move to i base linex rc clnt top i top border dc line to i base linex i base liney dc line to i base linex u hist width i base liney dc select object m penaux for uint s 0 s u max s u step int y i base liney u hist height s u max int i labely y m imaxlabelheight 2 c rect rc label 1 i labely 1 m imaxnumlabelwidth i labely m imaxlabelheight if s 0 dc move to i base linex 2 y dc line to i base linex u hist width y tchar sz label 12 int i label len stprintf sz label t u s dc draw text sz label i label len rc label dt right dt noclip c rect rc label rc clnt rc label left i base linex rc label bottom m imaxlabelheight dc draw text m stryaxis m stryaxis get length rc label dt left dt top dt noclip rc label rc clnt rc label top rc clnt bottom m imaxlabelheight 1 dc draw text m strxaxis m strxaxis get length rc label dt right dt bottom dt noclip int i last hx 1 for uint x 0 x u hist width x int hx x arrsize m ahist u hist width uint hv m ahist hx i last hx while i last hx hx hv m ahist i last hx if hv u max dc select object m penaxis hv u max else dc select object m penhist if hv dc move to i base linex x i base liney 1 uint u hist val hv u hist height u max dc line to i base linex x i base liney 1 u hist val 1 dc select object p old pen dc select object p old font ckadcontacthistogramctrl onpaint cpaintdc crect rcclnt getclientrect rcclnt rcclnt isrectempty fillsolidrect rcclnt cfont poldfont selectobject m_fontlabel m_binitializedfontmetrics gettextmetrics tmmaxcharwidth tmavecharwidth crect rclabel drawtext _t rclabel dt_calcrect m_imaxnumlabelwidth rclabel m_imaxnumlabelwidth m_imaxnumlabelwidth m_imaxlabelheight tmheight m_imaxlabelheight m_imaxlabelheight m_binitializedfontmetrics ileftborder m_imaxnumlabelwidth irightborder itopborder m_imaxlabelheight ibottomborder m_imaxlabelheight ibaselinex ileftborder ibaseliney rcclnt ibottomborder uhistwidth rcclnt ileftborder irightborder uhistwidth m_ahist uhistwidth m_ahist uhistwidth selectobject poldfont uhistheight rcclnt itopborder ibottomborder uhistheight selectobject poldfont umax m_ahist m_ahist m_ahist umax umax m_ahist umax m_ahist umax umax uhistheight ulabels uhistheight m_imaxlabelheight m_imaxlabelheight ulabels selectobject poldfont ustep umax ulabels ustep ustep cpen poldpen selectobject m_penaxis moveto ibaselinex rcclnt itopborder lineto ibaselinex ibaseliney lineto ibaselinex uhistwidth ibaseliney selectobject m_penaux umax ustep ibaseliney uhistheight umax ilabely m_imaxlabelheight crect rclabel ilabely m_imaxnumlabelwidth ilabely m_imaxlabelheight moveto ibaselinex lineto ibaselinex uhistwidth szlabel ilabellen _stprintf szlabel _t drawtext szlabel ilabellen rclabel dt_right dt_noclip crect rclabel rcclnt rclabel ibaselinex rclabel m_imaxlabelheight drawtext m_stryaxis m_stryaxis getlength rclabel dt_left dt_top dt_noclip rclabel rcclnt rclabel rcclnt m_imaxlabelheight drawtext m_strxaxis m_strxaxis getlength rclabel dt_right dt_bottom dt_noclip ilasthx uhistwidth m_ahist uhistwidth m_ahist ilasthx ilasthx m_ahist ilasthx umax selectobject m_penaxis umax selectobject m_penhist moveto ibaselinex ibaseliney uhistval uhistheight umax lineto ibaselinex ibaseliney uhistval selectobject poldpen selectobject poldfont c kademlia main c kademlia main void m status new status m status m connected false m status m firewalled true m status m ip 0 m status m tcpport 0 m status m totalfile 0 m status m totalstoresrc 0 m status m totalstorekey 0 m status m udpport 0 m status m kademliausers 0 m status m totalcontacts 0 m status m keywordpublish false m bootstraptimer time null ckademliamain ckademliamain m_status m_status m_connected m_status m_firewalled m_status m_ip m_status m_tcpport m_status m_totalfile m_status m_totalstoresrc m_status m_totalstorekey m_status m_udpport m_status m_kademliausers m_status m_totalcontacts m_status m_keywordpublish m_bootstraptimer c kademlia main c kademlia main void delete m status ckademliamain ckademliamain m_status void c kademlia main set status status val if m status m connected val m connected delete m status m status val the app emuledlg show connection state the app emuledlg show user count if m status m connected add log line true kademlia s get res string ids connected else add log line true kademlia s get res string ids disconnected else if val m status m firewalled val m firewalled m status m ip val m ip m status m udpport val m udpport m status m tcpport val m tcpport delete m status m status val the app emuledlg show connection state the app emuledlg show user count else delete m status m status val the app emuledlg show user count ckademliamain setstatus m_status m_connected m_connected m_status m_status theapp showconnectionstate theapp showusercount m_status m_connected addlogline getresstring ids_connected addlogline getresstring ids_disconnected m_status m_firewalled m_firewalled m_status m_ip m_ip m_status m_udpport m_udpport m_status m_tcpport m_tcpport m_status m_status theapp showconnectionstate theapp showusercount m_status m_status theapp showusercount status c kademlia main get status return m status ckademliamain getstatus m_status bool c kademlia main is connected return m status m connected ckademliamain isconnected m_status m_connected bool c kademlia main is firewalled return m status m firewalled ckademliamain isfirewalled m_status m_firewalled void c kademlia main connect if kademlia c timer get threadid bool udp change false while the app glob prefs get kadudp port the app glob prefs getudp port the app glob prefs get kadudp port what is the servers listen udp port the app glob prefs set kadudp port the app glob prefs get kadudp port 1 udp change true if udp change c string msg msg format get res string ids kadudpporterr the app glob prefs get kadudp port afx message box msg the app emuledlg kademliawnd contact list hide the app emuledlg kademliawnd search list hide kademlia c prefs startup kad pref new kademlia c prefs startup kad pref settcp port the app glob prefs get port startup kad pref setudp port the app glob prefs get kadudp port kademlia cu int128 clientid clientid set value uchar the app glob prefs get user hash startup kad pref set client hash clientid kademlia c kademlia start startup kad pref kademlia c kademlia set shared file list the app sharedfiles the app emuledlg kademliawnd contact list visable the app emuledlg kademliawnd search list visable the app emuledlg show connection state ckademliamain ctimer getthreadid udpchange theapp glob_prefs getkadudpport theapp glob_prefs getudpport theapp glob_prefs getkadudpport theapp glob_prefs setkadudpport theapp glob_prefs getkadudpport udpchange udpchange cstring getresstring ids_kadudpporterr theapp glob_prefs getkadudpport afxmessagebox theapp contactlist theapp searchlist cprefs startupkadpref cprefs startupkadpref settcpport theapp glob_prefs getport startupkadpref setudpport theapp glob_prefs getkadudpport cuint128 setvalue theapp glob_prefs getuserhash startupkadpref setclienthash ckademlia startupkadpref ckademlia setsharedfilelist theapp theapp contactlist theapp searchlist theapp showconnectionstate void c kademlia main dis connect if kademlia c timer get threadid if the app emuledlg is running the app emuledlg toolbar enable button idc toolbarbutton 0 false the app emuledlg kademliawnd get dlg item idc kadconnect enable window false the app emuledlg kademliawnd contact list hide the app emuledlg kademliawnd search list hide if the app emuledlg is running s kad stop params p stop params new s kad stop params p stop params dw flags the app emuledlg is running 1 0 p stop params p kad main this c win thread p kad stop thread new c win thread kad stop func lpvoid p stop params if p kad stop thread create thread delete p kad stop thread delete p stop params the app emuledlg kademliawnd contact list visable the app emuledlg kademliawnd search list visable the app emuledlg kademliawnd get dlg item idc kadconnect enable window true the app emuledlg toolbar enable button idc toolbarbutton 0 the app emuledlg show connection state assert 0 return else this is at least needed for a debug build if we want to stop the kad threads and properly free all memory to detect mem leaks we have to wait until the kad threads finished and performed their cleanup code this takes a noticeable amount of time and could maybe avoided for a release build though even for a release build there should be some special shutdown code which waits at least as long as the kad threads have closed their sockets a fast way for a release build only and only for application shutdown could be to properly let the kad threads exit the message loops close the sockets save the files all this should not take too much time in a synchronized way and after that just asynchronously kill the kad threads not caring about memory will be freed by system kademlia c kademlia stop true please leave this in a bit for testing to see if it does lockup if kademlia c timer get threadid m status m connected false m status m firewalled true m status m kademliausers 0 the app emuledlg show connection state ckademliamain disconnect ctimer getthreadid theapp isrunning theapp enablebutton idc_toolbarbutton theapp getdlgitem idc_kadconnect enablewindow theapp contactlist theapp searchlist theapp isrunning skadstopparams pstopparams skadstopparams pstopparams dwflags theapp isrunning pstopparams pkadmain cwinthread pkadstopthread cwinthread kadstopfunc pstopparams pkadstopthread createthread pkadstopthread pstopparams theapp contactlist theapp searchlist theapp getdlgitem idc_kadconnect enablewindow theapp enablebutton idc_toolbarbutton theapp showconnectionstate ckademlia ctimer getthreadid m_status m_connected m_status m_firewalled m_status m_kademliausers theapp showconnectionstate dword c kademlia main get threadid return kademlia c timer get threadid ckademliamain getthreadid ctimer getthreadid void c kademlia main bootstrap c string ip uint16 port if get status m totalcontacts return if kademlia c timer get threadid is connected time null m bootstraptimer 10 if ip port kademlia c kademlia getudp listener bootstrap ip port m bootstraptimer time null else c up down client client the app clientlist get random kad client if client kademlia c kademlia getudp listener bootstrap ntohl client getip client get kad port m bootstraptimer time null ckademliamain cstring getstatus m_totalcontacts ctimer getthreadid isconnected m_bootstraptimer ckademlia getudplistener m_bootstraptimer cupdownclient theapp getrandomkadclient ckademlia getudplistener getkadport m_bootstraptimer void c kademlia main bootstrap uint32 ip uint16 port if get status m totalcontacts return if kademlia c timer get threadid is connected time null m bootstraptimer 10 if ip port kademlia c kademlia getudp listener bootstrap ip port m bootstraptimer time null else c up down client client the app clientlist get random kad client if client kademlia c kademlia getudp listener bootstrap ntohl client getip client get kad port m bootstraptimer time null ckademliamain getstatus m_totalcontacts ctimer getthreadid isconnected m_bootstraptimer ckademlia getudplistener m_bootstraptimer cupdownclient theapp getrandomkadclient ckademlia getudplistener getkadport m_bootstraptimer uint32 c kademlia main getip return m status m ip ckademliamain m_status m_ip uint16 c kademlia main get udp port return m status m udpport ckademliamain getudpport m_status m_udpport uint16 c kademlia main get tcp port return m status m tcpport ckademliamain gettcpport m_status m_tcpport c resizable dialog cip filter dlg idd p parent m uipfilteritems 0 m ppipfilteritems null m icodlg null m pmenuipfilter null m ulfilteredips 0 m ipfilter m pparent this m ipfilter set registry key pref ini section m ipfilter set registry prefix t ipfilters m ipfilter m pfnfinditem find item m ipfilter m lfinditemparam dword ptr this cresizabledialog cipfilterdlg pparent m_uipfilteritems m_ppipfilteritems m_icodlg m_pmenuipfilter m_ulfilteredips m_ipfilter m_pparent m_ipfilter setregistrykey pref_ini_section m_ipfilter setregistryprefix _t ipfilters_ m_ipfilter m_pfnfinditem finditem m_ipfilter m_lfinditemparam dword_ptr cip filter dlg cip filter dlg free m ppipfilteritems delete m pmenuipfilter sm isortcolumn m ipfilter get sort column if m icodlg verify destroy icon m icodlg cipfilterdlg cipfilterdlg m_ppipfilteritems m_pmenuipfilter sm_isortcolumn m_ipfilter getsortcolumn m_icodlg destroyicon m_icodlg void cip filter dlg sortip filter items update sort if needed the listview items if m ipfilter get sort column 1 lparamsort m ipfilter get sort column qsort void m ppipfilteritems m uipfilteritems sizeof m ppipfilteritems compareip filter items cipfilterdlg sortipfilteritems m_ipfilter getsortcolumn _lparamsort m_ipfilter getsortcolumn m_ppipfilteritems m_uipfilteritems m_ppipfilteritems compareipfilteritems void cip filter dlg initip filters c wait cursor cur wait m uipfilteritems 0 free m ppipfilteritems m ppipfilteritems null const cip filter array ipfilter the app ipfilter getip filter m uipfilteritems ipfilter get count m ppipfilteritems const sip filter malloc sizeof m ppipfilteritems m uipfilteritems m ulfilteredips 0 for uint i 0 i m uipfilteritems i const sip filter p filter ipfilter i m ppipfilteritems i p filter m ulfilteredips p filter end p filter start 1 sortip filter items m ipfilter set item count m uipfilteritems set dlg item text idc total ipfilter get formatedu int m uipfilteritems set dlg item text idc total ips get formatedu int m ulfilteredips cipfilterdlg initipfilters cwaitcursor curwait m_uipfilteritems m_ppipfilteritems m_ppipfilteritems cipfilterarray theapp getipfilter m_uipfilteritems getcount m_ppipfilteritems sipfilter m_ppipfilteritems m_uipfilteritems m_ulfilteredips m_uipfilteritems sipfilter pfilter m_ppipfilteritems pfilter m_ulfilteredips pfilter pfilter sortipfilteritems m_ipfilter setitemcount m_uipfilteritems setdlgitemtext idc_total_ipfilter getformateduint m_uipfilteritems setdlgitemtext idc_total_ips getformateduint m_ulfilteredips bool cip filter dlg on init dialog c resizable dialog on init dialog init window styles this add anchor idc ipfilter top left bottom right add anchor idc total ipfilter label bottom left add anchor idc total ipfilter bottom left add anchor idc total ips label bottom left add anchor idc total ips bottom left add anchor idc copy bottom right add anchor idc remove bottom right add anchor idc append bottom right add anchor idc save bottom right add anchor idok bottom right enable save restore pref ini section assert m ipfilter get style lvs ownerdata m ipfilter send message ccm setunicodeformat true m ipfilter set extended style lvs ex fullrowselect lvs ex gridlines m ipfilter enable hdr ctrl sort bitmaps m ipfilter read column stats arrsize acolumns acolumns m ipfilter create columns arrsize acolumns acolumns m ipfilter init column orders arrsize acolumns acolumns m ipfilter update sort column arrsize acolumns acolumns set icon m icodlg the app load icon t ip filter false initip filters m pmenuipfilter new c menu if m pmenuipfilter create popup menu m pmenuipfilter append menu mf enabled mf string mp copyselected get res string ids copy m pmenuipfilter append menu mf enabled mf string mp remove get res string ids remove m pmenuipfilter append menu mf separator m pmenuipfilter append menu mf enabled mf string mp selectall get res string ids selectall m pmenuipfilter append menu mf separator m pmenuipfilter append menu mf enabled mf string mp find get res string ids find m ipfilter m pmenu m pmenuipfilter m ipfilter m pparent this localize set window text get res string ids ipfilter set dlg item text idc staticiplabel get res string ids ip rules set dlg item text idc total ipfilter label get res string ids total ipfilter label set dlg item text idc total ips label get res string ids total ips label set dlg item text idc copy get res string ids copy set dlg item text idc remove get res string ids deleteselected set dlg item text idc append get res string ids append set dlg item text idc save get res string ids save set dlg item text idok get res string ids fd close return true return true unless you set the focus to a control exception ocx property pages should return false cipfilterdlg oninitdialog cresizabledialog oninitdialog initwindowstyles addanchor idc_ipfilter top_left bottom_right addanchor idc_total_ipfilter_label bottom_left addanchor idc_total_ipfilter bottom_left addanchor idc_total_ips_label bottom_left addanchor idc_total_ips bottom_left addanchor idc_copy bottom_right addanchor idc_remove bottom_right addanchor idc_append bottom_right addanchor idc_save bottom_right addanchor bottom_right enablesaverestore pref_ini_section m_ipfilter getstyle lvs_ownerdata m_ipfilter sendmessage ccm_setunicodeformat m_ipfilter setextendedstyle lvs_ex_fullrowselect lvs_ex_gridlines m_ipfilter enablehdrctrlsortbitmaps m_ipfilter readcolumnstats _acolumns _acolumns m_ipfilter createcolumns _acolumns _acolumns m_ipfilter initcolumnorders _acolumns _acolumns m_ipfilter updatesortcolumn _acolumns _acolumns seticon m_icodlg theapp loadicon _t ipfilter initipfilters m_pmenuipfilter cmenu m_pmenuipfilter createpopupmenu m_pmenuipfilter appendmenu mf_enabled mf_string mp_copyselected getresstring ids_copy m_pmenuipfilter appendmenu mf_enabled mf_string mp_remove getresstring ids_remove m_pmenuipfilter appendmenu mf_separator m_pmenuipfilter appendmenu mf_enabled mf_string mp_selectall getresstring ids_selectall m_pmenuipfilter appendmenu mf_separator m_pmenuipfilter appendmenu mf_enabled mf_string mp_find getresstring ids_find m_ipfilter m_pmenu m_pmenuipfilter m_ipfilter m_pparent setwindowtext getresstring ids_ipfilter setdlgitemtext idc_staticiplabel getresstring ids_ip_rules setdlgitemtext idc_total_ipfilter_label getresstring ids_total_ipfilter_label setdlgitemtext idc_total_ips_label getresstring ids_total_ips_label setdlgitemtext idc_copy getresstring ids_copy setdlgitemtext idc_remove getresstring ids_deleteselected setdlgitemtext idc_append getresstring ids_append setdlgitemtext idc_save getresstring ids_save setdlgitemtext getresstring ids_fd_close void cip filter dlg do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc ipfilter m ipfilter cipfilterdlg dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_ipfilter m_ipfilter void cip filter dlg on destroy m ipfilter write column stats arrsize acolumns acolumns c resizable dialog on destroy cipfilterdlg ondestroy m_ipfilter writecolumnstats _acolumns _acolumns cresizabledialog ondestroy void cip filter dlg on lvn column clickip filter nmhdr pnmhdr lresult p result lpnmlistview pnmlv reinterpret cast lpnmlistview pnmhdr m ipfilter update sort order pnmlv arrsize acolumns acolumns sortip filter items m ipfilter update 1 p result 0 cipfilterdlg onlvncolumnclickipfilter presult reinterpret_cast m_ipfilter updatesortorder _acolumns _acolumns sortipfilteritems m_ipfilter presult void cip filter dlg on lvn key downip filter nmhdr pnmhdr lresult p result lpnmlvkeydown plv key dow reinterpret cast lpnmlvkeydown pnmhdr if plv key dow wv key vk delete on deleteip filter else if plv key dow wv key c get key state vk control 0x8000 on copyip filter p result 0 cipfilterdlg onlvnkeydownipfilter presult plvkeydow reinterpret_cast plvkeydow wvkey vk_delete ondeleteipfilter plvkeydow wvkey getkeystate vk_control oncopyipfilter presult void cip filter dlg on bn clicked append c string str file path do not localize that string if dialog browse file str file path t all ip filter files ipfilter dat ip prefix p2b p2p p2p txt zip gz rar ipfilter dat ip prefix p2b p2p p2p txt zip gz rar e mule ip filter files ipfilter dat ip prefix ipfilter dat ip prefix peer guardian files p2b p2p p2p txt p2b p2p p2p txt text files txt txt zip files zip gz zip gz rar files rar rar all files c wait cursor cur wait tchar sz ext max ext tsplitpath str file path null null null sz ext tcslwr sz ext bool b is archive file tcscmp sz ext t zip 0 tcscmp sz ext t rar 0 tcscmp sz ext t gz 0 bool b extracted archive false c string str temp unzip file path if tcscmp sz ext t zip 0 czip file zip if zip open str file path czip file file zfile zip get file t guarding p2p if zfile null zfile zip get file t ipfilter dat if zfile tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer if zfile extract str temp unzip file path str file path str temp unzip file path b extracted archive true else c string str error str error format t failed to extract ip filter file from zip file s str file path afx message box str error mb iconerror else c string str error str error format t failed to find ip filter file guarding p2p or ipfilter dat in zip file s str file path afx message box str error mb iconerror zip close else c string str error str error format t failed to open file s r n r n invalid file format str file path afx message box str error mb iconerror else if tcscmp sz ext t rar 0 crar file rar if rar open str file path c string str file if rar get next file str file str file compare no case t ipfilter dat 0 str file compare no case t guarding p2p 0 tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer if rar extract str temp unzip file path str file path str temp unzip file path b extracted archive true else c string str error str error format t failed to extract ip filter file from rar file s str file path afx message box str error mb iconerror else c string str error str error format t failed to find ip filter file guarding p2p or ipfilter dat in rar file s str file path afx message box str error mb iconerror rar close else c string str error str error format t failed to open file s r n r n invalid file format r n r n download latest version of unrar dll from http www rarlab com and copy unrar dll into e mule installation folder str file path afx message box str error mb iconerror else if tcscmp sz ext t gz 0 cgzip file gz if gz open str file path tmakepath str temp unzip file path get buffer max path null the prefs get config dir dflt ipfilter filename t unzip tmp str temp unzip file path release buffer add filename and extension of uncompressed file to temporary file c string str uncompressed file name gz get uncompressed file name if str uncompressed file name is empty str temp unzip file path t str temp unzip file path str uncompressed file name if gz extract str temp unzip file path str file path str temp unzip file path b extracted archive true gz close else c string str error str error format t failed to open file s r n r n invalid file format str file path afx message box str error mb iconerror if b is archive file b extracted archive the app ipfilter add from file str file path true initip filters m ipfilter update 1 if str temp unzip file path is empty verify tremove str temp unzip file path 0 cipfilterdlg onbnclickedappend cstring strfilepath dialogbrowsefile strfilepath _t emule cwaitcursor curwait szext _max_ext _tsplitpath strfilepath szext _tcslwr szext bisarchivefile _tcscmp szext _t _tcscmp szext _t _tcscmp szext _t bextractedarchive cstring strtempunzipfilepath _tcscmp szext _t czipfile strfilepath czipfile getfile _t getfile _t _tmakepath strtempunzipfilepath getbuffer max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer strtempunzipfilepath strfilepath strtempunzipfilepath bextractedarchive cstring strerror strerror _t strfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t strfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t ninvalid strfilepath afxmessagebox strerror mb_iconerror _tcscmp szext _t crarfile strfilepath cstring strfile getnextfile strfile strfile comparenocase _t strfile comparenocase _t _tmakepath strtempunzipfilepath getbuffer max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer strtempunzipfilepath strfilepath strtempunzipfilepath bextractedarchive cstring strerror strerror _t strfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t strfilepath afxmessagebox strerror mb_iconerror cstring strerror strerror _t ninvalid ndownload emule strfilepath afxmessagebox strerror mb_iconerror _tcscmp szext _t cgzipfile strfilepath _tmakepath strtempunzipfilepath getbuffer max_path theprefs getconfigdir dflt_ipfilter_filename _t strtempunzipfilepath releasebuffer cstring struncompressedfilename getuncompressedfilename struncompressedfilename isempty strtempunzipfilepath _t strtempunzipfilepath struncompressedfilename strtempunzipfilepath strfilepath strtempunzipfilepath bextractedarchive cstring strerror strerror _t ninvalid strfilepath afxmessagebox strerror mb_iconerror bisarchivefile bextractedarchive theapp addfromfile strfilepath initipfilters m_ipfilter strtempunzipfilepath isempty _tremove strtempunzipfilepath void cip filter dlg on bn clicked copy c wait cursor cur wait int i selected 0 c string str data position pos m ipfilter get first selected item position while pos int i item m ipfilter get next selected item pos if str data is empty str data t r n str data append format t 15s 15s hits 5s s m ipfilter get item text i item ipfilter col start m ipfilter get item text i item ipfilter col end m ipfilter get item text i item ipfilter col hits m ipfilter get item text i item ipfilter col desc i selected if str data is empty if i selected 1 str data t r n the app copy text to clipboard str data cipfilterdlg onbnclickedcopy cwaitcursor curwait iselected cstring strdata m_ipfilter getfirstselecteditemposition iitem m_ipfilter getnextselecteditem strdata isempty strdata _t strdata appendformat _t m_ipfilter getitemtext iitem ipfilter_col_start m_ipfilter getitemtext iitem ipfilter_col_end m_ipfilter getitemtext iitem ipfilter_col_hits m_ipfilter getitemtext iitem ipfilter_col_desc iselected strdata isempty iselected strdata _t theapp copytexttoclipboard strdata void cip filter dlg on bn clicked delete if m ipfilter get selected count 0 return if afx message box get res string ids deleteipfilters mb yesnocancel idyes return c wait cursor cur wait if m ipfilter get selected count m uipfilteritems the app ipfilter remove allip filters the app ipfilter set modified m uipfilteritems 0 free m ppipfilteritems m ppipfilteritems null m ipfilter set item count m uipfilteritems m ulfilteredips 0 else cu int array a items position pos m ipfilter get first selected item position while pos int i item m ipfilter get next selected item pos const sip filter p filter m ppipfilteritems i item if p filter ulong ulip range p filter end p filter start 1 if the app ipfilter removeip filter p filter the app ipfilter set modified a items add i item m ulfilteredips ulip range m ipfilter set redraw false for int i a items get count 1 i 0 i m ipfilter delete item a items i if a items get count 0 int i next sel item a items 0 if i next sel item m ipfilter get item count i next sel item if i next sel item 0 m ipfilter set item state i next sel item lvis selected lvis focused lvis selected lvis focused m ipfilter set selection mark i next sel item m ipfilter set redraw assert m uipfilteritems uint m ipfilter get item count set dlg item text idc total ipfilter get formatedu int m ipfilter get item count set dlg item text idc total ips get formatedu int m ulfilteredips cipfilterdlg onbnclickeddelete m_ipfilter getselectedcount afxmessagebox getresstring ids_deleteipfilters mb_yesnocancel cwaitcursor curwait m_ipfilter getselectedcount m_uipfilteritems theapp removeallipfilters theapp setmodified m_uipfilteritems m_ppipfilteritems m_ppipfilteritems m_ipfilter setitemcount m_uipfilteritems m_ulfilteredips cuintarray aitems m_ipfilter getfirstselecteditemposition iitem m_ipfilter getnextselecteditem sipfilter pfilter m_ppipfilteritems iitem pfilter uliprange pfilter pfilter theapp removeipfilter pfilter theapp setmodified aitems iitem m_ulfilteredips uliprange m_ipfilter setredraw aitems getcount m_ipfilter deleteitem aitems aitems getcount inextselitem aitems inextselitem m_ipfilter getitemcount inextselitem inextselitem m_ipfilter setitemstate inextselitem lvis_selected lvis_focused lvis_selected lvis_focused m_ipfilter setselectionmark inextselitem m_ipfilter setredraw m_uipfilteritems m_ipfilter getitemcount setdlgitemtext idc_total_ipfilter getformateduint m_ipfilter getitemcount setdlgitemtext idc_total_ips getformateduint m_ulfilteredips void cip filter dlg on bn clicked save c wait cursor cur wait try the app ipfilter save to default file catch c string err afx message box err mb iconerror cipfilterdlg onbnclickedsave cwaitcursor curwait theapp savetodefaultfile cstring afxmessagebox mb_iconerror void cip filter dlg on copyip filter on bn clicked copy cipfilterdlg oncopyipfilter onbnclickedcopy void cip filter dlg on deleteip filter on bn clicked delete cipfilterdlg ondeleteipfilter onbnclickeddelete void cip filter dlg on select allip filter m ipfilter select all items cipfilterdlg onselectallipfilter m_ipfilter selectallitems void cip filter dlg on find m ipfilter on find start cipfilterdlg onfind m_ipfilter onfindstart void cip filter dlg on lvn getdispinfo ipfilter nmhdr pnmhdr lresult p result nmlvdispinfo p disp info reinterpret cast nmlvdispinfo pnmhdr if p disp info item mask lvif text have to check that flag switch p disp info item i sub item case ipfilter col start if p disp info item cch text max 0 tcsncpy p disp info item psz text ipstr htonl m ppipfilteritems p disp info item i item start p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break case ipfilter col end if p disp info item cch text max 0 tcsncpy p disp info item psz text ipstr htonl m ppipfilteritems p disp info item i item end p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break case ipfilter col level if p disp info item cch text max 0 tcsncpy p disp info item psz text itot m ppipfilteritems p disp info item i item level p disp info item psz text 10 p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break case ipfilter col hits if p disp info item cch text max 0 tcsncpy p disp info item psz text itot m ppipfilteritems p disp info item i item hits p disp info item psz text 10 p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break case ipfilter col desc if p disp info item cch text max 0 uses conversion tcsncpy p disp info item psz text a2t m ppipfilteritems p disp info item i item desc p disp info item cch text max p disp info item psz text p disp info item cch text max 1 t 0 break p result 0 cipfilterdlg onlvngetdispinfoipfilter presult pdispinfo reinterpret_cast pdispinfo lvif_text pdispinfo isubitem ipfilter_col_start pdispinfo cchtextmax _tcsncpy pdispinfo psztext m_ppipfilteritems pdispinfo iitem pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t ipfilter_col_end pdispinfo cchtextmax _tcsncpy pdispinfo psztext m_ppipfilteritems pdispinfo iitem pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t ipfilter_col_level pdispinfo cchtextmax _tcsncpy pdispinfo psztext _itot m_ppipfilteritems pdispinfo iitem pdispinfo psztext pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t ipfilter_col_hits pdispinfo cchtextmax _tcsncpy pdispinfo psztext _itot m_ppipfilteritems pdispinfo iitem pdispinfo psztext pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t ipfilter_col_desc pdispinfo cchtextmax uses_conversion _tcsncpy pdispinfo psztext m_ppipfilteritems pdispinfo iitem pdispinfo cchtextmax pdispinfo psztext pdispinfo cchtextmax _t presult void cip filter dlg on lvn deleteitem ipfilter nmhdr pnmhdr lresult p result lpnmlistview pnmlv reinterpret cast lpnmlistview pnmhdr assert m uipfilteritems 0 if m uipfilteritems 0 assert uint pnmlv i item m uipfilteritems if uint pnmlv i item m uipfilteritems 1 memmove m ppipfilteritems pnmlv i item m ppipfilteritems pnmlv i item 1 m uipfilteritems pnmlv i item 1 sizeof m ppipfilteritems m uipfilteritems m ppipfilteritems const sip filter realloc m ppipfilteritems sizeof m ppipfilteritems m uipfilteritems p result 0 cipfilterdlg onlvndeleteitemipfilter presult reinterpret_cast m_uipfilteritems m_uipfilteritems iitem m_uipfilteritems iitem m_uipfilteritems m_ppipfilteritems iitem m_ppipfilteritems iitem m_uipfilteritems iitem m_ppipfilteritems m_uipfilteritems m_ppipfilteritems sipfilter m_ppipfilteritems m_ppipfilteritems m_uipfilteritems presult void c mule browser control site init internet security zone c string str zone afx get app get profile string t e mule t internet security zone t untrusted if str zone compare no case t local machine 0 m eurlzone urlzone local machine else if str zone compare no case t intranet 0 m eurlzone urlzone intranet else if str zone compare no case t trusted 0 m eurlzone urlzone trusted else if str zone compare no case t internet 0 m eurlzone urlzone internet else assert str zone compare no case t untrusted 0 m eurlzone urlzone untrusted cmulebrowsercontrolsite initinternetsecurityzone cstring strzone afxgetapp getprofilestring _t emule _t internetsecurityzone _t strzone comparenocase _t localmachine m_eurlzone urlzone_local_machine strzone comparenocase _t m_eurlzone urlzone_intranet strzone comparenocase _t m_eurlzone urlzone_trusted strzone comparenocase _t m_eurlzone urlzone_internet strzone comparenocase _t m_eurlzone urlzone_untrusted stdmethodimp ulong c mule browser control site x internet security manager add ref method prologue c mule browser control site internet security manager return p this external add ref stdmethodimp_ cmulebrowsercontrolsite xinternetsecuritymanager addref method_prologue cmulebrowsercontrolsite internetsecuritymanager pthis externaladdref stdmethodimp ulong c mule browser control site x internet security manager release method prologue c mule browser control site internet security manager return p this external release stdmethodimp_ cmulebrowsercontrolsite xinternetsecuritymanager method_prologue cmulebrowsercontrolsite internetsecuritymanager pthis externalrelease stdmethodimp c mule browser control site x internet security manager query interface refiid riid void ppv obj method prologue c mule browser control site internet security manager return hresult p this external query interface riid ppv obj cmulebrowsercontrolsite xinternetsecuritymanager queryinterface ppvobj method_prologue cmulebrowsercontrolsite internetsecuritymanager pthis externalqueryinterface ppvobj stdmethodimp c mule browser control site x internet security manager set security site i internet security mgr site p site method prologue c mule browser control site internet security manager trace t hs n set security site return inet e default action cmulebrowsercontrolsite xinternetsecuritymanager setsecuritysite iinternetsecuritymgrsite psite method_prologue cmulebrowsercontrolsite internetsecuritymanager _t setsecuritysite inet_e_default_action stdmethodimp c mule browser control site x internet security manager get security site i internet security mgr site pp site method prologue c mule browser control site internet security manager trace t hs n get security site return inet e default action cmulebrowsercontrolsite xinternetsecuritymanager getsecuritysite iinternetsecuritymgrsite ppsite method_prologue cmulebrowsercontrolsite internetsecuritymanager _t getsecuritysite inet_e_default_action dword dw flags unreferenced parameter pwsz url unreferenced parameter dw flags method prologue c mule browser control site internet security manager trace t hs url ls zone d flags 0x x n map url to zone pwsz url pdw zone dw flags if pdw zone null pdw zone dword p this m eurlzone return s ok return inet e default action dwflags unreferenced_parameter pwszurl unreferenced_parameter dwflags method_prologue cmulebrowsercontrolsite internetsecuritymanager _t mapurltozone pwszurl pdwzone dwflags pdwzone pdwzone pthis m_eurlzone s_ok inet_e_default_action dword dw reserved unreferenced parameter pwsz url unreferenced parameter dw reserved method prologue c mule browser control site internet security manager trace t hs url ls reserved u n get security id pwsz url dw reserved return inet e default action dwreserved unreferenced_parameter pwszurl unreferenced_parameter dwreserved method_prologue cmulebrowsercontrolsite internetsecuritymanager _t getsecurityid pwszurl dwreserved inet_e_default_action dword dw flags dword dw reserved unreferenced parameter pwsz url unreferenced parameter dw action unreferenced parameter dw flags unreferenced parameter dw reserved method prologue c mule browser control site internet security manager trace t hs url ls action u flags 0x x reserved u n process url action pwsz url dw action dw flags dw reserved if 0 dword dw policy urlpolicy disallow if cb policy sizeof dword dword p policy dw policy return s ok return s false else use the policy for the zone which was specified with map url to zone if that particular policy setting is specified as ask user the control will open a message box return inet e default action endif dwflags dwreserved unreferenced_parameter pwszurl unreferenced_parameter dwaction unreferenced_parameter dwflags unreferenced_parameter dwreserved method_prologue cmulebrowsercontrolsite internetsecuritymanager _t processurlaction pwszurl dwaction dwflags dwreserved dwpolicy urlpolicy_disallow cbpolicy ppolicy dwpolicy s_ok s_false mapurltozone inet_e_default_action dword dw reserved unreferenced parameter pwsz url method prologue c mule browser control site internet security manager trace t hs url ls n query custom policy pwsz url return inet e default action dwreserved unreferenced_parameter pwszurl method_prologue cmulebrowsercontrolsite internetsecuritymanager _t querycustompolicy pwszurl inet_e_default_action dword dw flags unreferenced parameter dw zone unreferenced parameter lpsz pattern unreferenced parameter dw flags method prologue c mule browser control site internet security manager trace t hs zone d pattern ls flags 0x x n set zone mapping dw zone lpsz pattern dw flags return inet e default action dwflags unreferenced_parameter dwzone unreferenced_parameter lpszpattern unreferenced_parameter dwflags method_prologue cmulebrowsercontrolsite internetsecuritymanager _t setzonemapping dwzone lpszpattern dwflags inet_e_default_action dword dw flags unreferenced parameter dw zone unreferenced parameter dw flags method prologue c mule browser control site internet security manager trace t hs zone d flags 0x s n get zone mappings dw zone dw flags return inet e default action dwflags unreferenced_parameter dwzone unreferenced_parameter dwflags method_prologue cmulebrowsercontrolsite internetsecuritymanager _t getzonemappings dwzone dwflags inet_e_default_action stdmethodimp ulong c mule browser control site x service provider add ref method prologue c mule browser control site service provider return p this external add ref stdmethodimp_ cmulebrowsercontrolsite xserviceprovider addref method_prologue cmulebrowsercontrolsite serviceprovider pthis externaladdref stdmethodimp ulong c mule browser control site x service provider release method prologue c mule browser control site service provider return p this external release stdmethodimp_ cmulebrowsercontrolsite xserviceprovider method_prologue cmulebrowsercontrolsite serviceprovider pthis externalrelease stdmethodimp c mule browser control site x service provider query interface refiid riid void ppv obj method prologue c mule browser control site service provider return hresult p this external query interface riid ppv obj cmulebrowsercontrolsite xserviceprovider queryinterface ppvobj method_prologue cmulebrowsercontrolsite serviceprovider pthis externalqueryinterface ppvobj stdmethodimp c mule browser control site x service provider query service refguid guid service refiid riid void ppv object method prologue c mule browser control site service provider dumpiid guid service t guid service dumpiid riid t riid if guid service sid sinternetsecuritymanager riid iid iinternetsecuritymanager trace t hs n query service return hresult p this external query interface riid ppv object ppv object null return e nointerface cmulebrowsercontrolsite xserviceprovider queryservice guidservice ppvobject method_prologue cmulebrowsercontrolsite serviceprovider guidservice _t guidservice _t guidservice sid_sinternetsecuritymanager iid_iinternetsecuritymanager _t queryservice pthis externalqueryinterface ppvobject ppvobject e_nointerface c prepared hyper text c prepared hyper text const c string s text prepare text s text cpreparedhypertext cpreparedhypertext cstring stext preparetext stext c prepared hyper text c prepared hyper text const c prepared hyper text src m stext src m stext m links assign src m links begin src m links end cpreparedhypertext cpreparedhypertext cpreparedhypertext m_stext m_stext m_links m_links m_links void c prepared hyper text clear m stext empty m links erase m links begin m links end cpreparedhypertext m_stext m_links m_links m_links void c prepared hyper text set text const c string s text clear prepare text s text cpreparedhypertext settext cstring stext preparetext stext void c prepared hyper text append text const c string s text int len m stext get length top the original code didn t check to see if the buffer was full bool flag true if len 60000 m stext m stext right 50000 int shift len m stext get length while flag true c hyper link test m links front if m links empty if test begin shift m links pop front else flag false else flag false flag true while flag true c key word test m keywords front if m keywords empty if test begin shift m keywords pop front else flag false else flag false len m stext get length c hyper link ltest m links front int litest ltest begin shift c key word wtest m keywords front int witest wtest begin shift flag true while flag true m links empty c hyper link temp m links front c hyper link backup temp backup set begin backup begin shift backup set end backup end shift m links pop front m links push back backup if c hyper link m links front begin uint litest flag false flag true while flag true m keywords empty c key word temp m keywords front c key word backup temp begin shift temp end shift temp color m keywords pop front m keywords push back backup if c key word m keywords front begin uint witest flag false bottom may not be the nicest code but it works c prepared hyper text ht s text m stext s text for std list c hyper link iterator it ht m links begin it ht m links end it c hyper link hl it hl m ibegin len hl m iend len m links push back hl cpreparedhypertext appendtext cstring stext m_stext getlength m_stext m_stext m_stext getlength chyperlink m_links m_links m_links pop_front ckeyword m_keywords m_keywords m_keywords pop_front m_stext getlength chyperlink m_links ckeyword m_keywords m_links chyperlink m_links chyperlink setbegin setend m_links pop_front m_links push_back chyperlink m_links m_keywords ckeyword m_keywords ckeyword m_keywords pop_front m_keywords push_back ckeyword m_keywords cpreparedhypertext stext m_stext stext chyperlink m_links m_links chyperlink m_ibegin m_iend m_links push_back void c prepared hyper text append hyper link const c string s text const c string s title const c string s command const c string s directory if s text get length s command get length return int len m stext get length top the original code didn t check to see if the buffer was full bool flag true if len 60000 m stext m stext right 50000 int shift len m stext get length while flag true c hyper link test m links front if m links empty if test begin shift m links pop front else flag false else flag false flag true while flag true c key word test m keywords front if m keywords empty if test begin shift m keywords pop front else flag false else flag false len m stext get length c hyper link ltest m links front int litest ltest begin shift c key word wtest m keywords front int witest wtest begin shift flag true while flag true m links empty c hyper link temp m links front c hyper link backup temp backup set begin backup begin shift backup set end backup end shift m links pop front m links push back backup if c hyper link m links front begin uint litest flag false flag true while flag true m keywords empty c key word temp m keywords front c key word backup temp begin shift temp end shift temp color m keywords pop front m keywords push back backup if c key word m keywords front begin uint witest flag false bottom may not be the nicest code but it works m stext s text m links push back c hyper link len len s text get length 1 s title s command s directory cpreparedhypertext appendhyperlink cstring stext cstring stitle cstring scommand cstring sdirectory stext getlength scommand getlength m_stext getlength m_stext m_stext m_stext getlength chyperlink m_links m_links m_links pop_front ckeyword m_keywords m_keywords m_keywords pop_front m_stext getlength chyperlink m_links ckeyword m_keywords m_links chyperlink m_links chyperlink setbegin setend m_links pop_front m_links push_back chyperlink m_links m_keywords ckeyword m_keywords ckeyword m_keywords pop_front m_keywords push_back ckeyword m_keywords m_stext stext m_links push_back chyperlink stext getlength stitle scommand sdirectory void c prepared hyper text append hyper link const c string s text const c string s title hwnd h wnd uint u msg wparam w param lparam l param if s text get length return int len m stext get length top the original code didn t check to see if the buffer was full bool flag true if len 60000 m stext m stext right 50000 int shift len m stext get length while flag true c hyper link test m links front if m links empty if test begin shift m links pop front else flag false else flag false flag true while flag true c key word test m keywords front if m keywords empty if test begin shift m keywords pop front else flag false else flag false len m stext get length c hyper link ltest m links front int litest ltest begin shift c key word wtest m keywords front int witest wtest begin shift flag true while flag true m links empty c hyper link temp m links front c hyper link backup temp backup set begin backup begin shift backup set end backup end shift m links pop front m links push back backup if c hyper link m links front begin uint litest flag false flag true while flag true m keywords empty c key word temp m keywords front c key word backup temp begin shift temp end shift temp color m keywords pop front m keywords push back backup if c key word m keywords front begin uint witest flag false bottom may not be the nicest code but it works m stext s text m links push back c hyper link len len s text get length 1 s title h wnd u msg w param l param cpreparedhypertext appendhyperlink cstring stext cstring stitle hwnd umsg wparam lparam stext getlength m_stext getlength m_stext m_stext m_stext getlength chyperlink m_links m_links m_links pop_front ckeyword m_keywords m_keywords m_keywords pop_front m_stext getlength chyperlink m_links ckeyword m_keywords m_links chyperlink m_links chyperlink setbegin setend m_links pop_front m_links push_back chyperlink m_links m_keywords ckeyword m_keywords ckeyword m_keywords pop_front m_keywords push_back ckeyword m_keywords m_stext stext m_links push_back chyperlink stext getlength stitle hwnd umsg wparam lparam void c prepared hyper text append key word const c string s text colorref i color if s text get length return int len m stext get length top the original code didn t check to see if the buffer was full bool flag true if len 60000 m stext m stext right 50000 int shift len m stext get length while flag true c hyper link test m links front if m links empty if test begin shift m links pop front else flag false else flag false flag true while flag true c key word test m keywords front if m keywords empty if test begin shift m keywords pop front else flag false else flag false len m stext get length c hyper link ltest m links front int litest ltest begin shift c key word wtest m keywords front int witest wtest begin shift flag true while flag true m links empty c hyper link temp m links front c hyper link backup temp backup set begin backup begin shift backup set end backup end shift m links pop front m links push back backup if c hyper link m links front begin uint litest flag false flag true while flag true m keywords empty c key word temp m keywords front c key word backup temp begin shift temp end shift temp color m keywords pop front m keywords push back backup if c key word m keywords front begin uint witest flag false bottom may not be the nicest code but it works m stext s text m keywords push back c key word len len s text get length 1 i color cpreparedhypertext appendkeyword cstring stext icolor stext getlength m_stext getlength m_stext m_stext m_stext getlength chyperlink m_links m_links m_links pop_front ckeyword m_keywords m_keywords m_keywords pop_front m_stext getlength chyperlink m_links ckeyword m_keywords m_links chyperlink m_links chyperlink setbegin setend m_links pop_front m_links push_back chyperlink m_links m_keywords ckeyword m_keywords ckeyword m_keywords pop_front m_keywords push_back ckeyword m_keywords m_stext stext m_keywords push_back ckeyword stext getlength icolor void c prepared hyper text remove last sign c string s link int len s link get length if len 0 tchar c s link len 1 switch c case t case t case t case t case t case t case t case t case t case t case t s link delete len 1 1 break cpreparedhypertext removelastsign cstring slink slink getlength slink _t _t _t _t _t _t _t _t _t _t _t slink void c prepared hyper text prepare text const c string s text m stext s text m links clear enum unknown space http0 http http1 http2 http3 http4 http5 http6 ftp0 ftp ftp1 ftp2 ftp3 ftp4 ftp5 ftp ftp www0 www www1 www2 www3 mailto0 mailto mailto1 mailto2 mailto3 mailto4 mailto5 mailto6 mail xxx yyy ed2k0 ed2k ed2k1 ed2k2 ed2k3 ed2k4 ed2k5 ed2k6 state space int word pos 0 tchar sz 2 tchar c sz 0 sz 1 0 int last m stext get length 1 for int i 0 i last i c m stext i tcslwr sz switch state case unknown if tspace c state space else if c t word pos i state mail break case space word pos i switch c case t h state http0 break case t f state ftp0 break case t w state www0 break case t m state mailto0 break case t e state ed2k0 break default if tspace c state unknown break http case http0 if c t t state http1 else if tspace c state space else state unknown break case http1 if c t t state http2 else if tspace c state space else state unknown break case http2 if c t p state http3 else if tspace c state space else state unknown break case http3 if c t state http4 else if tspace c state space else state unknown break case http4 if c t state http5 else if tspace c state space else state unknown break case http5 if c t state http6 else if tspace c state space else state unknown break case http6 if tspace c i last int len i last i word pos 1 i word pos c string s m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break ed2k case ed2k0 if c t d state ed2k1 else if tspace c state space else state unknown break case ed2k1 if c t 2 state ed2k2 else if tspace c state space else state unknown break case ed2k2 if c t k state ed2k3 else if tspace c state space else state unknown break case ed2k3 if c t state ed2k4 else if tspace c state space else state unknown break case ed2k4 if c t state ed2k5 else if tspace c state space else state unknown break case ed2k5 if c t state ed2k6 else if tspace c state space else state unknown break case ed2k6 if tspace c i last int len i last i word pos 1 i word pos c string s m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break ftp case ftp0 if c t t state ftp1 else if tspace c state space else state unknown break case ftp1 if c t p state ftp2 else if tspace c state space else state unknown break case ftp2 if c t state ftp3 else if c t state ftp else if tspace c state space else state unknown break case ftp3 if c t state ftp4 else if tspace c state space else state unknown break case ftp4 if c t state ftp5 else if tspace c state space else state unknown break case ftp if tspace c i last int len i last i word pos 1 i word pos c string s c string t ftp m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break case ftp5 if tspace c i last int len i last i word pos 1 i word pos c string s m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break www case www0 if c t w state www1 else if tspace c state space else state unknown break case www1 if c t w state www2 else if tspace c state space else state unknown break case www2 if c t state www3 else if tspace c state space else state unknown break case www3 if tspace c i last int len i last i word pos 1 i word pos c string s c string t http m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break mailto case mailto0 if c t a state mailto1 else if tspace c state space else state unknown break case mailto1 if c t i state mailto2 else if tspace c state space else state unknown break case mailto2 if c t l state mailto3 else if tspace c state space else state unknown break case mailto3 if c t t state mailto4 else if tspace c state space else state unknown break case mailto4 if c t o state mailto5 else if tspace c state space else state unknown break case mailto5 if c t state mailto6 else if tspace c state space else state unknown break case mailto6 if tspace c i last int len i last i word pos 1 i word pos c string s m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break mailto case mail if tspace c i last int len i last i word pos 1 i word pos c string s c string t mailto m stext mid word pos len remove last sign s m links push back c hyper link word pos word pos len 1 s s lpctstr null state space break m links sort cpreparedhypertext preparetext cstring stext m_stext stext m_links wordpos m_stext getlength m_stext _tcslwr _t wordpos wordpos _t _t _t _t _t _t _t _t _t _t _t wordpos wordpos cstring m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos _t _t _t _t _t _t wordpos wordpos cstring m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos _t _t _t _t _t _t wordpos wordpos cstring cstring _t m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos wordpos wordpos cstring m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos _t _t _t wordpos wordpos cstring cstring _t m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos _t _t _t _t _t _t wordpos wordpos cstring m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos wordpos wordpos cstring cstring _t m_stext wordpos removelastsign m_links push_back chyperlink wordpos wordpos m_links c hyper link c hyper link i a m type lt unknown m ibegin 0 m iend 0 m stitle empty m scommand empty m sdirectory empty m hwnd 0 m umsg 0 m wparam 0 m lparam 0 chyperlink chyperlink i_a m_type lt_unknown m_ibegin m_iend m_stitle m_scommand m_sdirectory m_hwnd m_umsg m_wparam m_lparam c hyper link c hyper link c hyper link int i begin uint16 i end const c string s title const c string s command const c string s directory m type lt shell m ibegin i begin m iend i end m stitle s title m scommand s command m sdirectory s directory i a used for lt message m hwnd 0 m umsg 0 m wparam 0 m lparam 0 chyperlink chyperlink chyperlink ibegin iend cstring stitle cstring scommand cstring sdirectory m_type lt_shell m_ibegin ibegin m_iend iend m_stitle stitle m_scommand scommand m_sdirectory sdirectory i_a lt_message m_hwnd m_umsg m_wparam m_lparam c hyper link c hyper link int i begin uint16 i end const c string s title hwnd h wnd uint u msg wparam w param lparam l param m type lt message m ibegin i begin m iend i end m stitle s title m hwnd h wnd m umsg u msg m wparam w param m lparam l param chyperlink chyperlink ibegin iend cstring stitle hwnd umsg wparam lparam m_type lt_message m_ibegin ibegin m_iend iend m_stitle stitle m_hwnd hwnd m_umsg umsg m_wparam wparam m_lparam lparam i a c hyper link c hyper link const c hyper link src m type src m type m ibegin src m ibegin m iend src m iend m stitle src m stitle m scommand src m scommand m sdirectory src m sdirectory m hwnd src m hwnd m umsg src m umsg m wparam src m wparam m lparam src m lparam i_a chyperlink chyperlink chyperlink m_type m_type m_ibegin m_ibegin m_iend m_iend m_stitle m_stitle m_scommand m_scommand m_sdirectory m_sdirectory m_hwnd m_hwnd m_umsg m_umsg m_wparam m_wparam m_lparam m_lparam void c hyper link execute switch m type case lt shell shell execute null null m scommand null m sdirectory sw showdefault break case lt message post message m hwnd m umsg m wparam m lparam break chyperlink m_type lt_shell shellexecute m_scommand m_sdirectory sw_showdefault lt_message postmessage m_hwnd m_umsg m_wparam m_lparam c key word c key word c key word int i begin uint16 i end colorref icolor color icolor m ibegin i begin m iend i end ckeyword ckeyword ckeyword ibegin iend m_ibegin ibegin m_iend iend c line part info c line part info int i begin uint16 i end c hyper link p hyper link c key word p key word m xbegin i begin m xend i end m phyperlink p hyper link m pkeyword p key word clinepartinfo clinepartinfo ibegin iend chyperlink phyperlink ckeyword pkeyword m_xbegin ibegin m_xend iend m_phyperlink phyperlink m_pkeyword pkeyword c line part info c line part info const c line part info src m xbegin src m xbegin m xend src m xend m phyperlink src m phyperlink m pkeyword src m pkeyword clinepartinfo clinepartinfo clinepartinfo m_xbegin m_xbegin m_xend m_xend m_phyperlink m_phyperlink m_pkeyword m_pkeyword c line info c line info int i begin uint16 i end m ibegin i begin m iend i end clineinfo clineinfo ibegin iend m_ibegin ibegin m_iend iend c line info c line info const c line info src m ibegin src m ibegin m iend src m iend assign src begin src end clineinfo clineinfo clineinfo m_ibegin m_ibegin m_iend m_iend c vis part c vis part const c line part info line part info const c rect rc bounds int i real begin uint16 i real len c vis part p prev c vis part p next c line part info line part info m rcbounds rc bounds m irealbegin i real begin m ireallen i real len m pprev p prev m pnext p next cvispart cvispart clinepartinfo linepartinfo crect rcbounds irealbegin ireallen cvispart pprev cvispart pnext clinepartinfo linepartinfo m_rcbounds rcbounds m_irealbegin irealbegin m_ireallen ireallen m_pprev pprev m_pnext pnext c vis part c vis part const c vis part src c line part info src m rcbounds src m rcbounds m irealbegin src m irealbegin m ireallen src m ireallen m pprev src m pprev m pnext src m pnext cvispart cvispart cvispart clinepartinfo m_rcbounds m_rcbounds m_irealbegin m_irealbegin m_ireallen m_ireallen m_pprev m_pprev m_pnext m_pnext c hyper text ctrl c hyper text ctrl m text standart text vscrollon false m font null m bkcolor rgb 0 0 0 m textcolor rgb 0 0 0 m linkcolor rgb 0 0 0 m hovercolor rgb 0 0 0 m linkcursor null m defaultcursor null vscrollon false m imaxwidth 0 m ilineheight 0 m ilinesheight 0 m bdontupdatesizeinfo false m ivertpos 0 m ihorzpos 0 m pactivepart null m iwheeldelta 0 chypertextctrl chypertextctrl m_text standart_text m_font m_bkcolor m_textcolor m_linkcolor m_hovercolor m_linkcursor m_defaultcursor m_imaxwidth m_ilineheight m_ilinesheight m_bdontupdatesizeinfo m_ivertpos m_ihorzpos m_pactivepart m_iwheeldelta void c hyper text ctrl on mouse move uint n flags c point pt c rect rc client get client rect rc client if pt in rect rc client pt m ilineheight bool b found false uint i pt y m ilineheight if i m vislines size std vector c vis line iterator it m vislines begin i for c vis line iterator jt it begin jt it end jt if pt x jt m rcbounds left pt x jt m rcbounds right if jt m phyperlink null highlight link jt pt b found true if get capture this set capture break if b found restore link if get capture this release capture else release capture chypertextctrl onmousemove nflags cpoint crect rcclient getclientrect rcclient ptinrect rcclient m_ilineheight bfound m_ilineheight m_vislines cvisline m_vislines cvisline m_rcbounds m_rcbounds m_phyperlink highlightlink bfound getcapture setcapture bfound restorelink getcapture releasecapture releasecapture void c hyper text ctrl onl button down uint n flags c point pt c rect rc client get client rect rc client if pt in rect rc client pt m ilineheight bool b found false uint i pt y m ilineheight if i m vislines size std vector c vis line iterator it m vislines begin i for c vis line iterator jt it begin jt it end jt if pt x jt m rcbounds left pt x jt m rcbounds right if jt m phyperlink null jt m phyperlink execute b found true break m tip onl button down n flags pt chypertextctrl onlbuttondown nflags cpoint crect rcclient getclientrect rcclient ptinrect rcclient m_ilineheight bfound m_ilineheight m_vislines cvisline m_vislines cvisline m_rcbounds m_rcbounds m_phyperlink m_phyperlink bfound m_tip onlbuttondown nflags bool c hyper text ctrl on mouse wheel uint n flags short z delta c point pt c rect rc get window rect rc if pt in rect rc pt int i scroll lines system parameters info spi getwheelscrolllines 0 i scroll lines 0 m iwheeldelta z delta if abs m iwheeldelta wheel delta if m iwheeldelta 0 for int i 0 i i scroll lines i post message wm vscroll sb linedown 0 else for int i 0 i i scroll lines i post message wm vscroll sb lineup 0 m iwheeldelta wheel delta return true m tip on mouse wheel n flags z delta pt chypertextctrl onmousewheel nflags zdelta cpoint crect getwindowrect ptinrect iscrolllines systemparametersinfo spi_getwheelscrolllines iscrolllines m_iwheeldelta zdelta m_iwheeldelta wheel_delta m_iwheeldelta iscrolllines postmessage wm_vscroll sb_linedown iscrolllines postmessage wm_vscroll sb_lineup m_iwheeldelta wheel_delta m_tip onmousewheel nflags zdelta lresult c hyper text ctrl on create wparam w param lparam l param lpcreatestruct lp create struct lpcreatestruct l param m imaxwidth 0 m ilinesheight 0 m bdontupdatesizeinfo false m ihorzpos 0 m ivertpos 0 m font the app m fonthypertext set colors load hand cursor m defaultcursor load cursor null idc arrow m pactivepart null m iwheeldelta 0 create a tool tip m tip create this if m tip m tip activate true update fonts return 0 chypertextctrl oncreate wparam lparam lpcreatestruct lparam m_imaxwidth m_ilinesheight m_bdontupdatesizeinfo m_ihorzpos m_ivertpos m_font theapp m_fonthypertext setcolors loadhandcursor m_defaultcursor loadcursor idc_arrow m_pactivepart m_iwheeldelta m_tip m_tip m_tip updatefonts lresult c hyper text ctrl on destroy wparam w param lparam l param if m linkcursor set cursor m defaultcursor verify destroy cursor m linkcursor m linkcursor null return 0 chypertextctrl ondestroy wparam lparam m_linkcursor setcursor m_defaultcursor destroycursor m_linkcursor m_linkcursor lresult c hyper text ctrl on paint wparam w param lparam l param c paintdc dc this device context for painting c font h old font dc select object m font dc set bk color m bkcolor int ypos 0 lpctstr s m text get text c rect rc c rect rc client get client rect rc client rc left dc m ps rc paint left rc right 2 rc top dc m ps rc paint top rc bottom dc m ps rc paint bottom c brush br bk br bk create solid brush m bkcolor dc fill rect rc br bk for std vector c vis line iterator it m vislines begin it m vislines end it int i lastx dc m ps rc paint left for c vis line iterator jt it begin jt it end jt if jt m pkeyword dc set text color jt m pkeyword color else if jt m phyperlink null dc set text color m textcolor else if m pactivepart null m pactivepart m phyperlink jt m phyperlink dc set text color m hovercolor dc select object m hoverfont else dc set text color m linkcolor dc select object m linksfont text out dc jt m rcbounds left jt m rcbounds top s jt m irealbegin jt m ireallen if jt m phyperlink null dc select object m font i lastx jt m rcbounds right rc left i lastx rc right dc m ps rc paint right rc top ypos rc bottom ypos m ilineheight dc fill rect rc br bk ypos m ilineheight rc left dc m ps rc paint left rc right dc m ps rc paint right rc top ypos rc bottom dc m ps rc paint bottom dc fill rect rc br bk dc select object h old font return 0 chypertextctrl onpaint wparam lparam cpaintdc cfont holdfont selectobject m_font setbkcolor m_bkcolor m_text gettext crect crect rcclient getclientrect rcclient m_ps rcpaint m_ps rcpaint m_ps rcpaint cbrush brbk brbk createsolidbrush m_bkcolor fillrect brbk cvisline m_vislines m_vislines ilastx m_ps rcpaint cvisline m_pkeyword settextcolor m_pkeyword m_phyperlink settextcolor m_textcolor m_pactivepart m_pactivepart m_phyperlink m_phyperlink settextcolor m_hovercolor selectobject m_hoverfont settextcolor m_linkcolor selectobject m_linksfont textout m_rcbounds m_rcbounds m_irealbegin m_ireallen m_phyperlink selectobject m_font ilastx m_rcbounds ilastx m_ps rcpaint m_ilineheight fillrect brbk m_ilineheight m_ps rcpaint m_ps rcpaint m_ps rcpaint fillrect brbk selectobject holdfont lresult c hyper text ctrl on size wparam w param lparam l param word cx cy cx loword l param cy hiword l param update size is window visible true return 0 chypertextctrl onsize wparam lparam lparam lparam updatesize iswindowvisible lresult c hyper text ctrl on show window wparam w param lparam l param if true bool w param update size false return 0 chypertextctrl onshowwindow wparam lparam wparam updatesize lresult c hyper text ctrl on set text wparam w param lparam l param m text set text lptstr l param update size is window visible true return true chypertextctrl onsettext wparam lparam m_text settext lparam updatesize iswindowvisible lresult c hyper text ctrl on get text wparam w param lparam l param int bufsize w param lptstr buf lptstr l param if l param null bufsize 0 m text get text is empty return 0 int cpy m text get text get length bufsize 1 bufsize 1 m text get text get length tcsncpy buf m text get text cpy return cpy chypertextctrl ongettext wparam lparam wparam lparam lparam m_text gettext isempty m_text gettext getlength m_text gettext getlength _tcsncpy m_text gettext lresult c hyper text ctrl on set font wparam w param lparam l param m font c font from handle hfont w param update fonts update size loword l param 0 return 0 chypertextctrl onsetfont wparam lparam m_font cfont fromhandle wparam updatefonts updatesize lparam lresult c hyper text ctrl on get font wparam w param lparam l param return lresult m font m hobject chypertextctrl ongetfont wparam lparam m_font m_hobject lresult c hyper text ctrl onh scroll wparam w param lparam l param scrollinfo si si cb size sizeof si si f mask sif all get scroll info sb horz si switch loword w param case sb left si n pos si n min break case sb right si n pos si n max break case sb lineleft if si n pos si n min si n pos 1 break case sb lineright if si n pos si n max si n pos 1 break case sb pageleft if si n pos si n min si n pos si n page if si n pos si n min si n pos si n min break case sb pageright if si n pos si n max si n pos si n page if si n pos si n max si n pos si n max break case sb thumbtrack si n pos si n track pos break if si n max si n min m ihorzpos si n pos 100 si n max si n min set scroll info sb horz si update vis lines invalidate rect null false return true chypertextctrl onhscroll wparam lparam cbsize fmask sif_all getscrollinfo sb_horz wparam sb_left npos nmin sb_right npos nmax sb_lineleft npos nmin npos sb_lineright npos nmax npos sb_pageleft npos nmin npos npage npos nmin npos nmin sb_pageright npos nmax npos npage npos nmax npos nmax sb_thumbtrack npos ntrackpos nmax nmin m_ihorzpos npos nmax nmin setscrollinfo sb_horz updatevislines invalidaterect lresult c hyper text ctrl onv scroll wparam w param lparam l param scrollinfo si si cb size sizeof si si f mask sif all get scroll info sb vert si switch loword w param case sb top si n pos si n min break case sb bottom si n pos si n max break case sb lineup if si n pos si n min si n pos 1 break case sb linedown if si n pos si n max si n pos 1 break case sb pageup if si n pos si n min si n pos si n page if si n pos si n min si n pos si n min break case sb pagedown if si n pos si n max si n pos si n page if si n pos si n max si n pos si n max break case sb thumbtrack si n pos si n track pos break if si n max si n min m ivertpos si n pos 100 si n max si n min set scroll info sb vert si update vis lines invalidate rect null false return true chypertextctrl onvscroll wparam lparam cbsize fmask sif_all getscrollinfo sb_vert wparam sb_top npos nmin sb_bottom npos nmax sb_lineup npos nmin npos sb_linedown npos nmax npos sb_pageup npos nmin npos npage npos nmin npos nmin sb_pagedown npos nmax npos npage npos nmax npos nmax sb_thumbtrack npos ntrackpos nmax nmin m_ivertpos npos nmax nmin setscrollinfo sb_vert updatevislines invalidaterect lresult c hyper text ctrl on capture changed wparam w param lparam l param restore link return 0 chypertextctrl oncapturechanged wparam lparam restorelink bool c hyper text ctrl on erase bkgnd cdc pdc return true chypertextctrl onerasebkgnd void c hyper text ctrl on sys color change adjust colors c wnd on sys color change set colors chypertextctrl onsyscolorchange cwnd onsyscolorchange setcolors operations c prepared hyper text c hyper text ctrl get hyper text return m text cpreparedhypertext chypertextctrl gethypertext m_text void c hyper text ctrl set hyper text c prepared hyper text src bool b invalidate if src m text src else m text standart text update size b invalidate chypertextctrl sethypertext cpreparedhypertext binvalidate m_text m_text standart_text updatesize binvalidate void c hyper text ctrl append text const c string s text bool b invalidate m text append text s text update size b invalidate chypertextctrl appendtext cstring stext binvalidate m_text appendtext stext updatesize binvalidate void c hyper text ctrl append hyper link const c string s text const c string s title const c string s command const c string s directory bool b invalidate m text append hyper link s text s title s command s directory update size b invalidate chypertextctrl appendhyperlink cstring stext cstring stitle cstring scommand cstring sdirectory binvalidate m_text appendhyperlink stext stitle scommand sdirectory updatesize binvalidate void c hyper text ctrl append hyper link const c string s text const c string s title hwnd h wnd uint u msg wparam w param lparam l param bool b invalidate m text append hyper link s text s title h wnd u msg w param l param update size b invalidate chypertextctrl appendhyperlink cstring stext cstring stitle hwnd umsg wparam lparam binvalidate m_text appendhyperlink stext stitle hwnd umsg wparam lparam updatesize binvalidate void c hyper text ctrl append key word const c string s text colorref icolor m text append key word s text icolor update size true chypertextctrl appendkeyword cstring stext m_text appendkeyword stext updatesize void c hyper text ctrl set link color colorref link color bool b invalidate m linkcolor link color if b invalidate invalidate rect null false chypertextctrl setlinkcolor linkcolor binvalidate m_linkcolor linkcolor binvalidate invalidaterect void c hyper text ctrl update size bool b repaint if m bdontupdatesizeinfo return m bdontupdatesizeinfo true dword dw style get window long ptr m hwnd gwl style bool vscrollneeded false c clientdc dc this c font h old font dc select object m font int i scroll height get system metrics sm cyhscroll m lines clear c rect rc get client rect rc rc deflate rect 2 0 m imaxwidth 0 m ilinesheight 0 long i max width chars 0 size sz if rc width 5 rc height 5 std list c hyper link iterator it m text get links begin std list c key word iterator ht m text get keywords begin lpctstr s m text get text int len m text get text get length int width rc width int npos new position pos 0 current position ll line length rll line length with wordwrap if used while len 0 ll len npos ll for int i 0 i len i if s i t r s i t n if s i t r i 1 len s i 1 t n npos i 2 else npos i 1 ll i break if get text extent ex point dc s ll 512 512 ll width rll null sz sz cy 0 get text extent ex point dc t 1 0 null null sz sz cx 0 rll ll if rll ll rll ll if check bits dw style htc wordwrap rll ll else if rll ll npos rll if rll 0 if rll len istspace tuchar s rll for int i rll 1 i 0 i if istspace tuchar s i rll i npos i 1 break if npos 0 npos 1 c line info li pos pos rll 1 c line part info pl pos pos rll 1 while it m text get links end it end pos it while ht m text get keywords end ht end pos ht split the line into parts of hypertext normaltext keywords etc for int i pl begin i pl end i if it m text get links end i it begin it end i i a if i pl m xbegin c line part info pln pl m xbegin i 1 li push back pln if it end pl end pl m xbegin pl end 1 c line part info pln i pl end it li push back pln break else pl m xbegin it end 1 c line part info pln i it end it li push back pln i pl m xbegin it else if ht m text get keywords end i ht begin ht end i i a if i pl m xbegin c line part info pln pl m xbegin i 1 li push back pln if ht end pl end pl m xbegin pl end 1 c line part info pln i pl end 0 ht li push back pln break else pl m xbegin ht end 1 c line part info pln i ht end 0 ht li push back pln i pl m xbegin ht if pl len 0 li push back pl m ilineheight sz cy m ilinesheight m ilineheight if sz cx m imaxwidth m imaxwidth sz cx if i max width chars li len i max width chars li len m lines push back li pos npos s npos len npos if m ilinesheight i scroll height rc height vscrollneeded true if b repaint invalidate rect rc dc select object h old font update scroll bars dw style get window long ptr m hwnd gwl style if check bits dw style htc auto scroll bars if vscrollneeded if vscrollon show scroll bar sb vert true dw style ws vscroll vscrollon true else if vscrollneeded show scroll bar sb vert false vscrollon false if check bits dw style htc auto scroll bars check bits dw style htc wordwrap if m imaxwidth rc width show scroll bar sb horz true dw style ws hscroll scrollinfo si si cb size sizeof si si f mask sif page sif pos sif range if check bits dw style ws hscroll m imaxwidth 0 si n min 0 si n max i max width chars i max width chars 2 si n pos int double si n max m ihorzpos 100 si n page rc width si n max m imaxwidth set scroll info sb horz si false if check bits dw style ws vscroll m ilinesheight 0 si n min 0 si n max int m lines size si n pos si n max int double si n max m ivertpos 100 si n page rc height si n max m ilinesheight set scroll info sb vert si true m bdontupdatesizeinfo false update vis lines chypertextctrl updatesize brepaint m_bdontupdatesizeinfo m_bdontupdatesizeinfo dwstyle getwindowlongptr m_hwnd gwl_style cclientdc cfont holdfont selectobject m_font iscrollheight getsystemmetrics sm_cyhscroll m_lines crect getclientrect deflaterect m_imaxwidth m_ilinesheight imaxwidthchars chyperlink m_text getlinks ckeyword m_text getkeywords m_text gettext m_text gettext getlength _t _t _t _t gettextextentexpoint gettextextentexpoint _t check_bits dwstyle htc_wordwrap _istspace _tuchar _istspace _tuchar clineinfo clinepartinfo m_text getlinks m_text getkeywords m_text getlinks i_a m_xbegin clinepartinfo m_xbegin push_back m_xbegin clinepartinfo push_back m_xbegin clinepartinfo push_back m_xbegin m_text getkeywords i_a m_xbegin clinepartinfo m_xbegin push_back m_xbegin clinepartinfo push_back m_xbegin clinepartinfo push_back m_xbegin push_back m_ilineheight m_ilinesheight m_ilineheight m_imaxwidth m_imaxwidth imaxwidthchars imaxwidthchars m_lines push_back m_ilinesheight iscrollheight brepaint invalidaterect selectobject holdfont dwstyle getwindowlongptr m_hwnd gwl_style check_bits dwstyle htc_auto_scroll_bars showscrollbar sb_vert dwstyle ws_vscroll showscrollbar sb_vert check_bits dwstyle htc_auto_scroll_bars check_bits dwstyle htc_wordwrap m_imaxwidth showscrollbar sb_horz dwstyle ws_hscroll cbsize fmask sif_page sif_pos sif_range check_bits dwstyle ws_hscroll m_imaxwidth nmin nmax imaxwidthchars imaxwidthchars npos nmax m_ihorzpos npage nmax m_imaxwidth setscrollinfo sb_horz check_bits dwstyle ws_vscroll m_ilinesheight nmin nmax m_lines npos nmax nmax m_ivertpos npage nmax m_ilinesheight setscrollinfo sb_vert m_bdontupdatesizeinfo updatevislines void c hyper text ctrl update fonts dword dw style get window long ptr m hwnd gwl style m linksfont delete object m hoverfont delete object logfont lf m font get log font lf if check bits dw style htc underline links lf lf underline true m linksfont create font indirect lf m font get log font lf if check bits dw style htc underline hover lf lf underline true m hoverfont create font indirect lf chypertextctrl updatefonts dwstyle getwindowlongptr m_hwnd gwl_style m_linksfont deleteobject m_hoverfont deleteobject m_font getlogfont check_bits dwstyle htc_underline_links lfunderline m_linksfont createfontindirect m_font getlogfont check_bits dwstyle htc_underline_hover lfunderline m_hoverfont createfontindirect void c hyper text ctrl update vis lines restore link dword dw style get window long ptr m hwnd gwl style int id 1 if check bits dw style htc enable tooltips for std vector c vis line iterator itv m vislines begin itv m vislines end itv for c vis line iterator jt itv begin jt itv end jt if jt m phyperlink null m tip del tool this id m vislines clear std vector c line info iterator it m lines begin int i vert pos 0 int i horz pos 0 if check bits dw style ws vscroll i vert pos get scroll pos sb vert if check bits dw style ws hscroll i horz pos get scroll pos sb horz if i vert pos int m lines size return it i vert pos c clientdc dc this device context for painting c font h old font dc select object m font int ypos 0 lpctstr s m text get text c rect rc client get client rect rc client for it m lines end it int x pos 2 uint line pos it begin uint offset 0 uint len 0 c vis line vl c rect rc bounds std vector c line part info iterator jt for jt it begin jt it end jt if jt begin line pos i horz pos jt end line pos i horz pos offset line pos i horz pos len jt len line pos i horz pos jt begin break while jt it end if len 0 size sz get text extent ex point dc s offset len 0 null null sz rc bounds left x pos x pos sz cx rc bounds right x pos rc bounds top ypos rc bounds bottom ypos m ilineheight vl push back c vis part jt rc bounds offset len null null if x pos rc client width break jt if jt it end break offset jt m xbegin len jt len m vislines push back vl ypos m ilineheight if ypos rc client bottom break c vis part p prev null p next id 1 for std vector c vis line iterator it2 m vislines begin it2 m vislines end it2 for c vis line iterator jt it2 begin jt it2 end jt p next jt if p prev null p prev m phyperlink null p prev m phyperlink p next m phyperlink p prev p next p prev m pnext p next p next m pprev p prev p prev p next if check bits dw style htc enable tooltips jt m phyperlink null m tip add tool this lpctstr jt m phyperlink title jt m rcbounds id dc select object h old font chypertextctrl updatevislines restorelink dwstyle getwindowlongptr m_hwnd gwl_style check_bits dwstyle htc_enable_tooltips cvisline m_vislines m_vislines cvisline m_phyperlink m_tip deltool m_vislines clineinfo m_lines ivertpos ihorzpos check_bits dwstyle ws_vscroll ivertpos getscrollpos sb_vert check_bits dwstyle ws_hscroll ihorzpos getscrollpos sb_horz ivertpos m_lines ivertpos cclientdc cfont holdfont selectobject m_font m_text gettext crect rcclient getclientrect rcclient m_lines xpos linepos cvisline crect rcbounds clinepartinfo linepos ihorzpos linepos ihorzpos linepos ihorzpos linepos ihorzpos gettextextentexpoint rcbounds xpos xpos rcbounds xpos rcbounds rcbounds m_ilineheight push_back cvispart rcbounds xpos rcclient m_xbegin m_vislines push_back m_ilineheight rcclient cvispart pprev pnext cvisline m_vislines m_vislines cvisline pnext pprev pprev m_phyperlink pprev m_phyperlink pnext m_phyperlink pprev pnext pprev m_pnext pnext pnext m_pprev pprev pprev pnext check_bits dwstyle htc_enable_tooltips m_phyperlink m_tip addtool m_phyperlink m_rcbounds selectobject holdfont void c hyper text ctrl highlight link c vis part part const c point mouse coords if m pactivepart part return if m pactivepart part m pactivepart null part null m pactivepart m phyperlink part m phyperlink restore link m pactivepart part while m pactivepart m pprev null m pactivepart m pactivepart m pprev c clientdc dc this c font h old font dc select object m hoverfont dc set bk color m bkcolor dc set text color m hovercolor lpctstr s m text get text c vis part p m pactivepart while p null text out dc p m rcbounds left p m rcbounds top s p m irealbegin p m ireallen p p m pnext dc select object h old font set cursor m linkcursor chypertextctrl highlightlink cvispart cpoint mousecoords m_pactivepart m_pactivepart m_pactivepart m_pactivepart m_phyperlink m_phyperlink restorelink m_pactivepart m_pactivepart m_pprev m_pactivepart m_pactivepart m_pprev cclientdc cfont holdfont selectobject m_hoverfont setbkcolor m_bkcolor settextcolor m_hovercolor m_text gettext cvispart m_pactivepart textout m_rcbounds m_rcbounds m_irealbegin m_ireallen m_pnext selectobject holdfont setcursor m_linkcursor void c hyper text ctrl restore link if m pactivepart null return c clientdc dc this c font h old font dc select object m linksfont dc set bk color m bkcolor dc set text color m linkcolor lpctstr s m text get text c vis part p m pactivepart while p null text out dc p m rcbounds left p m rcbounds top s p m irealbegin p m ireallen p p m pnext dc select object h old font m pactivepart null set cursor m defaultcursor chypertextctrl restorelink m_pactivepart cclientdc cfont holdfont selectobject m_linksfont setbkcolor m_bkcolor settextcolor m_linkcolor m_text gettext cvispart m_pactivepart textout m_rcbounds m_rcbounds m_irealbegin m_ireallen m_pnext selectobject holdfont m_pactivepart setcursor m_defaultcursor void c hyper text ctrl set colors m bkcolor get sys color color window m textcolor get sys color color windowtext perhaps some sort of check against the bk and text color can be made before blindly using these default link colors m linkcolor rgb 0 0 255 m hovercolor rgb 255 0 0 chypertextctrl setcolors m_bkcolor getsyscolor color_window m_textcolor getsyscolor color_windowtext m_linkcolor m_hovercolor void c hyper text ctrl load hand cursor c string windir get windows directory windir get buffer max path max path windir release buffer windir t winhlp32 exe hmodule h module load library windir assert m linkcursor null if h module hcursor h temp cursor load cursor h module makeintresource 106 if h temp cursor m linkcursor copy cursor h temp cursor free library h module if m linkcursor null m linkcursor copy cursor load cursor null idc arrow chypertextctrl loadhandcursor cstring getwindowsdirectory getbuffer max_path max_path releasebuffer _t hmodule loadlibrary m_linkcursor hmodule htempcursor loadcursor hmodule htempcursor m_linkcursor copycursor htempcursor freelibrary hmodule m_linkcursor m_linkcursor copycursor loadcursor idc_arrow cgdi thread cgdi thread c wnd p wnd hdc hdc m bautodelete false m pmainwnd p wnd m hdc hdc m ndelay 50 m nscrollinc scroll up m bwaitvrt false kill event starts out in the signaled state m heventkill create event null true false null m heventdead create event null true false null cgdithread cgdithread cwnd pwnd m_bautodelete m_pmainwnd pwnd m_hdc m_ndelay m_nscrollinc scroll_up m_bwaitvrt m_heventkill createevent m_heventdead createevent void cgdi thread kill thread note this function is called in the context of other threads not the thread itself reset the m heventkill which signals the thread to shutdown verify set event m heventkill allow thread to run at higher priority during kill process set thread priority thread priority above normal wait for single object m heventdead infinite wait for single object m hthread infinite now delete c win thread object since no longer necessary delete this cgdithread killthread m_heventkill setevent m_heventkill setthreadpriority thread_priority_above_normal waitforsingleobject m_heventdead waitforsingleobject m_hthread cwinthread bool cgdi thread set waitvrt bool b wait bool b tmp m bwaitvrt m bwaitvrt b wait return b tmp cgdithread setwaitvrt bwait btmp m_bwaitvrt m_bwaitvrt bwait btmp int cgdi thread set scroll direction int n direction int n tmp m nscrollinc m nscrollinc n direction return n tmp cgdithread setscrolldirection ndirection ntmp m_nscrollinc m_nscrollinc ndirection ntmp int cgdi thread set delay int n delay int n tmp m ndelay m ndelay n delay return n tmp cgdithread setdelay ndelay ntmp m_ndelay m_ndelay ndelay ntmp cgdi thread cgdi thread close handle m heventkill close handle m heventdead close handle m hanotherdead cgdithread cgdithread closehandle m_heventkill closehandle m_heventdead closehandle m_hanotherdead void cgdi thread delete calling the base here won t do anything but it is a good habit c win thread delete acknowledge receipt of kill notification verify set event m heventdead verify set event m hanotherdead what is this good for nobody is waiting on that event cgdithread cwinthread setevent m_heventdead setevent m_hanotherdead bool cgdi thread init instance thread setup m dc attach m hdc loop but check for kill notification while wait for single object m heventkill 0 wait timeout single step thread cleanup m dc detach avoid entering standard message loop by returning false return false cgdithread initinstance m_dc m_hdc waitforsingleobject m_heventkill wait_timeout singlestep m_dc c friend c friend c up down client client assert client m dwlastseen time null m dwlastusedip client getip m nlastusedport client get user port m dwlastchatted 0 m linkedclient null m friendslot false set linked client client cfriend cfriend cupdownclient m_dwlastseen m_dwlastusedip m_nlastusedport getuserport m_dwlastchatted m_linkedclient m_friendslot setlinkedclient c friend c friend const uchar aby userhash uint32 dw last seen uint32 dw last usedip uint16 n last used port uint32 dw last chatted lpctstr psz name uint32 dw has hash m dwlastseen dw last seen m dwlastusedip dw last usedip m nlastusedport n last used port m dwlastchatted dw last chatted if dw has hash aby userhash md4cpy m abyuserhash aby userhash m dwhashash md4cmp m abyuserhash sm abynullhash 1 0 else md4cpy m abyuserhash sm abynullhash m dwhashash 0 m strname psz name m linkedclient 0 m friendslot false cfriend cfriend abyuserhash dwlastseen dwlastusedip nlastusedport dwlastchatted pszname dwhashash m_dwlastseen dwlastseen m_dwlastusedip dwlastusedip m_nlastusedport nlastusedport m_dwlastchatted dwlastchatted dwhashash abyuserhash m_abyuserhash abyuserhash m_dwhashash m_abyuserhash sm_abynullhash m_abyuserhash sm_abynullhash m_dwhashash m_strname pszname m_linkedclient m_friendslot void c friend set linked client c up down client linked client if linked client m linkedclient if linked client null if m linkedclient null linked client set friend slot m friendslot else linked client set friend slot m linkedclient get friend slot m dwlastseen time null m dwlastusedip linked client getip m nlastusedport linked client get user port m strname linked client get user name md4cpy m abyuserhash linked client get user hash m dwhashash md4cmp m abyuserhash sm abynullhash 1 0 linked client m friend this else if m linkedclient null m friendslot m linkedclient get friend slot if m linkedclient null the old client is no longer friend since it is no longer the linked client m linkedclient set friend slot false m linkedclient m friend null m linkedclient linked client the app friendlist refresh friend this cfriend setlinkedclient cupdownclient linkedclient linkedclient m_linkedclient linkedclient m_linkedclient linkedclient setfriendslot m_friendslot linkedclient setfriendslot m_linkedclient getfriendslot m_dwlastseen m_dwlastusedip linkedclient m_nlastusedport linkedclient getuserport m_strname linkedclient getusername m_abyuserhash linkedclient getuserhash m_dwhashash m_abyuserhash sm_abynullhash linkedclient m_friend m_linkedclient m_friendslot m_linkedclient getfriendslot m_linkedclient m_linkedclient setfriendslot m_linkedclient m_friend m_linkedclient linkedclient theapp refreshfriend void c friend load from file c file dataio file file read hash16 m abyuserhash m dwhashash md4cmp m abyuserhash sm abynullhash 1 0 m dwlastusedip file readu int32 m nlastusedport file readu int16 m dwlastseen file readu int32 m dwlastchatted file readu int32 uint tagcount file readu int32 for uint j 0 j tagcount j c tag newtag new c tag file false switch newtag get nameid case ff name assert newtag is str if newtag is str if m strname is empty m strname newtag get str break delete newtag cfriend loadfromfile cfiledataio readhash16 m_abyuserhash m_dwhashash m_abyuserhash sm_abynullhash m_dwlastusedip readuint32 m_nlastusedport readuint16 m_dwlastseen readuint32 m_dwlastchatted readuint32 readuint32 ctag ctag getnameid ff_name isstr isstr m_strname isempty m_strname getstr void c friend write to file c file dataio file if m dwhashash md4cpy m abyuserhash sm abynullhash file write hash16 m abyuserhash file writeu int32 m dwlastusedip file writeu int16 m nlastusedport file writeu int32 m dwlastseen file writeu int32 m dwlastchatted uint32 u tag count 0 ulong u tag count file pos ulong file get position file writeu int32 u tag count if m strname is empty if write opted2kutf8 tag file m strname ff name u tag count c tag nametag ff name m strname nametag write tag to file file u tag count file seek u tag count file pos c file begin file writeu int32 u tag count file seek 0 c file end cfriend writetofile cfiledataio m_dwhashash m_abyuserhash sm_abynullhash writehash16 m_abyuserhash writeuint32 m_dwlastusedip writeuint16 m_nlastusedport writeuint32 m_dwlastseen writeuint32 m_dwlastchatted utagcount utagcountfilepos getposition writeuint32 utagcount m_strname isempty writeopted2kutf8tag m_strname ff_name utagcount ctag ff_name m_strname writetagtofile utagcount utagcountfilepos cfile writeuint32 utagcount cfile void c friend set friend slot bool new value if m linkedclient null m linkedclient set friend slot new value m friendslot new value cfriend setfriendslot newvalue m_linkedclient m_linkedclient setfriendslot newvalue m_friendslot newvalue bool c friend get friend slot const if m linkedclient null return m linkedclient get friend slot else return m friendslot cfriend getfriendslot m_linkedclient m_linkedclient getfriendslot m_friendslot bool c friend has userhash for int counter 0 counter 16 counter if m abyuserhash counter 0 return true return false cfriend hasuserhash m_abyuserhash c get media info thread m hwndowner null m pafiles null cgetmediainfothread m_hwndowner m_pafiles bool c get media info thread init instance dbg set thread name get media info init thread locale return true cgetmediainfothread initinstance dbgsetthreadname getmediainfo initthreadlocale int c get media info thread run co initialize null c array s media info pa media info new c array s media info try for int i 0 i m pafiles get size i s media info mi if is window m hwndowner get media info m hwndowner static downcast c known file m pafiles i mi m pafiles get size 1 pa media info add mi else delete pa media info pa media info null break catch assert 0 if is window m hwndowner post message m hwndowner um media info result 0 lparam pa media info delete pa media info co uninitialize return 0 cgetmediainfothread coinitialize carray smediainfo pamediainfo carray smediainfo m_pafiles getsize smediainfo iswindow m_hwndowner getmediainfo m_hwndowner static_downcast cknownfile m_pafiles m_pafiles getsize pamediainfo pamediainfo pamediainfo iswindow m_hwndowner postmessage m_hwndowner um_media_info_result pamediainfo pamediainfo couninitialize c media infodll m binitialized false m hlib null m ullversion 0 media info lib v0 4 0 1 m pfnmediainfo4 open null m pfnmediainfo4 close null m pfnmediainfo4 get null m pfnmediainfo4 count get null media info lib v0 5 v0 6 1 m pfnmediainfo5 open null media info lib v0 7 m pfnmediainfo new null m pfnmediainfo delete null m pfnmediainfo open null m pfnmediainfo close null m pfnmediainfo get null m pfnmediainfo count get null cmediainfodll m_binitialized m_hlib m_ullversion mediainfolib m_pfnmediainfo4_open m_pfnmediainfo4_close m_pfnmediainfo4_get m_pfnmediainfo4_count_get mediainfolib m_pfnmediainfo5_open mediainfolib m_pfnmediainfo_new m_pfnmediainfo_delete m_pfnmediainfo_open m_pfnmediainfo_close m_pfnmediainfo_get m_pfnmediainfo_count_get c media infodll if m hlib free library m hlib cmediainfodll m_hlib freelibrary m_hlib bool initialize if m binitialized m binitialized true c string str path the app get profile string t e mule t mediainfo mediainfodllpath t mediainfo dll m hlib load library str path if m hlib null ulonglong ull version get module version m hlib if ull version 0 media info lib v0 4 0 1 does not have a win32 version info resource record char stdcall fpmediainfo4 info version farproc fpmediainfo4 info version get proc address m hlib mediainfo info version if fpmediainfo4 info version char psz version fpmediainfo4 info version if psz version strcmp psz version media info lib v0 4 0 1 http mediainfo sourceforge net 0 farproc m pfnmediainfo4 open get proc address m hlib mediainfo open farproc m pfnmediainfo4 close get proc address m hlib mediainfo close farproc m pfnmediainfo4 get get proc address m hlib mediainfo get farproc m pfnmediainfo4 count get get proc address m hlib mediainfo count get if m pfnmediainfo4 open m pfnmediainfo4 close m pfnmediainfo4 get m ullversion makedllverull 0 4 0 1 return true m pfnmediainfo4 open null m pfnmediainfo4 close null m pfnmediainfo4 get null m pfnmediainfo4 count get null note from media info developer note versioning method for people who develop with load library method if one of 2 first numbers change there is no guaranties that the dll is compatible with old one if one of 2 last numbers change there is a garanty that the dll is compatible with old one so you should test the version of the dll and if one of the 2 first numbers change not load it e mule currently handles v0 5 1 0 v0 6 0 0 v0 6 1 0 else if ull version makedllverull 0 5 0 0 ull version makedllverull 0 7 0 0 don t use mediainfo info version with version v0 5 this function is exported can be called but does not return a valid version string farproc m pfnmediainfo5 open get proc address m hlib mediainfo open farproc m pfnmediainfo close get proc address m hlib mediainfo close farproc m pfnmediainfo get get proc address m hlib mediainfo get farproc m pfnmediainfo count get get proc address m hlib mediainfo count get if m pfnmediainfo5 open m pfnmediainfo close m pfnmediainfo get m ullversion ull version return true m pfnmediainfo5 open null m pfnmediainfo close null m pfnmediainfo get null m pfnmediainfo count get null else if ull version makedllverull 0 7 0 0 ull version makedllverull 0 8 0 0 farproc m pfnmediainfo new get proc address m hlib mediainfo new farproc m pfnmediainfo delete get proc address m hlib mediainfo delete farproc m pfnmediainfo open get proc address m hlib mediainfo open farproc m pfnmediainfo close get proc address m hlib mediainfo close farproc m pfnmediainfo get get proc address m hlib mediainfo get farproc m pfnmediainfo count get get proc address m hlib mediainfo count get if m pfnmediainfo new m pfnmediainfo delete m pfnmediainfo open m pfnmediainfo close m pfnmediainfo get m ullversion ull version return true m pfnmediainfo new null m pfnmediainfo delete null m pfnmediainfo open null m pfnmediainfo close null m pfnmediainfo get null m pfnmediainfo count get null free library m hlib m hlib null return m hlib null m_binitialized m_binitialized cstring strpath theapp getprofilestring _t emule _t mediainfo_mediainfodllpath _t m_hlib loadlibrary strpath m_hlib ullversion getmoduleversion m_hlib ullversion mediainfolib __stdcall fpmediainfo4_info_version fpmediainfo4_info_version getprocaddress m_hlib mediainfo_info_version fpmediainfo4_info_version pszversion fpmediainfo4_info_version pszversion pszversion mediainfolib m_pfnmediainfo4_open getprocaddress m_hlib mediainfo_open m_pfnmediainfo4_close getprocaddress m_hlib mediainfo_close m_pfnmediainfo4_get getprocaddress m_hlib mediainfo_get m_pfnmediainfo4_count_get getprocaddress m_hlib mediainfo_count_get m_pfnmediainfo4_open m_pfnmediainfo4_close m_pfnmediainfo4_get m_ullversion m_pfnmediainfo4_open m_pfnmediainfo4_close m_pfnmediainfo4_get m_pfnmediainfo4_count_get mediainfo loadlibrary emule ullversion ullversion mediainfo_info_version m_pfnmediainfo5_open getprocaddress m_hlib mediainfo_open m_pfnmediainfo_close getprocaddress m_hlib mediainfo_close m_pfnmediainfo_get getprocaddress m_hlib mediainfo_get m_pfnmediainfo_count_get getprocaddress m_hlib mediainfo_count_get m_pfnmediainfo5_open m_pfnmediainfo_close m_pfnmediainfo_get m_ullversion ullversion m_pfnmediainfo5_open m_pfnmediainfo_close m_pfnmediainfo_get m_pfnmediainfo_count_get ullversion ullversion m_pfnmediainfo_new getprocaddress m_hlib mediainfo_new m_pfnmediainfo_delete getprocaddress m_hlib mediainfo_delete m_pfnmediainfo_open getprocaddress m_hlib mediainfo_open m_pfnmediainfo_close getprocaddress m_hlib mediainfo_close m_pfnmediainfo_get getprocaddress m_hlib mediainfo_get m_pfnmediainfo_count_get getprocaddress m_hlib mediainfo_count_get m_pfnmediainfo_new m_pfnmediainfo_delete m_pfnmediainfo_open m_pfnmediainfo_close m_pfnmediainfo_get m_ullversion ullversion m_pfnmediainfo_new m_pfnmediainfo_delete m_pfnmediainfo_open m_pfnmediainfo_close m_pfnmediainfo_get m_pfnmediainfo_count_get freelibrary m_hlib m_hlib m_hlib ulonglong get version const return m ullversion getversion m_ullversion void open lpctstr file if m pfnmediainfo4 open uses conversion return m pfnmediainfo4 open t2a file else if m pfnmediainfo5 open return m pfnmediainfo5 open file else if m pfnmediainfo new void handle m pfnmediainfo new if handle m pfnmediainfo open handle file return handle return null m_pfnmediainfo4_open uses_conversion m_pfnmediainfo4_open m_pfnmediainfo5_open m_pfnmediainfo5_open m_pfnmediainfo_new m_pfnmediainfo_new m_pfnmediainfo_open void close void handle if m pfnmediainfo delete m pfnmediainfo delete handle file is automaticly closed else if m pfnmediainfo4 close m pfnmediainfo4 close handle else if m pfnmediainfo close m pfnmediainfo close handle m_pfnmediainfo_delete m_pfnmediainfo_delete m_pfnmediainfo4_close m_pfnmediainfo4_close m_pfnmediainfo_close m_pfnmediainfo_close c string get void handle stream t c stream kind int stream number lpctstr parameter info t c kind of info info t c kind of search if m pfnmediainfo4 get uses conversion return c string m pfnmediainfo4 get handle stream kind stream number t2a parameter kind of info kind of search else if m pfnmediainfo get return m pfnmediainfo get handle stream kind stream number parameter kind of info kind of search return t cstring stream_t_c streamkind streamnumber info_t_c kindofinfo info_t_c kindofsearch m_pfnmediainfo4_get uses_conversion cstring m_pfnmediainfo4_get streamkind streamnumber kindofinfo kindofsearch m_pfnmediainfo_get m_pfnmediainfo_get streamkind streamnumber kindofinfo kindofsearch _t int count get void handle stream t c stream kind int stream number if m pfnmediainfo4 get return m pfnmediainfo4 count get handle stream kind stream number else if m pfnmediainfo count get return m pfnmediainfo count get handle stream kind stream number return 0 count_get stream_t_c streamkind streamnumber m_pfnmediainfo4_get m_pfnmediainfo4_count_get streamkind streamnumber m_pfnmediainfo_count_get m_pfnmediainfo_count_get streamkind streamnumber c resizable page c file detail dialog name idd 0 m pafiles null m bdatachanged false m strcaption get res string ids dl filename m psp psz title m strcaption m psp dw flags psp usetitle m timer 0 memset m aicolwidths 0 sizeof m aicolwidths m bappliedsystemimagelist false m sortorder 0 m sortindex 1 m bself false cresizablepage cfiledetaildialogname m_pafiles m_bdatachanged m_strcaption getresstring ids_dl_filename m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_timer m_aicolwidths m_aicolwidths m_bappliedsystemimagelist m_sortorder m_sortindex m_bself c file detail dialog name c file detail dialog name cfiledetaildialogname cfiledetaildialogname void c file detail dialog name localize if the prefs get languageid makelangid lang english sublang default get dlg item idc takeover set window text get res string ids takeover get dlg item idc buttonstrip set window text get res string ids cleanup get dlg item idc fd sn set window text get res string ids sourcenames cfiledetaildialogname theprefs getlanguageid lang_english sublang_default getdlgitem idc_takeover setwindowtext getresstring ids_takeover getdlgitem idc_buttonstrip setwindowtext getresstring ids_cleanup getdlgitem idc_fd_sn setwindowtext getresstring ids_sourcenames void c file detail dialog name refresh data bool b enable rename can rename file get dlg item idc filename enable window b enable rename get dlg item idc buttonstrip enable window b enable rename get dlg item idc takeover enable window b enable rename fill sourcename list cfiledetaildialogname refreshdata benablerename canrenamefile getdlgitem idc_filename enablewindow benablerename getdlgitem idc_buttonstrip enablewindow benablerename getdlgitem idc_takeover enablewindow benablerename fillsourcenamelist void c file detail dialog name fill sourcename list lvfindinfo info info flags lvfi string int itempos c string str text reset for int i 0 i m listfilenames get item count i fctrlitem struct item fctrlitem struct m listfilenames get item data i item count 0 update const c part file file static downcast c part file m pafiles 0 for position pos file srclist get head position pos null c up down client cur src file srclist get next pos if cur src get request file file cur src get client filename get length 0 continue info psz cur src get client filename if itempos m listfilenames find item info 1 1 fctrlitem struct newitem new fctrlitem struct newitem count 1 newitem filename cur src get client filename int i system icon idx the app get file type system image idx cur src get client filename if the app get system image list m bappliedsystemimagelist m listfilenames apply image list the app get system image list assert m listfilenames get style lvs shareimagelists 0 m bappliedsystemimagelist true int ix m listfilenames insert item lvif text lvif param lvif image m listfilenames get item count cur src get client filename 0 0 i system icon idx lparam newitem m listfilenames set item text ix 1 t 1 else fctrlitem struct item fctrlitem struct m listfilenames get item data itempos item count 1 str text format t i item count m listfilenames set item text itempos 1 str text remove 0 er for int i 0 i m listfilenames get item count i fctrlitem struct item fctrlitem struct m listfilenames get item data i if item item count 0 delete item m listfilenames delete item i i 0 m listfilenames sort items compare list name items m sortindex m sortorder 0 10 cfiledetaildialogname fillsourcenamelist lvfi_string cstring strtext m_listfilenames getitemcount fctrlitem_struct fctrlitem_struct m_listfilenames getitemdata cpartfile static_downcast cpartfile m_pafiles getheadposition cupdownclient cur_src getnext cur_src getrequestfile cur_src getclientfilename getlength cur_src getclientfilename m_listfilenames finditem fctrlitem_struct fctrlitem_struct cur_src getclientfilename isystemiconidx theapp getfiletypesystemimageidx cur_src getclientfilename theapp getsystemimagelist m_bappliedsystemimagelist m_listfilenames applyimagelist theapp getsystemimagelist m_listfilenames getstyle lvs_shareimagelists m_bappliedsystemimagelist m_listfilenames insertitem lvif_text lvif_param lvif_image m_listfilenames getitemcount cur_src getclientfilename isystemiconidx m_listfilenames setitemtext _t fctrlitem_struct fctrlitem_struct m_listfilenames getitemdata strtext _t m_listfilenames setitemtext strtext m_listfilenames getitemcount fctrlitem_struct fctrlitem_struct m_listfilenames getitemdata m_listfilenames deleteitem m_listfilenames sortitems comparelistnameitems m_sortindex m_sortorder void c file detail dialog name copy int i sel m listfilenames get next item 1 lvis selected lvis focused if i sel 1 the app copy text to clipboard m listfilenames get item text i sel 0 cfiledetaildialogname isel m_listfilenames getnextitem lvis_selected lvis_focused isel theapp copytexttoclipboard m_listfilenames getitemtext isel bool c file detail dialog name can rename file const const c part file file static downcast c part file m pafiles 0 return file get status ps complete file get status ps completing cfiledetaildialogname canrenamefile cpartfile static_downcast cpartfile m_pafiles getstatus ps_complete getstatus ps_completing void c file detail dialog name rename file if can rename file c string str new file name get dlg item idc filename get window text str new file name str new file name trim if str new file name is empty is valid ed2k string str new file name return c part file file static downcast c part file m pafiles 0 file set file name str new file name true file update displayed info file save part file cfiledetaildialogname renamefile canrenamefile cstring strnewfilename getdlgitem idc_filename getwindowtext strnewfilename strnewfilename strnewfilename isempty isvalided2kstring strnewfilename cpartfile static_downcast cpartfile m_pafiles setfilename strnewfilename updatedisplayedinfo savepartfile bool c file detail dialog name on init dialog c resizable page on init dialog init window styles this add anchor idc fd sn top left bottom right add anchor idc listctrlfilenames top left bottom right add anchor idc takeover bottom left add anchor idc buttonstrip bottom right add anchor idc filename bottom left bottom right m listfilenames set name t file detail dlg name m listfilenames set extended style lvs ex fullrowselect lvs ex infotip m listfilenames insert column 0 get res string ids dl filename lvcfmt left 380 m listfilenames insert column 1 get res string ids dl sources lvcfmt left 80 assert m listfilenames get style lvs shareimagelists 0 m listfilenames load settings m listfilenames set sort arrow m listfilenames sort items compare list name items m listfilenames get sort item m listfilenames get sort ascending 0 10 localize start time for calling refresh data verify m timer set timer 301 5000 0 null return true cfiledetaildialogname oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_fd_sn top_left bottom_right addanchor idc_listctrlfilenames top_left bottom_right addanchor idc_takeover bottom_left addanchor idc_buttonstrip bottom_right addanchor idc_filename bottom_left bottom_right m_listfilenames setname _t filedetaildlgname m_listfilenames setextendedstyle lvs_ex_fullrowselect lvs_ex_infotip m_listfilenames insertcolumn getresstring ids_dl_filename lvcfmt_left m_listfilenames insertcolumn getresstring ids_dl_sources lvcfmt_left m_listfilenames getstyle lvs_shareimagelists m_listfilenames loadsettings m_listfilenames setsortarrow m_listfilenames sortitems comparelistnameitems m_listfilenames getsortitem m_listfilenames getsortascending refreshdata m_timer settimer void c file detail dialog name do data exchange c data exchange pdx c resizable page do data exchange pdx ddx control pdx idc listctrlfilenames m listfilenames cfiledetaildialogname dodataexchange cdataexchange cresizablepage dodataexchange ddx_control idc_listctrlfilenames m_listfilenames bool c file detail dialog name on set active if c resizable page on set active return false if m bdatachanged m bself true get dlg item idc filename set window text static downcast c part file m pafiles 0 get file name m bself false refresh data m bdatachanged false return true cfiledetaildialogname onsetactive cresizablepage onsetactive m_bdatachanged m_bself getdlgitem idc_filename setwindowtext static_downcast cpartfile m_pafiles getfilename m_bself refreshdata m_bdatachanged bool c file detail dialog name on apply if m bdatachanged rename file return c resizable page on apply cfiledetaildialogname onapply m_bdatachanged renamefile cresizablepage onapply bool c file detail dialog name on command wparam w param lparam l param int i sel m listfilenames get next item 1 lvis selected lvis focused if i sel 1 switch w param case mp message take over return true case mp copyselected copy return true case mp restore fill sourcename list return true return c resizable page on command w param l param cfiledetaildialogname oncommand wparam lparam isel m_listfilenames getnextitem lvis_selected lvis_focused isel wparam mp_message takeover mp_copyselected mp_restore fillsourcenamelist cresizablepage oncommand wparam lparam int callback c file detail dialog name compare list name items lparam l param1 lparam l param2 lparam l param sort fctrlitem struct item1 fctrlitem struct l param1 fctrlitem struct item2 fctrlitem struct l param2 switch l param sort case 0 return compare locale string no case item1 filename item2 filename case 10 return compare locale string no case item2 filename item1 filename case 1 return item1 count item2 count case 11 return item2 count item1 count return 0 cfiledetaildialogname comparelistnameitems lparam1 lparam2 lparamsort fctrlitem_struct fctrlitem_struct lparam1 fctrlitem_struct fctrlitem_struct lparam2 lparamsort comparelocalestringnocase comparelocalestringnocase void c file detail dialog name on bn clicked button strip c string filename get dlg item idc filename get window text filename get dlg item idc filename set window text cleanup filename filename cfiledetaildialogname onbnclickedbuttonstrip cstring getdlgitem idc_filename getwindowtext getdlgitem idc_filename setwindowtext cleanupfilename void c file detail dialog name take over int i sel m listfilenames get next item 1 lvis selected lvis focused if i sel 1 get dlg item idc filename set window text m listfilenames get item text i sel 0 cfiledetaildialogname takeover isel m_listfilenames getnextitem lvis_selected lvis_focused isel getdlgitem idc_filename setwindowtext m_listfilenames getitemtext isel void c file detail dialog name on lvn columnclick nmhdr pnmhdr lresult p result lpnmlistview pnmlv reinterpret cast lpnmlistview pnmhdr if m sortindex pnmlv i sub item m sortorder 1 else m sortorder m sortorder m sortindex pnmlv i sub item m listfilenames set sort arrow m sortindex m sortorder m listfilenames sort items compare list name items m sortindex m sortorder 0 10 p result 0 cfiledetaildialogname onlvncolumnclick presult reinterpret_cast m_sortindex isubitem m_sortorder m_sortorder m_sortorder m_sortindex isubitem m_listfilenames setsortarrow m_sortindex m_sortorder m_listfilenames sortitems comparelistnameitems m_sortindex m_sortorder presult void c file detail dialog name onnm dblclk list nmhdr pnmhdr lresult p result take over p result 0 cfiledetaildialogname onnmdblclklist presult takeover presult void c file detail dialog name onnm rclick list nmhdr pnmhdr lresult p result uint flag mf string if m listfilenames get next item 1 lvis selected lvis focused 1 flag mf grayed point point get cursor pos point c title menu popup menu popup menu create popup menu popup menu append menu flag mp message get res string ids takeover popup menu append menu flag mp copyselected get res string ids copy popup menu append menu mf string mp restore get res string ids sv update popup menu track popup menu tpm leftalign tpm rightbutton point x point y this verify popup menu destroy menu p result 0 cfiledetaildialogname onnmrclicklist presult mf_string m_listfilenames getnextitem lvis_selected lvis_focused mf_grayed getcursorpos ctitlemenu popupmenu popupmenu createpopupmenu popupmenu appendmenu mp_message getresstring ids_takeover popupmenu appendmenu mp_copyselected getresstring ids_copy popupmenu appendmenu mf_string mp_restore getresstring ids_sv_update popupmenu trackpopupmenu tpm_leftalign tpm_rightbutton popupmenu destroymenu presult void c file detail dialog name on timer uint nid event refresh data cfiledetaildialogname ontimer nidevent refreshdata void c file detail dialog name on destroy m listfilenames save settings for int i 0 i m listfilenames get item count i fctrlitem struct item fctrlitem struct m listfilenames get item data i delete item if m timer kill timer m timer m timer 0 cfiledetaildialogname ondestroy m_listfilenames savesettings m_listfilenames getitemcount fctrlitem_struct fctrlitem_struct m_listfilenames getitemdata m_timer killtimer m_timer m_timer lresult c file detail dialog name on data changed wparam lparam m bdatachanged true return 1 cfiledetaildialogname ondatachanged m_bdatachanged void c file detail dialog name on en change filename if m bself set modified cfiledetaildialogname onenchangefilename m_bself setmodified c resizable page c file detail dialog info idd 0 m pafiles null m bdatachanged false m strcaption get res string ids fileinformation m psp psz title m strcaption m psp dw flags psp usetitle m timer 0 cresizablepage cfiledetaildialoginfo m_pafiles m_bdatachanged m_strcaption getresstring ids_fileinformation m_psp psztitle m_strcaption m_psp dwflags psp_usetitle m_timer c file detail dialog info c file detail dialog info cfiledetaildialoginfo cfiledetaildialoginfo void c file detail dialog info localize get dlg item idc fd x0 set window text get res string ids fd general get dlg item idc fd x1 set window text get res string ids sw name t get dlg item idc fd x2 set window text get res string ids fd met get dlg item idc fd x3 set window text get res string ids fd hash get dlg item idc fd x4 set window text get res string ids dl size t get dlg item idc fd x9 set window text get res string ids fd parts t get dlg item idc fd x5 set window text get res string ids status t get dlg item idc fd x6 set window text get res string ids fd transfer get dlg item idc fd x7 set window text get res string ids dl sources t get dlg item idc fd x14 set window text get res string ids fd trans get dlg item idc fd x12 set window text get res string ids fd compsize get dlg item idc fd x13 set window text get res string ids fd datarate get dlg item idc fd x15 set window text get res string ids lastseencompl get dlg item idc fd lastchange set window text get res string ids fd lastchange get dlg item idc fd x8 set window text get res string ids fd timedate get dlg item idc fd x16 set window text get res string ids fd downloadstarted get dlg item idc dl active time lbl set window text get res string ids dl active time t get dlg item idc hsav set window text get res string ids hsav t get dlg item idc fd corr set window text get res string ids fd corr t get dlg item idc fd recov set window text get res string ids fd recov t get dlg item idc fd compr set window text get res string ids fd compr t get dlg item idc fd xaich set window text get res string ids iachhash t set dlg item text idc remaining text get res string ids dl remains t cfiledetaildialoginfo getdlgitem idc_fd_x0 setwindowtext getresstring ids_fd_general getdlgitem idc_fd_x1 setwindowtext getresstring ids_sw_name _t getdlgitem idc_fd_x2 setwindowtext getresstring ids_fd_met getdlgitem idc_fd_x3 setwindowtext getresstring ids_fd_hash getdlgitem idc_fd_x4 setwindowtext getresstring ids_dl_size _t getdlgitem idc_fd_x9 setwindowtext getresstring ids_fd_parts _t getdlgitem idc_fd_x5 setwindowtext getresstring ids_status _t getdlgitem idc_fd_x6 setwindowtext getresstring ids_fd_transfer getdlgitem idc_fd_x7 setwindowtext getresstring ids_dl_sources _t getdlgitem idc_fd_x14 setwindowtext getresstring ids_fd_trans getdlgitem idc_fd_x12 setwindowtext getresstring ids_fd_compsize getdlgitem idc_fd_x13 setwindowtext getresstring ids_fd_datarate getdlgitem idc_fd_x15 setwindowtext getresstring ids_lastseencompl getdlgitem idc_fd_lastchange setwindowtext getresstring ids_fd_lastchange getdlgitem idc_fd_x8 setwindowtext getresstring ids_fd_timedate getdlgitem idc_fd_x16 setwindowtext getresstring ids_fd_downloadstarted getdlgitem idc_dl_active_time_lbl setwindowtext getresstring ids_dl_active_time _t getdlgitem idc_hsav setwindowtext getresstring ids_hsav _t getdlgitem idc_fd_corr setwindowtext getresstring ids_fd_corr _t getdlgitem idc_fd_recov setwindowtext getresstring ids_fd_recov _t getdlgitem idc_fd_compr setwindowtext getresstring ids_fd_compr _t getdlgitem idc_fd_xaich setwindowtext getresstring ids_iachhash _t setdlgitemtext idc_remaining_text getresstring ids_dl_remains _t void c file detail dialog info refresh data c string str if m pafiles get size 1 const c part file file static downcast c part file m pafiles 0 if file is completed we output the file path and not the part met file path if file get status true ps complete get dlg item idc fd x2 set window text get res string ids dl filename set dlg item text idc fname file get file name set dlg item text idc metfile file get full name set dlg item text idc fhash md4str file get file hash if file get transferring src count 0 str format get res string ids partinfos2 file get transferring src count else str file get partfile status set dlg item text idc pfstatus str str format t u s u 1f file get part count get res string ids available file get available part count float file get available part count 100 file get part count set dlg item text idc partcount str date created if file get cr file date 0 str format t s get res string ids timebefore file get crc file date format the prefs get date time format cast seconds to lnghm time null file get cr file date else str get res string ids unknown set dlg item text idc filecreated str active download time uint32 n dl active time file get dl active time if n dl active time str cast seconds to lnghm n dl active time else str get res string ids unknown set dlg item text idc dl active time str last seen complete struct tm ptim last seen complete file lastseencomplete get local tm if file lastseencomplete null ptim last seen complete null str format get res string ids never else str format t s get res string ids timebefore file lastseencomplete format the prefs get date time format cast seconds to lnghm time null safe mktime ptim last seen complete set dlg item text idc lastseencompl str last receive if file get file date 0 file get real file size uint64 0 last modified sometimes is up to 2 seconds greater than the current time if it s related to the fat32 seconds time resolution the max failure should still be only 1 sec happens at least on fat32 with very high download speed uint32 t last modified file get file date uint32 t now time null uint32 t ago if t now t last modified t ago t now t last modified else trace t now s n c time t now format x trace tl md s u n c time t last modified format x t last modified t now trace n t ago 0 str format t s get res string ids timebefore file getc file date format the prefs get date time format cast seconds to lnghm t ago else str get res string ids never set dlg item text idc lastreceived str aich hash switch file getaich hashset get status case aich trusted case aich verified case aich hashsetcomplete if file getaich hashset has valid master hash set dlg item text idc fd aichhash file getaich hashset get master hash get string break default set dlg item text idc fd aichhash get res string ids unknown else set dlg item text idc fname sm psznotavail set dlg item text idc metfile sm psznotavail set dlg item text idc fhash sm psznotavail set dlg item text idc pfstatus sm psznotavail set dlg item text idc partcount sm psznotavail set dlg item text idc filecreated sm psznotavail set dlg item text idc dl active time sm psznotavail set dlg item text idc lastseencompl sm psznotavail set dlg item text idc lastreceived sm psznotavail set dlg item text idc fd aichhash sm psznotavail uint64 u file size 0 uint64 u real file size 0 uint64 u transferred 0 uint64 u corrupted 0 uint32 u recovered parts 0 uint64 u compression 0 uint64 u completed 0 int i hashset available 0 uint32 u data rate 0 uint u sources 0 uint u valid sources 0 uint unnp sources 0 uint ua4af sources 0 for int i 0 i m pafiles get size i const c part file file static downcast c part file m pafiles i u file size uint64 file get file size u real file size uint64 file get real file size u transferred uint64 file get transferred u corrupted file get corruption loss u recovered parts file get recovered parts byich u compression file get compression gain u data rate file get datarate u completed uint64 file get completed size i hashset available file get hash count file geted2k part hash count 1 0 if file is part file u sources file get source count u valid sources file get valid sources count unnp sources file get src statistics value ds noneededparts ua4af sources file get srca4af count str format t s s s s s cast itox bytes u file size false false get formatedu int64 u file size get res string ids bytes get res string ids ondisk cast itox bytes u real file size false false set dlg item text idc fsize str if i hashset available 0 set dlg item text idc hashset get res string ids no else if i hashset available m pafiles get size set dlg item text idc hashset get res string ids yes else set dlg item text idc hashset t str format get res string ids sourcesinfo u sources u valid sources unnp sources ua4af sources set dlg item text idc sourcecount str set dlg item text idc datarate cast itox bytes u data rate false true set dlg item text idc transferred cast itox bytes u transferred false false str format t s 1f cast itox bytes u completed false false u file size 0 u completed 100 0 u file size 0 0 set dlg item text idc complsize str str format t s 1f cast itox bytes u corrupted false false u transferred 0 u corrupted 100 0 u transferred 0 0 set dlg item text idc corrupted str str format t s 1f cast itox bytes u file size u completed false false u file size 0 u file size u completed 100 0 u file size 0 0 set dlg item text idc remaining str str format t u s u recovered parts get res string ids fd parts set dlg item text idc recovered str str format t s 1f cast itox bytes u compression false false u transferred 0 u compression 100 0 u transferred 0 0 set dlg item text idc compression str cfiledetaildialoginfo refreshdata cstring m_pafiles getsize cpartfile static_downcast cpartfile m_pafiles getstatus ps_complete getdlgitem idc_fd_x2 setwindowtext getresstring ids_dl_filename setdlgitemtext idc_fname getfilename setdlgitemtext idc_metfile getfullname setdlgitemtext idc_fhash getfilehash gettransferringsrccount getresstring ids_partinfos2 gettransferringsrccount getpartfilestatus setdlgitemtext idc_pfstatus _t getpartcount getresstring ids_available getavailablepartcount getavailablepartcount getpartcount setdlgitemtext idc_partcount getcrfiledate _t getresstring ids_timebefore getcrcfiledate theprefs getdatetimeformat castsecondstolnghm getcrfiledate getresstring ids_unknown setdlgitemtext idc_filecreated ndlactivetime getdlactivetime ndlactivetime castsecondstolnghm ndlactivetime getresstring ids_unknown setdlgitemtext idc_dl_active_time ptimlastseencomplete getlocaltm ptimlastseencomplete getresstring ids_never _t getresstring ids_timebefore theprefs getdatetimeformat castsecondstolnghm safe_mktime ptimlastseencomplete setdlgitemtext idc_lastseencompl getfiledate getrealfilesize tlastmodified getfiledate tnow tago tnow tlastmodified tago tnow tlastmodified tnow ctime tnow tlmd ctime tlastmodified tlastmodified tnow tago _t getresstring ids_timebefore getcfiledate theprefs getdatetimeformat castsecondstolnghm tago getresstring ids_never setdlgitemtext idc_lastreceived getaichhashset getstatus aich_trusted aich_verified aich_hashsetcomplete getaichhashset hasvalidmasterhash setdlgitemtext idc_fd_aichhash getaichhashset getmasterhash getstring setdlgitemtext idc_fd_aichhash getresstring ids_unknown setdlgitemtext idc_fname sm_psznotavail setdlgitemtext idc_metfile sm_psznotavail setdlgitemtext idc_fhash sm_psznotavail setdlgitemtext idc_pfstatus sm_psznotavail setdlgitemtext idc_partcount sm_psznotavail setdlgitemtext idc_filecreated sm_psznotavail setdlgitemtext idc_dl_active_time sm_psznotavail setdlgitemtext idc_lastseencompl sm_psznotavail setdlgitemtext idc_lastreceived sm_psznotavail setdlgitemtext idc_fd_aichhash sm_psznotavail ufilesize urealfilesize utransferred ucorrupted urecoveredparts ucompression ucompleted ihashsetavailable udatarate usources uvalidsources unnpsources ua4afsources m_pafiles getsize cpartfile static_downcast cpartfile m_pafiles ufilesize getfilesize urealfilesize getrealfilesize utransferred gettransferred ucorrupted getcorruptionloss urecoveredparts getrecoveredpartsbyich ucompression getcompressiongain udatarate getdatarate ucompleted getcompletedsize ihashsetavailable gethashcount geted2kparthashcount ispartfile usources getsourcecount uvalidsources getvalidsourcescount unnpsources getsrcstatisticsvalue ds_noneededparts ua4afsources getsrca4afcount _t castitoxbytes ufilesize getformateduint64 ufilesize getresstring ids_bytes getresstring ids_ondisk castitoxbytes urealfilesize setdlgitemtext idc_fsize ihashsetavailable setdlgitemtext idc_hashset getresstring ids_no ihashsetavailable m_pafiles getsize setdlgitemtext idc_hashset getresstring ids_yes setdlgitemtext idc_hashset _t getresstring ids_sourcesinfo usources uvalidsources unnpsources ua4afsources setdlgitemtext idc_sourcecount setdlgitemtext idc_datarate castitoxbytes udatarate setdlgitemtext idc_transferred castitoxbytes utransferred _t castitoxbytes ucompleted ufilesize ucompleted ufilesize setdlgitemtext idc_complsize _t castitoxbytes ucorrupted utransferred ucorrupted utransferred setdlgitemtext idc_corrupted _t castitoxbytes ufilesize ucompleted ufilesize ufilesize ucompleted ufilesize setdlgitemtext idc_remaining _t urecoveredparts getresstring ids_fd_parts setdlgitemtext idc_recovered _t castitoxbytes ucompression utransferred ucompression utransferred setdlgitemtext idc_compression bool c file detail dialog info on init dialog c resizable page on init dialog init window styles this add anchor idc fd x0 top left top right add anchor idc fd x6 top left top right add anchor idc fd x8 top left top right add anchor idc fname top left top right add anchor idc metfile top left top right add anchor idc fhash top left top right add anchor idc fd aichhash top left top right add anchor idc fsize top left top right add anchor idc partcount top left top right add anchor idc hashset top left top right add anchor idc sourcecount top left top right add anchor idc datarate top left top right add anchor idc filecreated top left top right add anchor idc dl active time top left top right add anchor idc lastseencompl top left top right add anchor idc lastreceived top left top right localize no need to explicitly call refresh data here on set active will be called right after on init dialog start time for calling refresh data verify m timer set timer 301 5000 0 null return true cfiledetaildialoginfo oninitdialog cresizablepage oninitdialog initwindowstyles addanchor idc_fd_x0 top_left top_right addanchor idc_fd_x6 top_left top_right addanchor idc_fd_x8 top_left top_right addanchor idc_fname top_left top_right addanchor idc_metfile top_left top_right addanchor idc_fhash top_left top_right addanchor idc_fd_aichhash top_left top_right addanchor idc_fsize top_left top_right addanchor idc_partcount top_left top_right addanchor idc_hashset top_left top_right addanchor idc_sourcecount top_left top_right addanchor idc_datarate top_left top_right addanchor idc_filecreated top_left top_right addanchor idc_dl_active_time top_left top_right addanchor idc_lastseencompl top_left top_right addanchor idc_lastreceived top_left top_right refreshdata onsetactive oninitdialog refreshdata m_timer settimer void c file detail dialog info do data exchange c data exchange pdx c resizable page do data exchange pdx cfiledetaildialoginfo dodataexchange cdataexchange cresizablepage dodataexchange bool c file detail dialog info on set active if c resizable page on set active return false if m bdatachanged refresh data m bdatachanged false return true cfiledetaildialoginfo onsetactive cresizablepage onsetactive m_bdatachanged refreshdata m_bdatachanged void c file detail dialog info on timer uint nid event refresh data cfiledetaildialoginfo ontimer nidevent refreshdata void c file detail dialog info on destroy if m timer kill timer m timer m timer 0 cfiledetaildialoginfo ondestroy m_timer killtimer m_timer m_timer lresult c file detail dialog info on data changed wparam lparam m bdatachanged true return 1 cfiledetaildialoginfo ondatachanged m_bdatachanged void c file detail dialog update title if m aitems get size 1 set window text get res string ids details t static downcast c abstract file m aitems 0 get file name else set window text get res string ids details cfiledetaildialog updatetitle m_aitems getsize setwindowtext getresstring ids_details _t static_downcast cabstractfile m_aitems getfilename setwindowtext getresstring ids_details bool c file detail dialog on init dialog enable stacked tabs false bool b result c list view walker property sheet on init dialog high color tab update image list this init window styles this enable save restore t file detail dialog call this after on init dialog update title return b result cfiledetaildialog oninitdialog enablestackedtabs bresult clistviewwalkerpropertysheet oninitdialog highcolortab updateimagelist initwindowstyles enablesaverestore _t filedetaildialog oninitdialog updatetitle bresult void c file detail dialog on destroy if m upshinvokepage 0 m ppshstartpage get page get active index m psp psz template c list view walker property sheet on destroy cfiledetaildialog ondestroy m_upshinvokepage m_ppshstartpage getpage getactiveindex m_psp psztemplate clistviewwalkerpropertysheet ondestroy lresult c file detail dialog on data changed wparam lparam update title return 1 cfiledetaildialog ondatachanged updatetitle c main frame drop target c main frame drop target m bdropdatavalid false m cfhtml clipformat register clipboard format t html format assert m cfhtml 0 m cfshellurl clipformat register clipboard format cfstr shellurl assert m cfshellurl 0 cmainframedroptarget cmainframedroptarget m_bdropdatavalid m_cfhtml registerclipboardformat _t m_cfhtml m_cfshellurl registerclipboardformat cfstr_shellurl m_cfshellurl void c main frame drop target on drag leave c wnd do not set m bdropdatavalid false on drag leave may be called from mfc when scrolling in that case it s not really a leave m bdropdatavalid false cmainframedroptarget ondragleave cwnd m_bdropdatavalid ondragleave m_bdropdatavalid void c credits dlg kill thread tell thread to shutdown verify set event m pthread m heventkill wait for thread to finish shutdown verify wait for single object m pthread m hthread infinite wait object 0 delete m pthread m pthread null ccreditsdlg killthread setevent m_pthread m_heventkill waitforsingleobject m_pthread m_hthread wait_object_0 m_pthread m_pthread void c credits dlg start thread m pthread new c credits thread this m pdc get safe hdc m rectscreen if m pthread null return assert valid m pthread m pthread m pthreadparams null create thread in a suspended state so we can set the priority before it starts getting away from us if m pthread create thread create suspended delete m pthread m pthread null return thread priority has been set at idle priority to keep from bogging down other apps that may also be running verify m pthread set thread priority thread priority idle now the thread can run wild m pthread resume thread ccreditsdlg startthread m_pthread ccreditsthread m_pdc getsafehdc m_rectscreen m_pthread assert_valid m_pthread m_pthread m_pthreadparams m_pthread createthread create_suspended m_pthread m_pthread m_pthread setthreadpriority thread_priority_idle m_pthread resumethread c dialog c credits dlg idd p parent afx data init c credits dlg note the class wizard will add member initialization here afx data init m pdc null cdialog ccreditsdlg pparent afx_data_init ccreditsdlg classwizard afx_data_init m_pdc c credits dlg c credits dlg m imgsplash delete object ccreditsdlg ccreditsdlg m_imgsplash deleteobject void c credits dlg do data exchange c data exchange pdx c dialog do data exchange pdx afx data map c credits dlg note the class wizard will add ddx and ddv calls here afx data map ccreditsdlg dodataexchange cdataexchange cdialog dodataexchange afx_data_map ccreditsdlg classwizard afx_data_map void c credits dlg onl button down uint n flags c point point c dialog onl button down n flags point see if they clicked on our button to dismiss the dialog if point x button left x point x button right x if point y button top y point y button bottom y c dialog onok return post message wm nclbuttondown htcaption makelparam point x point y ccreditsdlg onlbuttondown nflags cpoint cdialog onlbuttondown nflags button_left_x button_right_x button_top_y button_bottom_y cdialog postmessage wm_nclbuttondown bool c credits dlg on init dialog c dialog on init dialog verify m imgsplash attach the app load image t about t jpg m rectscreen set rect screen left screen top screen right screen bottom start thread return true ccreditsdlg oninitdialog cdialog oninitdialog m_imgsplash theapp loadimage _t _t m_rectscreen setrect screen_left screen_top screen_right screen_bottom startthread void c credits dlg on paint c paintdc dc this device context for painting if m imgsplash get safe handle cdc dc mem if dc mem create compatibledc dc c bitmap p oldbm dc mem select object m imgsplash bitmap bm m imgsplash get bitmap bm windowplacement wp this get window placement wp wp rc normal position right wp rc normal position left bm bm width wp rc normal position bottom wp rc normal position top bm bm height this set window placement wp dc bit blt 0 0 bm bm width bm bm height dc mem 0 0 srccopy dc mem select object p oldbm ccreditsdlg onpaint cpaintdc m_imgsplash getsafehandle dcmem dcmem createcompatibledc cbitmap poldbm dcmem selectobject m_imgsplash m_imgsplash getbitmap getwindowplacement rcnormalposition rcnormalposition bmwidth rcnormalposition rcnormalposition bmheight setwindowplacement bitblt bmwidth bmheight dcmem dcmem selectobject poldbm void c credits dlg on destroy kill thread delete m pdc m pdc null c dialog on destroy ccreditsdlg ondestroy killthread m_pdc m_pdc cdialog ondestroy int c credits dlg on create lpcreatestruct lp create struct if c dialog on create lp create struct 1 return 1 m pdc must be initialized here instead of the constructor because the hwnd isn t created until create is called m pdc new c clientdc this return 0 ccreditsdlg oncreate lpcreatestruct cdialog oncreate lpcreatestruct m_pdc m_pdc cclientdc c resizable dialog c direct download dlg idd p parent m icnwnd null cresizabledialog cdirectdownloaddlg pparent m_icnwnd c direct download dlg c direct download dlg if m icnwnd verify destroy icon m icnwnd cdirectdownloaddlg cdirectdownloaddlg m_icnwnd destroyicon m_icnwnd void c direct download dlg update controls get dlg item idok enable window get dlg item idc elink get window text length 0 cdirectdownloaddlg updatecontrols getdlgitem enablewindow getdlgitem idc_elink getwindowtextlength void c direct download dlg update cat tabs int oldsel m cattabs get cur sel m cattabs delete all items for int ix 0 ix the prefs get cat count ix c string label ix 0 get res string ids all the prefs get category ix title label replace t t m cattabs insert item ix label if oldsel m cattabs get item count oldsel 1 oldsel 0 m cattabs set cur sel oldsel cdirectdownloaddlg updatecattabs m_cattabs getcursel m_cattabs deleteallitems theprefs getcatcount cstring getresstring ids_all theprefs getcategory _t _t m_cattabs insertitem m_cattabs getitemcount m_cattabs setcursel bool c direct download dlg on init dialog c resizable dialog on init dialog init window styles this set icon m icnwnd the app load icon t paste link false add anchor idc ddown frm top left bottom right add anchor idc elink top left bottom right add anchor idcancel bottom right add anchor idok bottom right add anchor idc catlabel bottom left add anchor idc cats bottom left bottom right enable save restore pref ini section set window text get res string ids sw directdownload m ctrldirectdlfrm set window text get res string ids sw directdownload m ctrldirectdlfrm set icon t download get dlg item idok set window text get res string ids download get dlg item idc fstatic2 set window text get res string ids sw link get dlg item idc catlabel set window text get res string ids cat t get dlg item idok set window text get res string ids download get dlg item idcancel set window text get res string ids cancel if the prefs get cat count 0 get dlg item idc catlabel show window sw hide get dlg item idc cats show window sw hide else update cat tabs if the app m fontsymbol m hobject get dlg item idc catlabel set font the app m fontsymbol get dlg item idc catlabel set window text get ex style ws ex layoutrtl t 3 t 4 show a right arrow update controls return true return true unless you set the focus to a control exception ocx property pages should return false cdirectdownloaddlg oninitdialog cresizabledialog oninitdialog initwindowstyles seticon m_icnwnd theapp loadicon _t pastelink addanchor idc_ddown_frm top_left bottom_right addanchor idc_elink top_left bottom_right addanchor bottom_right addanchor bottom_right addanchor idc_catlabel bottom_left addanchor idc_cats bottom_left bottom_right enablesaverestore pref_ini_section setwindowtext getresstring ids_sw_directdownload m_ctrldirectdlfrm setwindowtext getresstring ids_sw_directdownload m_ctrldirectdlfrm seticon _t getdlgitem setwindowtext getresstring ids_download getdlgitem idc_fstatic2 setwindowtext getresstring ids_sw_link getdlgitem idc_catlabel setwindowtext getresstring ids_cat _t getdlgitem setwindowtext getresstring ids_download getdlgitem setwindowtext getresstring ids_cancel theprefs getcatcount getdlgitem idc_catlabel showwindow sw_hide getdlgitem idc_cats showwindow sw_hide updatecattabs theapp m_fontsymbol m_hobject getdlgitem idc_catlabel setfont theapp m_fontsymbol getdlgitem idc_catlabel setwindowtext getexstyle ws_ex_layoutrtl _t _t updatecontrols void c direct download dlg do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx control pdx idc ddown frm m ctrldirectdlfrm ddx control pdx idc cats m cattabs cdirectdownloaddlg dodataexchange cdataexchange cresizabledialog dodataexchange ddx_control idc_ddown_frm m_ctrldirectdlfrm ddx_control idc_cats m_cattabs void c direct download dlg onok c string str links get dlg item idc elink get window text str links int cur pos 0 c string str tok str links tokenize t t n r cur pos while str tok is empty if str tok right 1 t str tok t try ced2k link p link ced2k link create link from url str tok trim if p link if p link get kind ced2k link k file the app downloadqueue add file link to download p link get file link the prefs get cat count 0 0 m cattabs get cur sel else delete p link throw c string t bad link delete p link catch c string error tchar sz buffer 200 sntprintf sz buffer arrsize sz buffer get res string ids err invalidlink error c string str error str error format get res string ids err linkerror sz buffer afx message box str error return str tok str links tokenize t t n r cur pos c resizable dialog onok cdirectdownloaddlg cstring strlinks getdlgitem idc_elink getwindowtext strlinks curpos cstring strtok strlinks _t curpos strtok isempty strtok _t strtok _t ced2klink plink ced2klink createlinkfromurl strtok plink plink getkind ced2klink kfile theapp addfilelinktodownload plink getfilelink theprefs getcatcount m_cattabs getcursel plink cstring _t plink cstring szbuffer _sntprintf szbuffer szbuffer getresstring ids_err_invalidlink cstring strerror strerror getresstring ids_err_linkerror szbuffer afxmessagebox strerror strtok strlinks _t curpos cresizabledialog void c direct download dlg on en killfocus elink c string str links get dlg item idc elink get window text str links if str links is empty str links find t n 1 return str links replace t n t r n str links replace t r r t r get dlg item idc elink set window text str links cdirectdownloaddlg onenkillfocuselink cstring strlinks getdlgitem idc_elink getwindowtext strlinks strlinks isempty strlinks _t strlinks _t _t strlinks _t _t getdlgitem idc_elink setwindowtext strlinks void c direct download dlg on en update elink update controls cdirectdownloaddlg onenupdateelink updatecontrols m nsourcetype 0 m pfile null m_nsourcetype m_pfile c add source dlg c add source dlg caddsourcedlg caddsourcedlg void c add source dlg set file c part file p file m pfile p file caddsourcedlg setfile cpartfile pfile m_pfile pfile void c add source dlg do data exchange c data exchange pdx c resizable dialog do data exchange pdx ddx radio pdx idc rsrc m nsourcetype caddsourcedlg dodataexchange cdataexchange cresizabledialog dodataexchange ddx_radio idc_rsrc m_nsourcetype bool c add source dlg on init dialog c resizable dialog on init dialog init window styles this add anchor idc source type top left bottom right add anchor idc edit10 top left top right add anchor idok bottom right add anchor idc button1 bottom right add anchor idcancel bottom right if m pfile set window text m pfile get file name localize set dlg item text idc button1 get res string ids add set dlg item text idcancel get res string ids cancel set dlg item text idc rsrc get res string ids sourceclient set dlg item text idc source type get res string ids meta srctype set dlg item text idc rurl get res string ids sv url set dlg item text idc uip get res string ids usersip set dlg item text idc port get res string ids port enable save restore t add source dlg on bn clicked radio1 return false return false we changed the focus caddsourcedlg oninitdialog cresizabledialog oninitdialog initwindowstyles addanchor idc_source_type top_left bottom_right addanchor idc_edit10 top_left top_right addanchor bottom_right addanchor idc_button1 bottom_right addanchor bottom_right m_pfile setwindowtext m_pfile getfilename setdlgitemtext idc_button1 getresstring ids_add setdlgitemtext getresstring ids_cancel setdlgitemtext idc_rsrc getresstring ids_sourceclient setdlgitemtext idc_source_type getresstring ids_meta_srctype setdlgitemtext idc_rurl getresstring ids_sv_url setdlgitemtext idc_uip getresstring ids_usersip setdlgitemtext idc_port getresstring ids_port enablesaverestore _t addsourcedlg onbnclickedradio1 void c add source dlg on bn clicked radio1 m nsourcetype 0 get dlg item idc edit2 enable window true get dlg item idc edit3 enable window true get dlg item idc edit10 enable window false get dlg item idc edit2 set focus caddsourcedlg onbnclickedradio1 m_nsourcetype getdlgitem idc_edit2 enablewindow getdlgitem idc_edit3 enablewindow getdlgitem idc_edit10 enablewindow getdlgitem idc_edit2 setfocus void c add source dlg on bn clicked radio4 m nsourcetype 1 get dlg item idc edit2 enable window false get dlg item idc edit3 enable window false get dlg item idc edit10 enable window true get dlg item idc edit10 set focus caddsourcedlg onbnclickedradio4 m_nsourcetype getdlgitem idc_edit2 enablewindow getdlgitem idc_edit3 enablewindow getdlgitem idc_edit10 enablewindow getdlgitem idc_edit10 setfocus void c add source dlg on bn clicked button1 if m pfile return switch m nsourcetype case 0 c string sip get dlg item idc edit2 get window text sip if sip is empty return if the port is specified with the ip ignore any possible specified port in the port control uint16 port int i colon sip find t if i colon 1 port uint16 tstoi sip mid i colon 1 sip sip left i colon else bool b translated false port uint16 get dlg item int idc edit3 b translated false if b translated return uint32 ip uses conversion if ip inet addr t2ca sip inaddr none tcscmp sip t 255 255 255 255 0 ip 0 if is goodip port ip port c up down client toadd new c up down client m pfile port ntohl ip 0 0 toadd set source from sf passive the app downloadqueue check and add source m pfile toadd break case 1 c string strurl get dlg item idc edit10 get window text strurl if strurl is empty tchar sz scheme internet max scheme length tchar sz host name internet max host name length tchar sz url path internet max path length tchar sz user name internet max user name length tchar sz password internet max password length tchar sz extra info internet max url length url components url 0 url dw struct size sizeof url url lpsz scheme sz scheme url dw scheme length arrsize sz scheme url lpsz host name sz host name url dw host name length arrsize sz host name url lpsz user name sz user name url dw user name length arrsize sz user name url lpsz password sz password url dw password length arrsize sz password url lpsz url path sz url path url dw url path length arrsize sz url path url lpsz extra info sz extra info url dw extra info length arrsize sz extra info if internet crack url strurl 0 0 url url dw host name length 0 s unresolved hostname hostname new s unresolved hostname hostname strurl strurl hostname str hostname sz host name the app downloadqueue add to resolved m pfile hostname delete hostname break caddsourcedlg onbnclickedbutton1 m_pfile m_nsourcetype cstring getdlgitem idc_edit2 getwindowtext isempty icolon _t icolon _tstoi icolon icolon btranslated getdlgitemint idc_edit3 btranslated btranslated uses_conversion inet_addr inaddr_none _tcscmp _t isgoodipport cupdownclient cupdownclient m_pfile setsourcefrom sf_passive theapp checkandaddsource m_pfile cstring getdlgitem idc_edit10 getwindowtext isempty szscheme internet_max_scheme_length szhostname internet_max_host_name_length szurlpath internet_max_path_length szusername internet_max_user_name_length szpassword internet_max_password_length szextrainfo internet_max_url_length url_components dwstructsize lpszscheme szscheme dwschemelength szscheme lpszhostname szhostname dwhostnamelength szhostname lpszusername szusername dwusernamelength szusername lpszpassword szpassword dwpasswordlength szpassword lpszurlpath szurlpath dwurlpathlength szurlpath lpszextrainfo szextrainfo dwextrainfolength szextrainfo internetcrackurl dwhostnamelength sunresolvedhostname sunresolvedhostname strhostname szhostname theapp addtoresolved m_pfile void c add source dlg on bn clicked ok on bn clicked button1 onok caddsourcedlg onbnclickedok onbnclickedbutton1 bool cx image gray scale if p dib return false if head bi bit count 8 rgbquad ppal get palette int gray converts the colors to gray use the blue channel only for dword i 0 i head bi clr used i gray int rgb2gray ppal i rgb red ppal i rgb green ppal i rgb blue ppal i rgb blue byte gray preserve transparency if info n bkgnd index 1 info n bkgnd index ppal info n bkgnd index rgb blue create a real 8 bit gray scale image if head bi bit count 8 byte img info p image for dword i 0 i head bi size image i img i ppal img i rgb blue set gray palette transform to 8 bit gray scale if head bi bit count 4 head bi bit count 1 cx image ima head bi width head bi height 8 info dw type ima set gray palette byte img ima get bits long l ima get eff width for long y 0 y head bi height y for long x 0 x head bi width x img x y l ppal get pixel index x y rgb blue transfer ima else from rgb to 8 bit gray scale byte i src info p image cx image ima head bi width head bi height 8 info dw type ima set gray palette if cximage support alpha ima alpha copy this endif cximage support alpha byte img ima get bits long l8 ima get eff width long l head bi width 3 for long y 0 y head bi height y for long x 0 x8 0 x l x 3 x8 img x8 y l8 byte rgb2gray i src x 2 i src x 1 i src x 0 i src info dw eff width transfer ima return true cximage grayscale pdib bibitcount getpalette biclrused rgbred rgbgreen rgbblue rgbblue nbkgndindex nbkgndindex nbkgndindex rgbblue bibitcount pimage bisizeimage rgbblue setgraypalette bibitcount bibitcount cximage biwidth biheight dwtype setgraypalette getbits geteffwidth biheight biwidth getpixelindex rgbblue isrc pimage cximage biwidth biheight dwtype setgraypalette cximage_support_alpha alphacopy cximage_support_alpha getbits geteffwidth biwidth biheight isrc isrc isrc isrc dweffwidth bool cx image flip if p dib return false cx image imatmp new cx image this false false true if imatmp return false byte i src i dst i src info p image head bi height 1 info dw eff width i dst imatmp info p image for long y 0 y head bi height y memcpy i dst i src info dw eff width i src info dw eff width i dst info dw eff width if cximage support alpha imatmp alpha flip endif cximage support alpha transfer imatmp delete imatmp return true cximage pdib cximage cximage isrc idst isrc pimage biheight dweffwidth idst pimage biheight idst isrc dweffwidth isrc dweffwidth idst dweffwidth cximage_support_alpha alphaflip cximage_support_alpha bool cx image mirror if p dib return false cx image imatmp new cx image this false false true if imatmp return false byte i src i dst long wdt head bi width 1 head bi bit count 24 3 1 i src info p image wdt i dst imatmp info p image long x y switch head bi bit count case 24 for y 0 y head bi height y for x 0 x wdt x 3 i dst x i src x i dst x 1 i src x 1 i dst x 2 i src x 2 i src info dw eff width i dst info dw eff width break case 8 for y 0 y head bi height y for x 0 x wdt x i dst x i src x i src info dw eff width i dst info dw eff width break default for y 0 y head bi height y for x 0 x wdt x imatmp set pixel index x y get pixel index wdt x y if cximage support alpha imatmp alpha mirror endif cximage support alpha transfer imatmp delete imatmp return true cximage pdib cximage cximage isrc idst biwidth bibitcount isrc pimage idst pimage bibitcount biheight idst isrc idst isrc idst isrc isrc dweffwidth idst dweffwidth biheight idst isrc isrc dweffwidth idst dweffwidth biheight setpixelindex getpixelindex cximage_support_alpha alphamirror cximage_support_alpha bool cx image negative if p dib return false if head bi bit count 8 if is gray scale grayscale selection if p selection for long y info r selection box bottom y info r selection box top y for long x info r selection box left x info r selection box right x if cximage support selection if selection is inside x y endif cximage support selection set pixel index x y byte 255 get pixel index x y else for long y 0 y head bi height y for long x 0 x head bi width x set pixel index x y byte 255 get pixel index x y else palette full image rgbquad ppal get palette for dword i 0 i head bi clr used i ppal i rgb blue byte 255 ppal i rgb blue ppal i rgb green byte 255 ppal i rgb green ppal i rgb red byte 255 ppal i rgb red else if p selection null rgb full image byte i src info p image for unsigned long i 0 i head bi size image i i src byte i src i src else rgb with selection rgbquad color for long y info r selection box bottom y info r selection box top y for long x info r selection box left x info r selection box right x if cximage support selection if selection is inside x y endif cximage support selection color get pixel color x y color rgb red byte 255 color rgb red color rgb green byte 255 color rgb green color rgb blue byte 255 color rgb blue set pixel color x y color dp invert transparent color too info n bkgnd color rgb blue byte 255 info n bkgnd color rgb blue info n bkgnd color rgb green byte 255 info n bkgnd color rgb green info n bkgnd color rgb red byte 255 info n bkgnd color rgb red return true cximage pdib bibitcount isgrayscale pselection rselectionbox rselectionbox rselectionbox rselectionbox cximage_support_selection selectionisinside cximage_support_selection setpixelindex getpixelindex biheight biwidth setpixelindex getpixelindex getpalette biclrused rgbblue rgbblue rgbgreen rgbgreen rgbred rgbred pselection isrc pimage bisizeimage isrc isrc isrc rselectionbox rselectionbox rselectionbox rselectionbox cximage_support_selection selectionisinside cximage_support_selection getpixelcolor rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue setpixelcolor nbkgndcolor rgbblue nbkgndcolor rgbblue nbkgndcolor rgbgreen nbkgndcolor rgbgreen nbkgndcolor rgbred nbkgndcolor rgbred bool cx image rotate left cx image i dst if p dib return false long new width get height long new height get width cx image img dest img dest copy info this img dest create new width new height get bpp get type img dest set palette get palette long x x2 y dlineup speedy rotate for bw images robert abram if head bi bit count 1 byte sbits dbits dbitsmax bitpos nrow srcdisp div t div r byte bsrc get bits bdest img dest get bits dbitsmax bdest img dest head bi size image 1 dlineup 8 img dest info dw eff width img dest head bi width img dest clear 0 for y 0 y head bi height y figure out the column we are going to be copying to div r div y dlineup 8 set bit pos of src column byte bitpos 1 div r rem srcdisp bsrc y info dw eff width for x 0 x long info dw eff width x get source bits sbits srcdisp x get destination column nrow bdest x 8 img dest info dw eff width img dest info dw eff width 1 div r quot for long z 0 z 8 z get destination byte dbits nrow z img dest info dw eff width if dbits bdest dbits dbitsmax break if sbits 128 z dbits bitpos else for x 0 x new width x info n progress long 100 x new width anatoly ivasyuk x2 new width x 1 for y 0 y new height y if head bi clr used 0 rgb img dest set pixel color x y get pixel color y x2 else palette img dest set pixel index x y get pixel index y x2 if cximage support alpha if alpha is valid img dest alpha create for x 0 x new width x x2 new width x 1 for y 0 y new height y img dest alpha set x y alpha get y x2 endif cximage support alpha select the destination if i dst i dst transfer img dest else transfer img dest return true cximage rotateleft cximage idst pdib newwidth getheight newheight getwidth cximage imgdest imgdest copyinfo imgdest newwidth newheight getbpp gettype imgdest setpalette getpalette bibitcount div_t div_r getbits imgdest getbits imgdest bisizeimage imgdest dweffwidth imgdest biwidth imgdest biheight div_r div_r dweffwidth dweffwidth imgdest dweffwidth imgdest dweffwidth div_r imgdest dweffwidth newwidth nprogress newwidth newwidth newheight biclrused imgdest setpixelcolor getpixelcolor imgdest setpixelindex getpixelindex cximage_support_alpha alphaisvalid imgdest alphacreate newwidth newwidth newheight imgdest alphaset alphaget cximage_support_alpha idst idst imgdest imgdest bool cx image rotate right cx image i dst if p dib return false long new width get height long new height get width cx image img dest img dest copy info this img dest create new width new height get bpp get type img dest set palette get palette long x y y2 speedy rotate for bw images robert abram if head bi bit count 1 byte sbits dbits dbitsmax bitpos nrow srcdisp div t div r byte bsrc get bits bdest img dest get bits dbitsmax bdest img dest head bi size image 1 img dest clear 0 for y 0 y head bi height y figure out the column we are going to be copying to div r div y 8 set bit pos of src column byte bitpos 128 div r rem srcdisp bsrc y info dw eff width for x 0 x long info dw eff width x get source bits sbits srcdisp x get destination column nrow bdest img dest head bi height 1 x 8 img dest info dw eff width div r quot for long z 0 z 8 z get destination byte dbits nrow z img dest info dw eff width if dbits bdest dbits dbitsmax break if sbits 128 z dbits bitpos else for y 0 y new height y info n progress long 100 y new height anatoly ivasyuk y2 new height y 1 for x 0 x new width x if head bi clr used 0 rgb img dest set pixel color x y get pixel color y2 x else palette img dest set pixel index x y get pixel index y2 x if cximage support alpha if alpha is valid img dest alpha create for y 0 y new height y y2 new height y 1 for x 0 x new width x img dest alpha set x y alpha get y2 x endif cximage support alpha select the destination if i dst i dst transfer img dest else transfer img dest return true cximage rotateright cximage idst pdib newwidth getheight newheight getwidth cximage imgdest imgdest copyinfo imgdest newwidth newheight getbpp gettype imgdest setpalette getpalette bibitcount div_t div_r getbits imgdest getbits imgdest bisizeimage imgdest biheight div_r div_r dweffwidth dweffwidth imgdest biheight imgdest dweffwidth div_r imgdest dweffwidth newheight nprogress newheight newheight newwidth biclrused imgdest setpixelcolor getpixelcolor imgdest setpixelindex getpixelindex cximage_support_alpha alphaisvalid imgdest alphacreate newheight newheight newwidth imgdest alphaset alphaget cximage_support_alpha idst idst imgdest imgdest bool cx image rotate float angle cx image i dst if p dib return false id filter rotate cpp v 1 10 2000 12 18 22 42 53 uzadow exp copyright c 1996 1998 ulrich von zadow negative the angle because the y axis is negative double ang angle acos float 0 90 int new width new height int n width get width int n height get height double cos angle cos ang double sin angle sin ang calculate the size of the new bitmap point p1 0 0 point p2 n width 0 point p3 0 n height point p4 n width 1 n height point newp1 newp2 newp3 newp4 left top right top left bottom right bottom newp1 x p1 x newp1 y p1 y newp2 x long p2 x cos angle p2 y sin angle newp2 y long p2 x sin angle p2 y cos angle newp3 x long p3 x cos angle p3 y sin angle newp3 y long p3 x sin angle p3 y cos angle newp4 x long p4 x cos angle p4 y sin angle newp4 y long p4 x sin angle p4 y cos angle left top x min min newp1 x newp2 x min newp3 x newp4 x left top y min min newp1 y newp2 y min newp3 y newp4 y right bottom x max max newp1 x newp2 x max newp3 x newp4 x right bottom y max max newp1 y newp2 y max newp3 y newp4 y left bottom x left top x left bottom y right bottom y right top x right bottom x right top y left top y new width right top x left top x new height left bottom y left top y cx image img dest img dest copy info this img dest create new width new height get bpp get type img dest set palette get palette if cximage support alpha if alpha is valid mta fix for rotation problem when the image has an alpha channel img dest alpha create img dest alpha clear endif cximage support alpha int x y newx newy oldx oldy if head bi clr used 0 rgb for y left top y newy 0 y left bottom y y newy info n progress long 100 newy new height if info n escape break for x left top x newx 0 x right top x x newx oldx long x cos angle y sin angle 0 5 oldy long y cos angle x sin angle 0 5 img dest set pixel color newx newy get pixel color oldx oldy if cximage support alpha img dest alpha set newx newy alpha get oldx oldy mta copy the alpha value endif cximage support alpha else palette for y left top y newy 0 y left bottom y y newy info n progress long 100 newy new height if info n escape break for x left top x newx 0 x right top x x newx oldx long x cos angle y sin angle 0 5 oldy long y cos angle x sin angle 0 5 img dest set pixel index newx newy get pixel index oldx oldy if cximage support alpha img dest alpha set newx newy alpha get oldx oldy mta copy the alpha value endif cximage support alpha select the destination if i dst i dst transfer img dest else transfer img dest return true cximage cximage idst pdib filterrotate newwidth newheight nwidth getwidth nheight getheight cos_angle sin_angle nwidth nheight nwidth nheight lefttop righttop leftbottom rightbottom cos_angle sin_angle sin_angle cos_angle cos_angle sin_angle sin_angle cos_angle cos_angle sin_angle sin_angle cos_angle lefttop lefttop rightbottom rightbottom leftbottom lefttop leftbottom rightbottom righttop rightbottom righttop lefttop newwidth righttop lefttop newheight leftbottom lefttop cximage imgdest imgdest copyinfo imgdest newwidth newheight getbpp gettype imgdest setpalette getpalette cximage_support_alpha alphaisvalid imgdest alphacreate imgdest alphaclear cximage_support_alpha biclrused lefttop leftbottom nprogress newheight nescape lefttop righttop cos_angle sin_angle cos_angle sin_angle imgdest setpixelcolor getpixelcolor cximage_support_alpha imgdest alphaset alphaget cximage_support_alpha lefttop leftbottom nprogress newheight nescape lefttop righttop cos_angle sin_angle cos_angle sin_angle imgdest setpixelindex getpixelindex cximage_support_alpha imgdest alphaset alphaget cximage_support_alpha idst idst imgdest imgdest bool cx image rotate180 cx image i dst if p dib return false long wid get width long ht get height cx image img dest img dest copy info this img dest create wid ht get bpp get type img dest set palette get palette if cximage support alpha if alpha is valid img dest alpha create endif cximage support alpha long x y y2 for y 0 y ht y info n progress long 100 y ht anatoly ivasyuk y2 ht y 1 for x 0 x wid x if head bi clr used 0 rgb img dest set pixel color wid x 1 y2 get pixel color x y else palette img dest set pixel index wid x 1 y2 get pixel index x y if cximage support alpha if alpha is valid img dest alpha set wid x 1 y2 alpha get x y endif cximage support alpha select the destination if i dst i dst transfer img dest else transfer img dest return true cximage cximage idst pdib getwidth getheight cximage imgdest imgdest copyinfo imgdest getbpp gettype imgdest setpalette getpalette cximage_support_alpha alphaisvalid imgdest alphacreate cximage_support_alpha nprogress biclrused imgdest setpixelcolor getpixelcolor imgdest setpixelindex getpixelindex cximage_support_alpha alphaisvalid imgdest alphaset alphaget cximage_support_alpha idst idst imgdest imgdest bool cx image resample long newx long newy int mode cx image i dst if newx 0 newy 0 return false if head bi width newx head bi height newy if i dst i dst copy this return true float x scale y scale fx fy x scale float head bi width float newx y scale float head bi height float newy cx image new image new image copy info this new image create newx newy head bi bit count get type new image set palette get palette if new image is valid return false if head bi width newx head bi height newy transfer new image return true switch mode case 1 nearest pixel for long y 0 y newy y info n progress long 100 y newy if info n escape break fy y y scale for long x 0 x newx x fx x x scale new image set pixel color x y get pixel color long fx long fy break case 2 bicubic interpolation by blake l carlson blake carlson at uiowa dot edu float f x f y a b rr gg bb r1 r2 int i x i y xx yy rgbquad rgb for long y 0 y newy y info n progress long 100 y newy if info n escape break f y float y y scale i y int floor f y a f y float floor f y for long x 0 x newx x f x float x x scale i x int floor f x b f x float floor f x rr gg bb 0 0f for int m 1 m 3 m r1 b3spline float m a for int n 1 n 3 n r2 b3spline 1 0f float n b xx i x n 2 yy i y m 2 if xx 0 xx 0 if yy 0 yy 0 if xx head bi width xx head bi width 1 if yy head bi height yy head bi height 1 rgb get pixel color xx yy rr rgb rgb red r1 r2 gg rgb rgb green r1 r2 bb rgb rgb blue r1 r2 new image set pixel color x y rgb rr gg bb break default bilinear interpolation if head bi width newx head bi height newy head bi bit count 24 1999 steve mc mahon steve dogma demon co uk long ifx ify ifx1 ify1 xmax ymax float ir1 ir2 ig1 ig2 ib1 ib2 dx dy byte r g b rgbquad rgb1 rgb2 rgb3 rgb4 xmax head bi width 1 ymax head bi height 1 for long y 0 y newy y info n progress long 100 y newy if info n escape break fy y y scale ify int fy ify1 min ymax ify 1 dy fy ify for long x 0 x newx x fx x x scale ifx int fx ifx1 min xmax ifx 1 dx fx ifx interpolate using the four nearest pixels in the source if head bi clr used rgb1 get palette color get pixel index ifx ify rgb2 get palette color get pixel index ifx1 ify rgb3 get palette color get pixel index ifx ify1 rgb4 get palette color get pixel index ifx1 ify1 else byte i dst i dst info p image ify info dw eff width ifx 3 rgb1 rgb blue i dst rgb1 rgb green i dst rgb1 rgb red i dst i dst info p image ify info dw eff width ifx1 3 rgb2 rgb blue i dst rgb2 rgb green i dst rgb2 rgb red i dst i dst info p image ify1 info dw eff width ifx 3 rgb3 rgb blue i dst rgb3 rgb green i dst rgb3 rgb red i dst i dst info p image ify1 info dw eff width ifx1 3 rgb4 rgb blue i dst rgb4 rgb green i dst rgb4 rgb red i dst interplate in x direction ir1 rgb1 rgb red 1 dy rgb3 rgb red dy ig1 rgb1 rgb green 1 dy rgb3 rgb green dy ib1 rgb1 rgb blue 1 dy rgb3 rgb blue dy ir2 rgb2 rgb red 1 dy rgb4 rgb red dy ig2 rgb2 rgb green 1 dy rgb4 rgb green dy ib2 rgb2 rgb blue 1 dy rgb4 rgb blue dy interpolate in y r byte ir1 1 dx ir2 dx g byte ig1 1 dx ig2 dx b byte ib1 1 dx ib2 dx set output new image set pixel color x y rgb r g b else high resolution shrink thanks to henrik stellmann henrik stellmann volleynet de const long accuracy 1000 long i j index for fa value long x y coordinates in source image byte p source byte p dest new image info p image long na accu new long 3 newx 3 long na carry new long 3 newx 3 long na temp long n weightx n weighty float f endx long n scale long accuracy x scale y scale memset na accu 0 sizeof long 3 newx memset na carry 0 sizeof long 3 newx int u v 0 coordinates in dest image float f endy y scale 1 0f for y 0 y head bi height y info n progress long 100 y head bi height anatoly ivasyuk if info n escape break p source info p image y info dw eff width u i 0 f endx x scale 1 0f if float y f endy complete source row goes into dest row for x 0 x head bi width x if float x f endx complete source pixel goes into dest pixel for j 0 j 3 j na accu i j p source accuracy else source pixel is splitted for 2 dest pixels n weightx long float x f endx accuracy for j 0 j 3 j na accu i accuracy n weightx p source na accu 3 i n weightx p source f endx x scale u else source row is splitted for 2 dest rows n weighty long float y f endy accuracy for x 0 x head bi width x if float x f endx complete source pixel goes into 2 pixel for j 0 j 3 j na accu i j accuracy n weighty p source na carry i j n weighty p source else source pixel is splitted for 4 dest pixels n weightx int float x f endx accuracy for j 0 j 3 j na accu i accuracy n weighty accuracy n weightx p source accuracy p dest byte na accu i n scale na carry i n weighty accuracy n weightx p source accuracy na accu i 3 accuracy n weighty n weightx p source accuracy na carry i 3 n weighty n weightx p source accuracy i p source f endx x scale u if u newx possibly not completed due to rounding errors for j 0 j 3 j p dest byte na accu i n scale na temp na carry na carry na accu na accu na temp memset na carry 0 sizeof int 3 need only to set first pixel zero p dest new image info p image v new image info dw eff width f endy y scale if v newy possibly not completed due to rounding errors for i 0 i 3 newx i p dest byte na accu i n scale delete na accu delete na carry if cximage support alpha if alpha is valid new image alpha create for long y 0 y newy y fy y y scale for long x 0 x newx x fx x x scale new image alpha set x y alpha get long fx long fy endif cximage support alpha select the destination if i dst i dst transfer new image else transfer new image return true cximage cximage idst biwidth biheight idst idst xscale yscale xscale biwidth yscale biheight cximage newimage newimage copyinfo newimage bibitcount gettype newimage setpalette getpalette newimage isvalid biwidth biheight newimage nprogress nescape yscale xscale newimage setpixelcolor getpixelcolor f_x f_y i_x i_y nprogress nescape f_y yscale i_y f_y f_y f_y f_x xscale i_x f_x f_x f_x i_x i_y biwidth biwidth biheight biheight getpixelcolor rgbred rgbgreen rgbblue newimage setpixelcolor biwidth biheight bibitcount mcmahon biwidth biheight nprogress nescape yscale xscale biclrused getpalettecolor getpixelindex getpalettecolor getpixelindex getpalettecolor getpixelindex getpalettecolor getpixelindex idst idst pimage dweffwidth rgbblue idst rgbgreen idst rgbred idst idst pimage dweffwidth rgbblue idst rgbgreen idst rgbred idst idst pimage dweffwidth rgbblue idst rgbgreen idst rgbred idst idst pimage dweffwidth rgbblue idst rgbgreen idst rgbred idst rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue newimage setpixelcolor favalue psource pdest newimage pimage naaccu nacarry natemp nweightx nweighty fendx nscale xscale yscale naaccu nacarry fendy yscale biheight nprogress biheight nescape psource pimage dweffwidth fendx xscale fendy biwidth fendx naaccu psource nweightx fendx naaccu nweightx psource naaccu nweightx psource fendx xscale nweighty fendy biwidth fendx naaccu nweighty psource nacarry nweighty psource nweightx fendx naaccu nweighty nweightx psource pdest naaccu nscale nacarry nweighty nweightx psource naaccu nweighty nweightx psource nacarry nweighty nweightx psource psource fendx xscale pdest naaccu nscale natemp nacarry nacarry naaccu naaccu natemp nacarry pdest newimage pimage newimage dweffwidth fendy yscale pdest naaccu nscale naaccu nacarry cximage_support_alpha alphaisvalid newimage alphacreate yscale xscale newimage alphaset alphaget cximage_support_alpha idst idst newimage newimage bool cx image decrease bpp dword nbit bool errordiffusion rgbquad ppal if p dib return false if head bi bit count nbit return false if head bi bit count nbit return true long er eg eb rgbquad c ce cx image tmp tmp copy info this tmp create head bi width head bi height word nbit info dw type if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this endif cximage support alpha switch tmp head bi bit count case 1 if ppal tmp set palette ppal 16 else tmp set palette color 0 0 0 0 tmp set palette color 1 255 255 255 break case 4 if ppal tmp set palette ppal 16 else tmp set std palette break case 8 if ppal tmp set palette ppal else tmp set std palette break default return false for long y 0 y head bi height y if info n escape break info n progress long 100 y head bi height for long x 0 x head bi width x if errordiffusion tmp set pixel color x y get pixel color x y else c get pixel color x y tmp set pixel color x y c ce tmp get pixel color x y er long c rgb red long ce rgb red eg long c rgb green long ce rgb green eb long c rgb blue long ce rgb blue c get pixel color x 1 y c rgb red byte min 255l max 0l long c rgb red er 7 16 c rgb green byte min 255l max 0l long c rgb green eg 7 16 c rgb blue byte min 255l max 0l long c rgb blue eb 7 16 set pixel color x 1 y c int coeff for int i 1 i 2 i switch i case 1 coeff 2 break case 0 coeff 4 break case 1 coeff 1 break c get pixel color x i y 1 c rgb red byte min 255l max 0l long c rgb red er coeff 16 c rgb green byte min 255l max 0l long c rgb green eg coeff 16 c rgb blue byte min 255l max 0l long c rgb blue eb coeff 16 set pixel color x i y 1 c if head bi bit count 1 tmp set palette color 0 0 0 0 tmp set palette color 1 255 255 255 transfer tmp return true cximage decreasebpp pdib bibitcount bibitcount cximage copyinfo biwidth biheight dwtype cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy cximage_support_alpha bibitcount setpalette setpalettecolor setpalettecolor setpalette setstdpalette setpalette setstdpalette biheight nescape nprogress biheight biwidth setpixelcolor getpixelcolor getpixelcolor setpixelcolor getpixelcolor rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue getpixelcolor rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue setpixelcolor getpixelcolor rgbred rgbred rgbgreen rgbgreen rgbblue rgbblue setpixelcolor bibitcount setpalettecolor setpalettecolor bool cx image increase bpp dword nbit if p dib return false switch nbit case 4 if head bi bit count 4 return true if head bi bit count 4 return false cx image tmp tmp copy info this tmp create head bi width head bi height 4 info dw type tmp set palette get palette get num colors if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this endif cximage support alpha for long y 0 y head bi height y if info n escape break for long x 0 x head bi width x tmp set pixel index x y get pixel index x y transfer tmp return true case 8 if head bi bit count 8 return true if head bi bit count 8 return false cx image tmp tmp copy info this tmp create head bi width head bi height 8 info dw type tmp set palette get palette get num colors if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this endif cximage support alpha for long y 0 y head bi height y if info n escape break for long x 0 x head bi width x tmp set pixel index x y get pixel index x y transfer tmp return true case 24 if head bi bit count 24 return true if head bi bit count 24 return false cx image tmp tmp copy info this tmp create head bi width head bi height 24 info dw type if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this if alpha palette is valid alpha is valid tmp alpha create endif cximage support alpha for long y 0 y head bi height y if info n escape break for long x 0 x head bi width x tmp set pixel color x y get pixel color x y true transfer tmp return true return false cximage increasebpp pdib bibitcount bibitcount cximage copyinfo biwidth biheight dwtype setpalette getpalette getnumcolors cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy cximage_support_alpha biheight nescape biwidth setpixelindex getpixelindex bibitcount bibitcount cximage copyinfo biwidth biheight dwtype setpalette getpalette getnumcolors cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy cximage_support_alpha biheight nescape biwidth setpixelindex getpixelindex bibitcount bibitcount cximage copyinfo biwidth biheight dwtype cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy alphapaletteisvalid alphaisvalid alphacreate cximage_support_alpha biheight nescape biwidth setpixelcolor getpixelcolor bool cx image dither long method if p dib return false if head bi bit count 1 return true switch method case 1 multi level ordered dithering by kenny hoff oct 12 1995 define num rows 4 define num cols 4 define num intensity levels 2 define num rows less one num rows 1 define num cols less one num cols 1 define rowsx cols num rows num cols define max intensity val 255 define max dither intensity val num rows num cols num intensity levels 1 int dither matrix num rows num cols 0 8 2 10 12 4 14 6 3 11 1 9 15 7 13 5 unsigned char intensity num intensity levels 0 1 2 levels b w unsigned char intensity num intensity levels 0 255 2 levels unsigned char intensity num intensity levels 0 127 255 3 levels unsigned char intensity num intensity levels 0 85 170 255 4 levels unsigned char intensity num intensity levels 0 63 127 191 255 5 levels unsigned char intensity num intensity levels 0 51 102 153 204 255 6 levels unsigned char intensity num intensity levels 0 42 85 127 170 213 255 7 levels unsigned char intensity num intensity levels 0 36 73 109 145 182 219 255 8 levels int dither intensity dither matrix intensity offset device intensity unsigned char dither value gray scale cx image tmp head bi width head bi height 1 info dw type if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this endif cximage support alpha for long y 0 y head bi height y info n progress long 100 y head bi height if info n escape break for long x 0 x head bi width x device intensity get pixel index x y dither intensity device intensity max dither intensity val max intensity val dither matrix intensity dither intensity rowsx cols offset dither intensity rowsx cols if dither matrix y num rows less one x num cols less one dither matrix intensity dither value intensity 1 offset else dither value intensity 0 offset tmp set pixel index x y dither value tmp set palette color 0 0 0 0 tmp set palette color 1 255 255 255 transfer tmp break default floyd steinberg error diffusion thanks to steve mc mahon long error nlevel coeff byte level gray scale cx image tmp head bi width head bi height 1 info dw type if cximage support selection tmp selection copy this endif cximage support selection if cximage support alpha tmp alpha copy this endif cximage support alpha for long y 0 y head bi height y info n progress long 100 y head bi height if info n escape break for long x 0 x head bi width x level get pixel index x y if level 128 tmp set pixel index x y 1 error level 255 else tmp set pixel index x y 0 error level nlevel get pixel index x 1 y error 7 16 level byte min 255 max 0 int nlevel set pixel index x 1 y level for int i 1 i 2 i switch i case 1 coeff 3 break case 0 coeff 5 break case 1 coeff 1 break nlevel get pixel index x i y 1 error coeff 16 level byte min 255 max 0 int nlevel set pixel index x i y 1 level tmp set palette color 0 0 0 0 tmp set palette color 1 255 255 255 transfer tmp return true cximage pdib bibitcount numrows numcols numintensitylevels numrowslessone numrows numcolslessone numcols rowsxcols numrows numcols maxintensityval maxditherintensityval numrows numcols numintensitylevels dithermatrix numrows numcols numintensitylevels numintensitylevels numintensitylevels numintensitylevels numintensitylevels numintensitylevels numintensitylevels numintensitylevels ditherintensity dithermatrixintensity deviceintensity dithervalue grayscale cximage biwidth biheight dwtype cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy cximage_support_alpha biheight nprogress biheight nescape biwidth deviceintensity getpixelindex ditherintensity deviceintensity maxditherintensityval maxintensityval dithermatrixintensity ditherintensity rowsxcols ditherintensity rowsxcols dithermatrix numrowslessone numcolslessone dithermatrixintensity dithervalue dithervalue setpixelindex dithervalue setpalettecolor setpalettecolor mcmahon grayscale cximage biwidth biheight dwtype cximage_support_selection selectioncopy cximage_support_selection cximage_support_alpha alphacopy cximage_support_alpha biheight nprogress biheight nescape biwidth getpixelindex setpixelindex setpixelindex getpixelindex setpixelindex getpixelindex setpixelindex setpalettecolor setpalettecolor bool cx image crop long left long top long right long bottom cx image i dst if p dib return false long startx max 0l min left head bi width long endx max 0l min right head bi width long starty head bi height max 0l min top head bi height long endy head bi height max 0l min bottom head bi height if startx endx starty endy return false if startx endx long tmp startx startx endx endx tmp if starty endy long tmp starty starty endy endy tmp cx image tmp endx startx endy starty head bi bit count info dw type tmp set palette get palette head bi clr used tmp info n bkgnd index info n bkgnd index tmp info n bkgnd color info n bkgnd color switch head bi bit count case 1 case 4 for long y starty yd 0 y endy y yd info n progress long 100 y endy anatoly ivasyuk for long x startx xd 0 x endx x xd tmp set pixel index xd yd get pixel index x y break case 8 case 24 byte p dest tmp info p image byte p src info p image starty info dw eff width startx head bi bit count 3 for long y starty y endy y info n progress long 100 y endy anatoly ivasyuk memcpy p dest p src tmp info dw eff width p dest tmp info dw eff width p src info dw eff width select the destination if i dst i dst transfer tmp else transfer tmp return true cximage cximage idst pdib biwidth biwidth biheight biheight biheight biheight cximage bibitcount dwtype setpalette getpalette biclrused nbkgndindex nbkgndindex nbkgndcolor nbkgndcolor bibitcount nprogress setpixelindex getpixelindex pdest pimage psrc pimage dweffwidth bibitcount nprogress pdest psrc dweffwidth pdest dweffwidth psrc dweffwidth idst idst bool cx image skew float xgain float ygain long xpivot long ypivot if p dib return false long nx ny cx image tmp this p selection 0 true true long xmin xmax ymin ymax if p selection xmin info r selection box left xmax info r selection box right ymin info r selection box bottom ymax info r selection box top else xmin ymin 0 xmax head bi width ymax head bi height for long y ymin y ymax y info n progress long 100 y head bi height if info n escape break for long x xmin x xmax x if cximage support selection if selection is inside x y endif cximage support selection nx x long xgain y ypivot ny y long ygain x xpivot if head bi clr used 0 tmp set pixel color x y get pixel color nx ny else tmp set pixel index x y get pixel index nx ny if cximage support alpha tmp alpha set x y alpha get nx ny endif cximage support alpha transfer tmp return true cximage pdib cximage pselection pselection rselectionbox rselectionbox rselectionbox rselectionbox biwidth biheight nprogress biheight nescape cximage_support_selection selectionisinside cximage_support_selection biclrused setpixelcolor getpixelcolor setpixelindex getpixelindex cximage_support_alpha alphaset alphaget cximage_support_alpha float cx image b3spline float x float a b c d if x 2 0f 0 0f a 0 0f else a float pow x 2 0f 3 0f if x 1 0f 0 0f b 0 0f else b float pow x 1 0f 3 0f if x 0 c 0 0f else c float pow x 3 0f if x 1 0f 0 0f d 0 0f else d float pow x 1 0f 3 0f return 0 16666666666666666667f a 4 0f b 6 0f c 4 0f d cximage bool cx image is gray scale rgbquad ppal get palette if p dib ppal head bi clr used return false for dword i 0 i head bi clr used i if ppal i rgb blue i ppal i rgb green i ppal i rgb red i return false return true cximage isgrayscale getpalette pdib biclrused biclrused rgbblue rgbgreen rgbred dword cx image get palette size return head bi clr used sizeof rgbquad cximage getpalettesize biclrused rgbquad cx image get palette const if p dib head bi clr used return rgbquad byte p dib sizeof bitmapinfoheader return null cximage getpalette pdib biclrused pdib rgbquad cx image get palette color byte idx rgbquad rgb 0 0 0 0 if p dib head bi clr used byte i dst byte p dib sizeof bitmapinfoheader if idx head bi clr used long ldx idx sizeof rgbquad rgb rgb blue i dst ldx rgb rgb green i dst ldx rgb rgb red i dst ldx rgb rgb reserved i dst ldx return rgb cximage getpalettecolor pdib biclrused idst pdib biclrused rgbblue idst rgbgreen idst rgbred idst rgbreserved idst bool cx image get palette color byte i byte r byte g byte b rgbquad ppal get palette if ppal r ppal i rgb red g ppal i rgb green b ppal i rgb blue return true return false cximage getpalettecolor getpalette rgbred rgbgreen rgbblue byte cx image get nearest index rgbquad c if p dib null head bi clr used 0 return 0 rj check matching with the previous result if info last c isvalid long info last c long c return info last c index info last c c info last c isvalid true byte i dst byte p dib sizeof bitmapinfoheader long distance 200000 int i j 0 long k l int m int head bi clr used for i 0 l 0 i m i l sizeof rgbquad k i dst l c rgb blue i dst l c rgb blue i dst l 1 c rgb green i dst l 1 c rgb green i dst l 2 c rgb red i dst l 2 c rgb red k abs i dst l c rgb blue abs i dst l 1 c rgb green abs i dst l 2 c rgb red if k 0 j i break if k distance distance k j i info last c index j return byte j cximage getnearestindex pdib biclrused last_c_isvalid last_c last_c_index last_c last_c_isvalid idst pdib biclrused idst rgbblue idst rgbblue idst rgbgreen idst rgbgreen idst rgbred idst rgbred idst rgbblue idst rgbgreen idst rgbred last_c_index void cx image blend palette colorref cr long perc if p dib null head bi clr used 0 return byte i dst byte p dib sizeof bitmapinfoheader dword i r g b rgbquad p pal rgbquad i dst r getr value cr g getg value cr b getb value cr if perc 100 perc 100 for i 0 i head bi clr used i p pal i rgb blue byte p pal i rgb blue 100 perc b perc 100 p pal i rgb green byte p pal i rgb green 100 perc g perc 100 p pal i rgb red byte p pal i rgb red 100 perc r perc 100 cximage blendpalette pdib biclrused idst pdib ppal idst getrvalue getgvalue getbvalue biclrused ppal rgbblue ppal rgbblue ppal rgbgreen ppal rgbgreen ppal rgbred ppal rgbred void cx image set gray palette if p dib null head bi clr used 0 return rgbquad pal get palette for dword ni 0 ni head bi clr used ni pal ni rgb blue pal ni rgb green pal ni rgb red byte ni 255 head bi clr used 1 cximage setgraypalette pdib biclrused getpalette biclrused rgbblue rgbgreen rgbred biclrused void cx image set palette dword n byte r byte g byte b if r p dib null head bi clr used 0 return if g g r if b b g rgbquad ppal get palette dword m min n head bi clr used for dword i 0 i m i ppal i rgb red r i ppal i rgb green g i ppal i rgb blue b i info last c isvalid false cximage setpalette pdib biclrused getpalette biclrused rgbred rgbgreen rgbblue last_c_isvalid void cx image set palette rgbquad p pal dword n colors if p pal null p dib null head bi clr used 0 return memcpy get palette p pal min get palette size n colors sizeof rgbquad info last c isvalid false cximage setpalette ppal ncolors ppal pdib biclrused getpalette ppal getpalettesize ncolors last_c_isvalid void cx image set palette rgb color rgb dword n colors if rgb p dib null head bi clr used 0 return rgbquad ppal get palette dword m min n colors head bi clr used for dword i 0 i m i ppal i rgb red rgb i r ppal i rgb green rgb i g ppal i rgb blue rgb i b info last c isvalid false cximage setpalette rgb_color ncolors pdib biclrused getpalette ncolors biclrused rgbred rgbgreen rgbblue last_c_isvalid void cx image set palette color byte idx byte r byte g byte b byte alpha if p dib head bi clr used byte i dst byte p dib sizeof bitmapinfoheader if idx head bi clr used long ldx idx sizeof rgbquad i dst ldx byte b i dst ldx byte g i dst ldx byte r i dst ldx byte alpha info last c isvalid false cximage setpalettecolor pdib biclrused idst pdib biclrused idst idst idst idst last_c_isvalid void cx image set palette color byte idx rgbquad c if p dib head bi clr used byte i dst byte p dib sizeof bitmapinfoheader if idx head bi clr used long ldx idx sizeof rgbquad i dst ldx byte c rgb blue i dst ldx byte c rgb green i dst ldx byte c rgb red i dst ldx byte c rgb reserved info last c isvalid false cximage setpalettecolor pdib biclrused idst pdib biclrused idst rgbblue idst rgbgreen idst rgbred idst rgbreserved last_c_isvalid void cx image set palette color byte idx colorref cr if p dib head bi clr used byte i dst byte p dib sizeof bitmapinfoheader if idx head bi clr used long ldx idx sizeof rgbquad i dst ldx byte getb value cr i dst ldx byte getg value cr i dst ldx byte getr value cr i dst ldx byte 0 info last c isvalid false cximage setpalettecolor pdib biclrused idst pdib biclrused idst getbvalue idst getgvalue idst getrvalue idst last_c_isvalid void cx image swap index byte idx1 byte idx2 rgbquad ppal get palette if p dib ppal return swap the colors rgbquad temprgb get palette color idx1 set palette color idx1 get palette color idx2 set palette color idx2 temprgb swap the pixels byte idx for long y 0 y head bi height y for long x 0 x head bi width x idx get pixel index x y if idx idx1 set pixel index x y idx2 if idx idx2 set pixel index x y idx1 cximage swapindex getpalette pdib getpalettecolor setpalettecolor getpalettecolor setpalettecolor biheight biwidth getpixelindex setpixelindex setpixelindex void cx image set std palette if p dib return switch head bi bit count case 8 const byte pal256 1024 0 0 0 0 0 0 128 0 0 128 0 0 0 128 128 0 128 0 0 0 128 0 128 0 128 128 0 0 192 192 192 0 192 220 192 0 240 202 166 0 212 240 255 0 177 226 255 0 142 212 255 0 107 198 255 0 72 184 255 0 37 170 255 0 0 170 255 0 0 146 220 0 0 122 185 0 0 98 150 0 0 74 115 0 0 50 80 0 212 227 255 0 177 199 255 0 142 171 255 0 107 143 255 0 72 115 255 0 37 87 255 0 0 85 255 0 0 73 220 0 0 61 185 0 0 49 150 0 0 37 115 0 0 25 80 0 212 212 255 0 177 177 255 0 142 142 255 0 107 107 255 0 72 72 255 0 37 37 255 0 0 0 254 0 0 0 220 0 0 0 185 0 0 0 150 0 0 0 115 0 0 0 80 0 227 212 255 0 199 177 255 0 171 142 255 0 143 107 255 0 115 72 255 0 87 37 255 0 85 0 255 0 73 0 220 0 61 0 185 0 49 0 150 0 37 0 115 0 25 0 80 0 240 212 255 0 226 177 255 0 212 142 255 0 198 107 255 0 184 72 255 0 170 37 255 0 170 0 255 0 146 0 220 0 122 0 185 0 98 0 150 0 74 0 115 0 50 0 80 0 255 212 255 0 255 177 255 0 255 142 255 0 255 107 255 0 255 72 255 0 255 37 255 0 254 0 254 0 220 0 220 0 185 0 185 0 150 0 150 0 115 0 115 0 80 0 80 0 255 212 240 0 255 177 226 0 255 142 212 0 255 107 198 0 255 72 184 0 255 37 170 0 255 0 170 0 220 0 146 0 185 0 122 0 150 0 98 0 115 0 74 0 80 0 50 0 255 212 227 0 255 177 199 0 255 142 171 0 255 107 143 0 255 72 115 0 255 37 87 0 255 0 85 0 220 0 73 0 185 0 61 0 150 0 49 0 115 0 37 0 80 0 25 0 255 212 212 0 255 177 177 0 255 142 142 0 255 107 107 0 255 72 72 0 255 37 37 0 254 0 0 0 220 0 0 0 185 0 0 0 150 0 0 0 115 0 0 0 80 0 0 0 255 227 212 0 255 199 177 0 255 171 142 0 255 143 107 0 255 115 72 0 255 87 37 0 255 85 0 0 220 73 0 0 185 61 0 0 150 49 0 0 115 37 0 0 80 25 0 0 255 240 212 0 255 226 177 0 255 212 142 0 255 198 107 0 255 184 72 0 255 170 37 0 255 170 0 0 220 146 0 0 185 122 0 0 150 98 0 0 115 74 0 0 80 50 0 0 255 255 212 0 255 255 177 0 255 255 142 0 255 255 107 0 255 255 72 0 255 255 37 0 254 254 0 0 220 220 0 0 185 185 0 0 150 150 0 0 115 115 0 0 80 80 0 0 240 255 212 0 226 255 177 0 212 255 142 0 198 255 107 0 184 255 72 0 170 255 37 0 170 255 0 0 146 220 0 0 122 185 0 0 98 150 0 0 74 115 0 0 50 80 0 0 227 255 212 0 199 255 177 0 171 255 142 0 143 255 107 0 115 255 72 0 87 255 37 0 85 255 0 0 73 220 0 0 61 185 0 0 49 150 0 0 37 115 0 0 25 80 0 0 212 255 212 0 177 255 177 0 142 255 142 0 107 255 107 0 72 255 72 0 37 255 37 0 0 254 0 0 0 220 0 0 0 185 0 0 0 150 0 0 0 115 0 0 0 80 0 0 212 255 227 0 177 255 199 0 142 255 171 0 107 255 143 0 72 255 115 0 37 255 87 0 0 255 85 0 0 220 73 0 0 185 61 0 0 150 49 0 0 115 37 0 0 80 25 0 212 255 240 0 177 255 226 0 142 255 212 0 107 255 198 0 72 255 184 0 37 255 170 0 0 255 170 0 0 220 146 0 0 185 122 0 0 150 98 0 0 115 74 0 0 80 50 0 212 255 255 0 177 255 255 0 142 255 255 0 107 255 255 0 72 255 255 0 37 255 255 0 0 254 254 0 0 220 220 0 0 185 185 0 0 150 150 0 0 115 115 0 0 80 80 0 242 242 242 0 230 230 230 0 218 218 218 0 206 206 206 0 194 194 194 0 182 182 182 0 170 170 170 0 158 158 158 0 146 146 146 0 134 134 134 0 122 122 122 0 110 110 110 0 98 98 98 0 86 86 86 0 74 74 74 0 62 62 62 0 50 50 50 0 38 38 38 0 26 26 26 0 14 14 14 0 240 251 255 0 164 160 160 0 128 128 128 0 0 0 255 0 0 255 0 0 0 255 255 0 255 0 0 0 255 0 255 0 255 255 0 0 255 255 255 0 memcpy get palette pal256 1024 break case 4 const byte pal16 64 0 0 0 0 0 0 128 0 0 128 0 0 0 128 128 0 128 0 0 0 128 0 128 0 128 128 0 0 192 192 192 0 128 128 128 0 0 0 255 0 0 255 0 0 0 255 255 0 255 0 0 0 255 0 255 0 255 255 0 0 255 255 255 0 memcpy get palette pal16 64 break return cximage setstdpalette pdib bibitcount getpalette getpalette byte cx image get pixel index long x long y if p dib null head bi clr used 0 return 0 if x 0 y 0 x head bi width y head bi height if info n bkgnd index 1 return byte info n bkgnd index else return 0 if head bi bit count 8 return info p image y info dw eff width x else byte pos byte i dst info p image y info dw eff width x head bi bit count 3 if head bi bit count 4 pos byte 4 1 x 2 i dst 0x0f pos return byte i dst pos else if head bi bit count 1 pos byte 7 x 8 i dst 0x01 pos return byte i dst pos return 0 cximage getpixelindex pdib biclrused biwidth biheight nbkgndindex nbkgndindex bibitcount pimage dweffwidth idst pimage dweffwidth bibitcount bibitcount idst idst bibitcount idst idst rgbquad cx image get pixel color long x long y rgbquad rgb 0 0 0 0 rgbquad rgb info n bkgnd color mpwolski if p dib null x 0 y 0 x head bi width y head bi height if info n bkgnd index 1 if head bi bit count 24 rgb get palette color byte info n bkgnd index else rgb info n bkgnd color else if p dib rgb get pixel color 0 0 return rgb if head bi clr used rgb get palette color get pixel index x y else byte i dst info p image y info dw eff width x 3 rgb rgb blue i dst rgb rgb green i dst rgb rgb red i dst if cximage support alpha if p alpha rgb rgb reserved alpha get x y else rgb rgb reserved 0 endif cximage support alpha return rgb cximage getpixelcolor nbkgndcolor pdib biwidth biheight nbkgndindex bibitcount getpalettecolor nbkgndindex nbkgndcolor pdib getpixelcolor biclrused getpalettecolor getpixelindex idst pimage dweffwidth rgbblue idst rgbgreen idst rgbred idst cximage_support_alpha palpha rgbreserved alphaget rgbreserved cximage_support_alpha void cx image set pixel color long x long y rgbquad c bool b edit alpha if p dib null x 0 y 0 x head bi width y head bi height return if head bi clr used set pixel index x y get nearest index c else byte i dst info p image y info dw eff width x 3 i dst c rgb blue i dst c rgb green i dst c rgb red if cximage support alpha if b edit alpha alpha set x y c rgb reserved endif cximage support alpha cximage setpixelcolor beditalpha pdib biwidth biheight biclrused setpixelindex getnearestindex idst pimage dweffwidth idst rgbblue idst rgbgreen idst rgbred cximage_support_alpha beditalpha alphaset rgbreserved cximage_support_alpha void cx image set pixel index long x long y byte i if p dib null head bi clr used 0 x 0 y 0 x head bi width y head bi height return if head bi bit count 8 info p image y info dw eff width x i return else byte pos byte i dst info p image y info dw eff width x head bi bit count 3 if head bi bit count 4 pos byte 4 1 x 2 i dst 0x0f pos i dst i 0x0f pos return else if head bi bit count 1 pos byte 7 x 8 i dst 0x01 pos i dst i 0x01 pos return cximage setpixelindex pdib biclrused biwidth biheight bibitcount pimage dweffwidth idst pimage dweffwidth bibitcount bibitcount idst idst bibitcount idst idst void cx image set pixel color long x long y colorref cr set pixel color x y rg btorgbquad cr cximage setpixelcolor setpixelcolor rgbtorgbquad byte cx image get pixel gray long x long y rgbquad color get pixel color x y return byte rgb2gray color rgb red color rgb green color rgb blue cximage getpixelgray getpixelcolor rgbred rgbgreen rgbblue rgbquad cx image rg btorgbquad colorref cr rgbquad c c rgb red getr value cr get r g and b out of dword c rgb green getg value cr c rgb blue getb value cr c rgb reserved 0 return c cximage rgbtorgbquad rgbred getrvalue rgbgreen getgvalue rgbblue getbvalue rgbreserved colorref cx image rgbqua dtorgb rgbquad c return rgb c rgb red c rgb green c rgb blue cximage rgbquadtorgb rgbred rgbgreen rgbblue void cx image rg btobgr byte buffer int length if buffer head bi clr used 0 byte temp length min length int info dw eff width for int i 0 i length i 3 temp buffer i buffer i buffer i 2 buffer i 2 temp cximage rgbtobgr biclrused dweffwidth cx image cx image dword imagetype startup imagetype cximage cximage cx image cx image dword dw width dword dw height dword w bpp dword imagetype startup imagetype create dw width dw height w bpp imagetype cximage cximage dwwidth dwheight wbpp dwwidth dwheight wbpp cx image cx image const cx image src bool copypixels bool copyselection bool copyalpha startup src get type copy src copypixels copyselection copyalpha cximage cximage cximage gettype cx image cx image destroy cximage cximage cx image cx image operator const cx image isrc if this isrc copy isrc return this cximage cximage cximage void cx image create dword dw width dword dw height dword w bpp dword imagetype destroy the existing image if any destroy make sure bits per pixel is valid if w bpp 1 w bpp 1 else if w bpp 4 w bpp 4 else if w bpp 8 w bpp 8 else w bpp 24 set the correct bpp value switch w bpp case 1 head bi clr used 2 break case 4 head bi clr used 16 break case 8 head bi clr used 256 break default head bi clr used 0 set the common image informations info dw eff width w bpp dw width 31 32 4 info dw type imagetype initialize bitmapinfoheader head bi width dw width fill in width from parameter head bi height dw height fill in height from parameter head bi planes 1 must be 1 head bi bit count word w bpp from parameter head bi compression bi rgb head bi size image info dw eff width dw height head bix pels per meter 0 see setxdpi head biy pels per meter 0 see setydpi head bi clr important 0 p dib malloc get size alloc memory block to store our bitmap if p dib return null clear the palette rgbquad pal get palette if pal memset pal 0 get palette size destroy the existing selection if cximage support selection if p selection selection delete endif cximage support selection destroy the existing alpha channel if cximage support alpha if p alpha alpha delete endif cximage support alpha use our bitmap info structure to fill in first part of our dib with the bitmapinfoheader bitmapinfoheader lpbi lpbi bitmapinfoheader p dib lpbi head info p image get bits return p dib return handle to the dib cximage dwwidth dwheight wbpp wbpp wbpp wbpp wbpp wbpp wbpp wbpp wbpp biclrused biclrused biclrused biclrused dweffwidth wbpp dwwidth dwtype biwidth dwwidth biheight dwheight biplanes bibitcount wbpp bicompression bi_rgb bisizeimage dweffwidth dwheight bixpelspermeter biypelspermeter biclrimportant pdib getsize pdib getpalette getpalettesize cximage_support_selection pselection selectiondelete cximage_support_selection cximage_support_alpha palpha alphadelete cximage_support_alpha pdib pimage getbits pdib void cx image destroy free this only if it s valid and it s not a ghost if info p ghost null if p layers for long n 0 n info n num layers n delete p layers n free p layers p layers 0 if p selection free p selection p selection 0 if p alpha free p alpha p alpha 0 if p dib free p dib p dib 0 cximage pghost players nnumlayers players players players pselection pselection pselection palpha palpha palpha pdib pdib pdib void cx image clear byte bval if p dib memset info p image bval head bi size image cximage pdib pimage bisizeimage void cx image copy const cx image src bool copypixels bool copyselection bool copyalpha copy the attributes memcpy info src info sizeof cximageinfo rebuild the image create src get width src get height src get bpp src get type copy the pixels and the palette or at least copy the palette only if copypixels p dib src p dib memcpy p dib src p dib get size else set palette src get palette long n size head bi width head bi height copy the selection if copyselection src p selection if p selection free p selection p selection byte malloc n size memcpy p selection src p selection n size copy the alpha channel if copyalpha src p alpha if p alpha free p alpha p alpha byte malloc n size memcpy p alpha src p alpha n size cximage cximage getwidth getheight getbpp gettype pdib pdib pdib pdib getsize setpalette getpalette nsize biwidth biheight pselection pselection pselection pselection nsize pselection pselection nsize palpha palpha palpha palpha nsize palpha palpha nsize void cx image transfer cx image from destroy memcpy head from head sizeof bitmapinfoheader memcpy info from info sizeof cximageinfo p dib from p dib p selection from p selection p alpha from p alpha p layers from p layers memset from head 0 sizeof bitmapinfoheader memset from info 0 sizeof cximageinfo from p dib from p selection from p alpha null from p layers null cximage cximage pdib pdib pselection pselection palpha palpha players players pdib pselection palpha players bool cx image create fromargb dword dw width dword dw height byte argb array if argb array null return false if create dw width dw height 24 return false byte dst byte src argb array if cximage support alpha if alpha is valid alpha create endif cximage support alpha for long y dw height 1 y 0 y dst info p image y info dw eff width for dword x 0 x dw width x dst src 0 dst src 1 dst src 2 if cximage support alpha alpha set x y src 3 endif cximage support alpha src 4 return true cximage createfromargb dwwidth dwheight argbarray argbarray dwwidth dwheight argbarray cximage_support_alpha alphaisvalid alphacreate cximage_support_alpha dwheight pimage dweffwidth dwwidth cximage_support_alpha alphaset cximage_support_alpha long cx image get size return head bi size head bi size image get palette size cximage getsize bisize bisizeimage getpalettesize byte cx image get bits if p dib return byte p dib dword p dib get palette size return null cximage getbits pdib pdib pdib getpalettesize byte cx image get color type byte b byte head bi bit count 8 2 colortype color 1 colortype palette if cximage support alpha if alpha is valid b 4 colortype alpha endif cximage support alpha return b cximage getcolortype bibitcount colortype_color colortype_palette cximage_support_alpha alphaisvalid colortype_alpha cximage_support_alpha const char cx image get version static const char cx image version cx image 5 71 return cx image version cximage getversion cximageversion cximage cximageversion void cx image setxdpi long dpi info xdpi dpi head bix pels per meter long floor dpi 10000 0 254 0 0 5 cximage bixpelspermeter void cx image setydpi long dpi info ydpi dpi head biy pels per meter long floor dpi 10000 0 254 0 0 5 cximage biypelspermeter rgbquad cx image get trans color if head bi bit count 24 info n bkgnd index 1 return get palette color byte info n bkgnd index return info n bkgnd color cximage gettranscolor bibitcount nbkgndindex getpalettecolor nbkgndindex nbkgndcolor void cx image set flags dword flags bool b lock reserved flags if b lock reserved flags info dw flags flags 0x0000ffff else info dw flags flags cximage setflags blockreservedflags blockreservedflags dwflags dwflags bool cx image is inside long x long y return 0 y y head bi height 0 x x head bi width cximage isinside biheight biwidth void cx image startup dword imagetype init pointers p dib p selection p alpha null p layers null init structures memset head 0 sizeof bitmapinfoheader head bi size sizeof bitmapinfoheader memset info 0 sizeof cximageinfo init default attributes info dw type imagetype info n quality 75 info n alpha max 255 info n bkgnd index 1 info b enabled true setxdpi 96 setydpi 96 cximage pdib pselection palpha players bisize dwtype nquality nalphamax nbkgndindex benabled void cx image copy info const cx image src if p dib null memcpy info src info sizeof cximageinfo cximage copyinfo cximage pdib void cx image ghost cx image from if from memcpy head from head sizeof bitmapinfoheader memcpy info from info sizeof cximageinfo p dib from p dib p selection from p selection p alpha from p alpha p layers from p layers info p ghost from cximage cximage pdib pdib pselection pselection palpha palpha players players pghost void cx image bitfield2rgb byte src word redmask word greenmask word bluemask byte bpp switch bpp case 16 dword ns 3 0 0 0 compute the number of shift for each mask for int i 0 i 16 i if redmask i 0x01 ns 0 if greenmask i 0x01 ns 1 if bluemask i 0x01 ns 2 ns 1 ns 0 ns 2 ns 1 ns 0 8 ns 0 ns 1 8 ns 2 8 dword aligned width for 16 bit image long effwidth2 head bi width 1 2 4 word w long y2 y3 x2 x3 byte p info p image scan the buffer in reverse direction to avoid reallocations for long y head bi height 1 y 0 y y2 effwidth2 y y3 info dw eff width y for long x head bi width 1 x 0 x x2 2 x y2 x3 3 x y3 w word src x2 256 src 1 x2 p x3 byte w bluemask ns 0 p 1 x3 byte w greenmask ns 1 p 2 x3 byte w redmask ns 2 break case 32 dword aligned width for 32 bit image long effwidth4 head bi width 4 long y4 y3 x4 x3 byte p info p image scan the buffer in reverse direction to avoid reallocations for long y head bi height 1 y 0 y y4 effwidth4 y y3 info dw eff width y for long x head bi width 1 x 0 x x4 4 x y4 x3 3 x y3 p x3 src x4 p 1 x3 src 1 x4 p 2 x3 src 2 x4 return cximage biwidth pimage biheight dweffwidth biwidth biwidth pimage biheight dweffwidth biwidth int cx image compare colors const void elem1 const void elem2 rgbquad c1 rgbquad elem1 rgbquad c2 rgbquad elem2 int g1 int rgb2gray c1 rgb red c1 rgb green c1 rgb blue int g2 int rgb2gray c2 rgb red c2 rgb green c2 rgb blue return g1 g2 cximage comparecolors rgbred rgbgreen rgbblue rgbred rgbgreen rgbblue cx image cx image const char filename dword imagetype startup imagetype load filename imagetype cximage cximage cx image cx image file stream dword imagetype startup imagetype decode stream imagetype cximage cximage cx image cx image cx file stream dword imagetype startup imagetype decode stream imagetype cximage cximage cxfile cx image cx image byte buffer dword size dword imagetype startup imagetype cx mem file stream buffer size decode stream imagetype cximage cximage cxmemfile bool cx image load const char filename dword imagetype file h file file handle to read the image if h file fopen filename rb null return false bool bok decode h file imagetype fclose h file automatic file type recognition bool bok false if imagetype 0 imagetype cmax image formats file h file file handle to read the image if h file fopen filename rb null return false bok decode h file imagetype fclose h file if bok return bok char sz error 256 strcpy sz error info sz last error save the first error if failed try automatic recognition of the file file h file if h file fopen filename rb null return false bok decode h file cximage format unknown fclose h file if bok imagetype 0 strcpy info sz last error sz error restore the first error return bok cximage hfile hfile hfile hfile cmax_image_formats hfile hfile hfile hfile szerror szerror szlasterror hfile hfile hfile cximage_format_unknown hfile szlasterror szerror bool cx image decode file h file dword imagetype cxio file file h file return decode file imagetype cximage hfile cxiofile hfile bool cx image decode cx file h file dword imagetype if imagetype cximage format unknown dword pos h file tell if cximage support bmp cx imagebmp newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support jpg cx imagejpg newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support ico cx imageico newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support gif cx imagegif newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support png cx imagepng newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support tif cx imagetif newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support mng cx imagemng newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support tga cx imagetga newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support pcx cx imagepcx newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support wbmp cx imagewbmp newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support wmf cximage support windows cx imagewmf newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support j2k cx imagej2k newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support jbg cx imagejbg newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support jasper cx imagejas newima if newima decode h file transfer newima return true else h file seek pos seek set endif if cximage support bmp if imagetype cximage format bmp cx imagebmp newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support jpg if imagetype cximage format jpg cx imagejpg newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support ico if imagetype cximage format ico cx imageico newima newima set frame get frame rec 29 01 02 handles multipage if newima decode h file transfer newima return true else info n num frames newima info n num frames strcpy info sz last error newima get last error return false endif if cximage support gif if imagetype cximage format gif cx imagegif newima newima set frame get frame rec 29 01 02 handles multipage if newima decode h file transfer newima return true else info n num frames newima info n num frames strcpy info sz last error newima get last error return false endif if cximage support png if imagetype cximage format png cx imagepng newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support tif if imagetype cximage format tif cx imagetif newima newima set frame get frame rec 29 01 02 handles multipage if newima decode h file transfer newima return true else info n num frames newima info n num frames strcpy info sz last error newima get last error return false endif if cximage support mng if imagetype cximage format mng cx imagemng newima newima set frame get frame rec 29 01 02 handles multipage if newima decode h file transfer newima return true else info n num frames newima info n num frames strcpy info sz last error newima get last error return false endif if cximage support tga if imagetype cximage format tga cx imagetga newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support pcx if imagetype cximage format pcx cx imagepcx newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support wbmp if imagetype cximage format wbmp cx imagewbmp newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support wmf cximage support windows vho wmf support if imagetype cximage format wmf cx imagewmf newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support j2k if imagetype cximage format j2k cx imagej2k newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support jbg if imagetype cximage format jbg cx imagejbg newima if newima decode h file transfer newima return true else strcpy info sz last error newima get last error return false endif if cximage support jasper if if cximage support jp2 imagetype cximage format jp2 endif if cximage support jpc imagetype cximage format jpc endif if cximage support pgx imagetype cximage format pgx endif if cximage support pnm imagetype cximage format pnm endif if cximage support ras imagetype cximage format ras endif false cx imagejas newima if newima decode h file imagetype transfer newima return true else strcpy info sz last error newima get last error return false endif strcpy info sz last error decode unknown or wrong format return false cximage cxfile hfile cximage_format_unknown hfile cximage_support_bmp cximagebmp hfile hfile seek_set cximage_support_jpg cximagejpg hfile hfile seek_set cximage_support_ico cximageico hfile hfile seek_set cximage_support_gif cximagegif hfile hfile seek_set cximage_support_png cximagepng hfile hfile seek_set cximage_support_tif cximagetif hfile hfile seek_set cximage_support_mng cximagemng hfile hfile seek_set cximage_support_tga cximagetga hfile hfile seek_set cximage_support_pcx cximagepcx hfile hfile seek_set cximage_support_wbmp cximagewbmp hfile hfile seek_set cximage_support_wmf cximage_support_windows cximagewmf hfile hfile seek_set cximage_support_j2k cximagej2k hfile hfile seek_set cximage_support_jbg cximagejbg hfile hfile seek_set cximage_support_jasper cximagejas hfile hfile seek_set cximage_support_bmp cximage_format_bmp cximagebmp hfile szlasterror getlasterror cximage_support_jpg cximage_format_jpg cximagejpg hfile szlasterror getlasterror cximage_support_ico cximage_format_ico cximageico setframe getframe hfile nnumframes nnumframes szlasterror getlasterror cximage_support_gif cximage_format_gif cximagegif setframe getframe hfile nnumframes nnumframes szlasterror getlasterror cximage_support_png cximage_format_png cximagepng hfile szlasterror getlasterror cximage_support_tif cximage_format_tif cximagetif setframe getframe hfile nnumframes nnumframes szlasterror getlasterror cximage_support_mng cximage_format_mng cximagemng setframe getframe hfile nnumframes nnumframes szlasterror getlasterror cximage_support_tga cximage_format_tga cximagetga hfile szlasterror getlasterror cximage_support_pcx cximage_format_pcx cximagepcx hfile szlasterror getlasterror cximage_support_wbmp cximage_format_wbmp cximagewbmp hfile szlasterror getlasterror cximage_support_wmf cximage_support_windows cximage_format_wmf cximagewmf hfile szlasterror getlasterror cximage_support_j2k cximage_format_j2k cximagej2k hfile szlasterror getlasterror cximage_support_jbg cximage_format_jbg cximagejbg hfile szlasterror getlasterror cximage_support_jasper cximage_support_jp2 cximage_format_jp2 cximage_support_jpc cximage_format_jpc cximage_support_pgx cximage_format_pgx cximage_support_pnm cximage_format_pnm cximage_support_ras cximage_format_ras cximagejas hfile szlasterror getlasterror szlasterror bool cx image decode byte buffer dword size dword imagetype cx mem file file buffer size return decode file imagetype cximage cxmemfile bool cx image save const char filename dword imagetype file h file file handle to write the image if h file fopen filename wb null return false bool bok encode h file imagetype fclose h file return bok cximage hfile hfile hfile hfile bool cx image encode file h file dword imagetype cxio file file h file return encode file imagetype cximage hfile cxiofile hfile bool cx image encode cx file h file dword imagetype if cximage support bmp if imagetype cximage format bmp cx imagebmp newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support ico if imagetype cximage format ico cx imageico newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support tif if imagetype cximage format tif cx imagetif newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support jpg if imagetype cximage format jpg cx imagejpg newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support gif if imagetype cximage format gif cx imagegif newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support png if imagetype cximage format png cx imagepng newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support mng if imagetype cximage format mng cx imagemng newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support tga if imagetype cximage format tga cx imagetga newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support pcx if imagetype cximage format pcx cx imagepcx newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support wbmp if imagetype cximage format wbmp cx imagewbmp newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support wmf cximage support windows vho wmf emf support if imagetype cximage format wmf cx imagewmf newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support j2k if imagetype cximage format j2k cx imagej2k newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support jbg if imagetype cximage format jbg cx imagejbg newima newima ghost this if newima encode h file return true else strcpy info sz last error newima get last error return false endif if cximage support jasper if if cximage support jp2 imagetype cximage format jp2 endif if cximage support jpc imagetype cximage format jpc endif if cximage support pgx imagetype cximage format pgx endif if cximage support pnm imagetype cximage format pnm endif if cximage support ras imagetype cximage format ras endif false cx imagejas newima newima ghost this if newima encode h file imagetype return true else strcpy info sz last error newima get last error return false endif strcpy info sz last error encode unknown format return false cximage cxfile hfile cximage_support_bmp cximage_format_bmp cximagebmp hfile szlasterror getlasterror cximage_support_ico cximage_format_ico cximageico hfile szlasterror getlasterror cximage_support_tif cximage_format_tif cximagetif hfile szlasterror getlasterror cximage_support_jpg cximage_format_jpg cximagejpg hfile szlasterror getlasterror cximage_support_gif cximage_format_gif cximagegif hfile szlasterror getlasterror cximage_support_png cximage_format_png cximagepng hfile szlasterror getlasterror cximage_support_mng cximage_format_mng cximagemng hfile szlasterror getlasterror cximage_support_tga cximage_format_tga cximagetga hfile szlasterror getlasterror cximage_support_pcx cximage_format_pcx cximagepcx hfile szlasterror getlasterror cximage_support_wbmp cximage_format_wbmp cximagewbmp hfile szlasterror getlasterror cximage_support_wmf cximage_support_windows cximage_format_wmf cximagewmf hfile szlasterror getlasterror cximage_support_j2k cximage_format_j2k cximagej2k hfile szlasterror getlasterror cximage_support_jbg cximage_format_jbg cximagejbg hfile szlasterror getlasterror cximage_support_jasper cximage_support_jp2 cximage_format_jp2 cximage_support_jpc cximage_format_jpc cximage_support_pgx cximage_format_pgx cximage_support_pnm cximage_format_pnm cximage_support_ras cximage_format_ras cximagejas hfile szlasterror getlasterror szlasterror bool cx image encode cx file h file cx image p images int pagecount dword imagetype if cximage support tif if imagetype cximage format tif cx imagetif newima newima ghost this if newima encode h file p images pagecount return true else strcpy info sz last error newima get last error return false endif if cximage support gif if imagetype cximage format gif cx imagegif newima newima ghost this if newima encode h file p images pagecount return true else strcpy info sz last error newima get last error return false endif strcpy info sz last error multipage encode unsupported operation for this format return false cximage cxfile hfile cximage pimages cximage_support_tif cximage_format_tif cximagetif hfile pimages szlasterror getlasterror cximage_support_gif cximage_format_gif cximagegif hfile pimages szlasterror getlasterror szlasterror bool cx image encode file h file cx image p images int pagecount dword imagetype cxio file file h file return encode file p images pagecount imagetype cximage hfile cximage pimages cxiofile hfile pimages bool cx image encode byte buffer long size dword imagetype if buffer null return false the buffer must be empty cx mem file file file open if encode file imagetype buffer file get buffer size file size return true return false cximage cxmemfile getbuffer bool cx imagepng decode cx file h file int number passes png struct png ptr png info info ptr byte row pointers null c image iterator iter this try create and initialize the png struct with the desired error handler functions if you want to use the default stderr and longjump method you can supply null for the last three parameters we also supply the the compiler header file version so that we know if the application was compiled with a compatible version of the library required png ptr png create read struct png libpng ver string void null null null if png ptr null throw failed to create png structure allocate initialize the memory for image information required info ptr png create info struct png ptr if info ptr null png destroy read struct png ptr png infopp null png infopp null throw failed to initialize png info structure set error handling if you are using the setjmp longjmp method this is the normal method of doing things with libpng required unless you set up your own error handlers in the png create read struct earlier if setjmp png ptr jmpbuf free all of the memory associated with the png ptr and info ptr if row pointers delete row pointers png destroy read struct png ptr info ptr png infopp null throw set up the input control png init io png ptr h file use custom i o functions png set read fn png ptr h file png rw ptr user read data png set error fn png ptr info sz last error png error ptr user error fn null read the file information png read info png ptr info ptr allocate the memory to hold the image using the fields of png info png color 16 my background 0 192 192 192 0 png color 16 image background if info ptr pixel depth 32 yeonjun jeong preserve original background info if png get bkgd png ptr info ptr image background png set background png ptr image background png background gamma file 1 1 0 else png set background png ptr my background png background gamma screen 0 1 0 vho we call png set bgr below vho yeonjun jeong safe check vho if info ptr pixel depth 16 info ptr color type colortype color dp hack for images with alpha channel if info ptr pixel depth 32 info n bkgnd index 0 enable transparency if png get bkgd png ptr info ptr image background info n bkgnd color rgb red byte image background red info n bkgnd color rgb green byte image background green info n bkgnd color rgb blue byte image background blue info n bkgnd color rgb reserved 0 vho tell libpng to strip 16 bit depth files down to 8 bits if info ptr bit depth 16 png set strip 16 png ptr int pixel depth info ptr pixel depth if pixel depth 16 pixel depth 24 if pixel depth 16 pixel depth 8 create info ptr width info ptr height pixel depth cximage format png get metrics switch info ptr phys unit type case png resolution unknown setxdpi info ptr x pixels per unit setydpi info ptr y pixels per unit break case png resolution meter setxdpi long floor info ptr x pixels per unit 254 0 10000 0 0 5 setydpi long floor info ptr y pixels per unit 254 0 10000 0 0 5 break if info ptr num palette 0 set palette rgb color info ptr palette info ptr num palette else if info ptr bit depth 2 dp needed for 2 bpp grayscale pn gs set palette color 0 0 0 0 set palette color 1 85 85 85 set palette color 2 170 170 170 set palette color 3 255 255 255 else set gray palette dp needed for grayscale pn gs simple transparency the real pgn transparency is more complex if info ptr num trans 0 palette transparency rgbquad pal get palette if pal dword ip for ip 0 ip min head bi clr used unsigned long info ptr num trans ip pal ip rgb reserved info ptr trans ip if info ptr num trans 1 pal 0 rgb reserved 0 info n bkgnd index 0 else info b alpha palette enabled true for ip head bi clr used ip pal ip rgb reserved 255 if info ptr color type png color type rgb alpha alpha channel info ptr color type png color type gray alpha info ptr pixel depth 32 if info ptr color type png color type gray alpha png set gray to rgb png ptr png set expand png ptr if cximage support alpha vho png set filler png ptr 0xff png filler after alpha create else png set strip alpha png ptr endif cximage support alpha vho flip the rgb pixels to bgr or rgba to bgra if info ptr color type png color mask color png set bgr png ptr vho handle cancel if info n escape longjmp png ptr jmpbuf 1 allocate the buffer int row stride info ptr width info ptr pixel depth 7 3 row pointers new byte 10 row stride turn on interlace handling if info ptr interlace type number passes png set interlace handling png ptr else number passes 1 for int pass 0 pass number passes pass iter upset int y 0 do vho handle cancel if info n escape longjmp png ptr jmpbuf 1 if cximage support alpha vho if alpha is valid endif cximage support alpha recover data from previous scan if info ptr interlace type pass 0 iter get row row pointers info dw eff width read next row png read row png ptr row pointers null vho already done by png set bgr vho hack by op dp for interlace swap only in the last pass vho if info ptr color type colortype color pass number passes 1 vho rg btobgr row pointers info dw eff width dp expand 2 bpp images only in the last pass if info ptr bit depth 2 pass number passes 1 expand2to4bpp row pointers copy the pixels iter set row row pointers info dw eff width go on iter prev row if cximage support alpha vho else alpha blend read next row png read row png ptr row pointers null compute the correct position of the line long ay if info ptr interlace type if y 0 ay 0 else ay head bi height y else ay head bi height 1 y rgba rgb a if pass number passes 1 byte prow iter get row ay for long ax 0 ax head bi width ax alpha set ax ay row pointers ax 4 3 vho don t flip rgb bgr already done by png set bgr png ptr prow 3 ax row pointers ax 4 2 prow 3 ax 1 row pointers ax 4 1 prow 3 ax 2 row pointers ax 4 prow 3 ax row pointers ax 4 prow 3 ax 1 row pointers ax 4 1 prow 3 ax 2 row pointers ax 4 2 endif cximage support alpha vho y while y head bi height delete row pointers read the rest of the file getting any additional chunks in info ptr png read end png ptr info ptr clean up after the read and free any memory allocated required png destroy read struct png ptr info ptr png infopp null catch char message if strcmp message strncpy info sz last error message 255 return false that s it return true cximagepng cxfile hfile number_passes png_struct png_ptr png_info info_ptr row_pointers cimageiterator png_struct png_ptr png_create_read_struct png_libpng_ver_string png_ptr info_ptr png_create_info_struct png_ptr info_ptr png_destroy_read_struct png_ptr png_infopp png_infopp png_create_read_struct png_ptr png_ptr info_ptr row_pointers row_pointers png_destroy_read_struct png_ptr info_ptr png_infopp png_init_io png_ptr hfile png_set_read_fn png_ptr hfile png_rw_ptr user_read_data png_set_error_fn png_ptr szlasterror png_error_ptr user_error_fn png_read_info png_ptr info_ptr png_info png_color_16 my_background png_color_16 image_background info_ptr pixel_depth png_get_bkgd png_ptr info_ptr image_background png_set_background png_ptr image_background png_background_gamma_file png_set_background png_ptr my_background png_background_gamma_screen png_set_bgr info_ptr pixel_depth info_ptr color_type colortype_color info_ptr pixel_depth nbkgndindex png_get_bkgd png_ptr info_ptr image_background nbkgndcolor rgbred image_background nbkgndcolor rgbgreen image_background nbkgndcolor rgbblue image_background nbkgndcolor rgbreserved info_ptr bit_depth png_set_strip_16 png_ptr pixel_depth info_ptr pixel_depth pixel_depth pixel_depth pixel_depth pixel_depth info_ptr info_ptr pixel_depth cximage_format_png info_ptr phys_unit_type png_resolution_unknown info_ptr x_pixels_per_unit info_ptr y_pixels_per_unit png_resolution_meter info_ptr x_pixels_per_unit info_ptr y_pixels_per_unit info_ptr num_palette setpalette rgb_color info_ptr info_ptr num_palette info_ptr bit_depth pngs setpalettecolor setpalettecolor setpalettecolor setpalettecolor setgraypalette pngs info_ptr num_trans getpalette biclrused info_ptr num_trans rgbreserved info_ptr info_ptr num_trans rgbreserved nbkgndindex balphapaletteenabled biclrused rgbreserved info_ptr color_type png_color_type_rgb_alpha info_ptr color_type png_color_type_gray_alpha info_ptr pixel_depth info_ptr color_type png_color_type_gray_alpha png_set_gray_to_rgb png_ptr png_set_expand png_ptr cximage_support_alpha png_set_filler png_ptr png_filler_after alphacreate png_set_strip_alpha png_ptr cximage_support_alpha info_ptr color_type png_color_mask_color png_set_bgr png_ptr nescape png_ptr row_stride info_ptr info_ptr pixel_depth row_pointers row_stride info_ptr interlace_type number_passes png_set_interlace_handling png_ptr number_passes number_passes nescape png_ptr cximage_support_alpha alphaisvalid cximage_support_alpha info_ptr interlace_type getrow row_pointers dweffwidth png_read_row png_ptr row_pointers png_set_bgr info_ptr color_type colortype_color number_passes rgbtobgr row_pointers dweffwidth info_ptr bit_depth number_passes row_pointers setrow row_pointers dweffwidth prevrow cximage_support_alpha png_read_row png_ptr row_pointers info_ptr interlace_type biheight biheight number_passes getrow biwidth alphaset row_pointers png_set_bgr png_ptr row_pointers row_pointers row_pointers row_pointers row_pointers row_pointers cximage_support_alpha biheight row_pointers info_ptr png_read_end png_ptr info_ptr png_destroy_read_struct png_ptr info_ptr png_infopp szlasterror bool cx imagepng encode cx file h file if h file null return false c image iterator iter this byte trans 256 for transparency don t move png struct png ptr png info info ptr try create and initialize the png struct with the desired error handler functions if you want to use the default stderr and longjump method you can supply null for the last three parameters we also check that the library version is compatible with the one used at compile time in case we are using dynamically linked libraries required png ptr png create write struct png libpng ver string void null null null if png ptr null throw failed to create png structure allocate initialize the image information data required info ptr png create info struct png ptr if info ptr null png destroy write struct png ptr png infopp null throw failed to initialize png info structure set error handling required if you aren t supplying your own error hadnling functions in the png create write struct call if setjmp png ptr jmpbuf if we get here we had a problem reading the file if info ptr palette free info ptr palette png destroy write struct png ptr png infopp info ptr throw error saving png file int row stride info dw eff width set up the output control png init io png ptr h file use custom i o functions png set write fn png ptr h file png rw ptr user write data png flush ptr user flush data set the file information here info ptr width get width info ptr height get height info ptr pixel depth byte get bpp info ptr channels get bpp 8 byte 3 byte 1 info ptr bit depth byte get bpp info ptr channels info ptr color type get color type info ptr compression type info ptr filter type info ptr interlace type 0 info ptr valid 0 info ptr interlace type png interlace none info ptr rowbytes row stride set metrics png set phys png ptr info ptr head bix pels per meter head biy pels per meter png resolution meter set the palette if there is one if get palette png set ihdr png ptr info ptr info ptr width info ptr height info ptr bit depth png color type palette info ptr interlace type png compression type base png filter type base info ptr valid png info plte dp simple transparency if info n bkgnd index 1 trans 0 0 info ptr num trans 1 info ptr valid png info trns info ptr trans trans the transparency indexes start from 0 if info n bkgnd index swap index 0 byte info n bkgnd index the ghost must set the changed attributes in the body if info p ghost info p ghost set trans index 0 if info b alpha palette enabled for word ip 0 ip head bi clr used ip trans ip get palette color byte ip rgb reserved info ptr num trans word head bi clr used info ptr valid png info trns info ptr trans trans copy the palette colors int nc get num colors info ptr palette new png color nc info ptr num palette png uint 16 nc for int i 0 i nc i get palette color i info ptr palette i red info ptr palette i green info ptr palette i blue if cximage support alpha vho merge the transparent color with the alpha channel bool b need temp alpha false if head bi bit count 24 info n bkgnd index 0 if alpha is valid b need temp alpha true alpha create alpha set 255 rgbquad c ct get trans color for long y 0 y head bi height y for long x 0 x head bi width x c get pixel color x y if long c long ct alpha set x y 0 endif cximage support alpha vho if cximage support alpha vho if alpha is valid row stride 4 head bi width info ptr pixel depth 32 info ptr channels 4 info ptr bit depth 8 info ptr color type png color type rgb alpha info ptr rowbytes row stride write the file information png write info png ptr info ptr ranger 10 row stride fix heap deallocation problem during debug byte row pointers new byte 10 row stride iter upset long ay head bi height 1 rgbquad c do iter get row row pointers row stride for long ax head bi width 1 ax 0 ax c get pixel color ax ay row pointers ax 4 3 byte alpha get ax ay info n alpha max 255 row pointers ax 4 2 c rgb blue row pointers ax 4 1 c rgb green row pointers ax 4 c rgb red png write row png ptr row pointers ay while iter prev row delete row pointers else endif cximage support alpha vho write the file information png write info png ptr info ptr if you are only writing one row at a time this works byte row pointers new byte 10 row stride iter upset do iter get row row pointers row stride hack by op if info ptr color type 2 colortype color rg btobgr row pointers row stride png write row png ptr row pointers while iter prev row delete row pointers if cximage support alpha vho remove the temporary alpha channel if b need temp alpha alpha delete endif cximage support alpha vho it is required to call this to finish writing the rest of the file png write end png ptr info ptr if you malloced the palette free it here if info ptr palette delete info ptr palette clean up after the write and free any memory allocated png destroy write struct png ptr png infopp info ptr catch char message strncpy info sz last error message 255 return false that s it return true cximagepng cxfile hfile hfile cimageiterator png_struct png_ptr png_info info_ptr png_struct png_ptr png_create_write_struct png_libpng_ver_string png_ptr info_ptr png_create_info_struct png_ptr info_ptr png_destroy_write_struct png_ptr png_infopp png_create_write_struct png_ptr info_ptr info_ptr png_destroy_write_struct png_ptr png_infopp info_ptr row_stride dweffwidth png_init_io png_ptr hfile png_set_write_fn png_ptr hfile png_rw_ptr user_write_data png_flush_ptr user_flush_data info_ptr getwidth info_ptr getheight info_ptr pixel_depth getbpp info_ptr getbpp info_ptr bit_depth getbpp info_ptr info_ptr color_type getcolortype info_ptr compression_type info_ptr filter_type info_ptr interlace_type info_ptr info_ptr interlace_type png_interlace_none info_ptr row_stride png_set_phys png_ptr info_ptr bixpelspermeter biypelspermeter png_resolution_meter getpalette png_set_ihdr png_ptr info_ptr info_ptr info_ptr info_ptr bit_depth png_color_type_palette info_ptr interlace_type png_compression_type_base png_filter_type_base info_ptr png_info_plte nbkgndindex info_ptr num_trans info_ptr png_info_trns info_ptr nbkgndindex swapindex nbkgndindex pghost pghost settransindex balphapaletteenabled biclrused getpalettecolor rgbreserved info_ptr num_trans biclrused info_ptr png_info_trns info_ptr getnumcolors info_ptr png_color info_ptr num_palette png_uint_16 getpalettecolor info_ptr info_ptr info_ptr cximage_support_alpha bneedtempalpha bibitcount nbkgndindex alphaisvalid bneedtempalpha alphacreate alphaset gettranscolor biheight biwidth getpixelcolor alphaset cximage_support_alpha cximage_support_alpha alphaisvalid row_stride biwidth info_ptr pixel_depth info_ptr info_ptr bit_depth info_ptr color_type png_color_type_rgb_alpha info_ptr row_stride png_write_info png_ptr info_ptr row_stride row_pointers row_stride biheight getrow row_pointers row_stride biwidth getpixelcolor row_pointers alphaget nalphamax row_pointers rgbblue row_pointers rgbgreen row_pointers rgbred png_write_row png_ptr row_pointers prevrow row_pointers cximage_support_alpha png_write_info png_ptr info_ptr row_pointers row_stride getrow row_pointers row_stride info_ptr color_type colortype_color rgbtobgr row_pointers row_stride png_write_row png_ptr row_pointers prevrow row_pointers cximage_support_alpha bneedtempalpha alphadelete cximage_support_alpha png_write_end png_ptr info_ptr info_ptr info_ptr png_destroy_write_struct png_ptr png_infopp info_ptr szlasterror void cx imagepng expand2to4bpp byte prow byte psrc pdst byte pos idx for long x head bi width 1 x 0 x psrc prow 2 x 3 pdst prow 4 x 3 pos byte 2 3 x 4 idx byte psrc 0x03 pos pos pos byte 4 1 x 2 pdst 0x0f pos pdst idx 0x0f pos cximagepng biwidth c image iterator c image iterator void ima 0 iter image 0 itx ity 0 stepx stepy 0 cimageiterator cimageiterator iterimage c image iterator c image iterator cx image image impl ima image impl if ima iter image ima get bits itx ity 0 stepx stepy 0 cimageiterator cimageiterator cximage imageimpl imageimpl iterimage getbits c image iterator operator cx image return ima cimageiterator cximage inline bool c image iterator itok if ima return ima is inside itx ity else return false cimageiterator isinside inline void c image iterator reset if ima iter image ima get bits else iter image 0 itx ity 0 cimageiterator iterimage getbits iterimage inline void c image iterator upset itx 0 ity ima get height 1 iter image ima get bits ima get eff width ima get height 1 cimageiterator getheight iterimage getbits geteffwidth getheight inline void c image iterator set row byte buf int n if n 0 n int ima get eff width else n min n int ima get eff width if iter image memcpy iter image buf n cimageiterator setrow geteffwidth geteffwidth iterimage iterimage inline void c image iterator get row byte buf int n if buf null n 0 memcpy buf iter image n cimageiterator getrow iterimage inline byte c image iterator get row int n sety n return iter image cimageiterator getrow iterimage inline bool c image iterator next row if ity int ima get height return 0 iter image ima get eff width return 1 cimageiterator nextrow getheight iterimage geteffwidth inline bool c image iterator prev row if ity 0 return 0 iter image ima get eff width return 1 cimageiterator prevrow iterimage geteffwidth inline bool c image iterator next byte if itx int ima get eff width return 1 else if ity int ima get height iter image ima get eff width itx 0 return 1 else return 0 cimageiterator nextbyte geteffwidth getheight iterimage geteffwidth inline bool c image iterator prev byte if itx 0 return 1 else if ity 0 iter image ima get eff width itx 0 return 1 else return 0 cimageiterator prevbyte iterimage geteffwidth inline bool c image iterator next step itx stepx if itx int ima get eff width return 1 else ity stepy if ity int ima get height iter image ima get eff width itx 0 return 1 else return 0 cimageiterator nextstep geteffwidth getheight iterimage geteffwidth inline bool c image iterator prev step itx stepx if itx 0 return 1 else ity stepy if ity 0 ity int ima get height iter image ima get eff width itx 0 return 1 else return 0 cimageiterator prevstep getheight iterimage geteffwidth inline void c image iterator sety int y if y 0 y int ima get height return ity y iter image ima get bits ima get eff width y cimageiterator getheight iterimage getbits geteffwidth bool cx imagebmp decode cx file h file if h file null return false bitmapfileheader bf dword off h file tell csc try if h file read bf sizeof bf 1 0 throw not a bmp if bf bf type bft bitmap do we have a rc header bf bf off bits 0l h file seek off seek set if dib read bitmap info h file head throw error reading bmp info dword dw compression head bi compression dword dw bit count head bi bit count preserve for bi bitfields compression thomas ernst bool b isos2 head bi size sizeof bitmapinfoheader head bi size sizeof bitmapinfoheader bool b top down dib head bi height 0 flanders check if it s a top down bitmap if b top down dib head bi height head bi height if create head bi width head bi height head bi bit count cximage format bmp throw can t allocate memory info xdpi long floor head bix pels per meter 254 0 10000 0 0 5 info ydpi long floor head biy pels per meter 254 0 10000 0 0 5 if info n escape throw cancelled vho cancel decoding rgbquad p rgb get palette if p rgb if b isos2 convert a old color table 3 byte entries to a new color table 4 byte entries h file read void p rgb dib num colors head sizeof rgbtriple 1 for int i dib num colors head 1 i 0 i p rgb i rgb red rgbtriple p rgb i rgbt red p rgb i rgb blue rgbtriple p rgb i rgbt blue p rgb i rgb green rgbtriple p rgb i rgbt green p rgb i rgb reserved byte 0 else h file read void p rgb dib num colors head sizeof rgbquad 1 if info n escape throw cancelled vho cancel decoding switch dw bit count case 32 if bf bf off bits 0l h file seek off bf bf off bits seek set if dw compression bi bitfields dw compression bi rgb long imagesize 4 head bi height head bi width byte buff32 byte malloc imagesize if buff32 h file read buff32 imagesize 1 read in the pixels bitfield2rgb buff32 0 0 0 32 free buff32 else throw can t allocate memory else throw unknown compression break case 24 if bf bf off bits 0l h file seek off bf bf off bits seek set if dw compression bi rgb h file read info p image head bi size image 1 read in the pixels else throw unknown compression break case 16 dword bfmask 3 if dw compression bi bitfields h file read bfmask 12 1 else bfmask 0 0x7c00 bfmask 1 0x3e0 bfmask 2 0x1f rgb555 bf bf off bits required after the bitfield mask cui ying jie if bf bf off bits 0l h file seek off bf bf off bits seek set read in the pixels h file read info p image head bi height head bi width 1 2 4 1 transform into rgb bitfield2rgb info p image word bfmask 0 word bfmask 1 word bfmask 2 16 break case 8 case 4 case 1 if bf bf off bits 0l h file seek off bf bf off bits seek set switch dw compression case bi rgb h file read info p image head bi size image 1 read in the pixels break case bi rle4 byte status byte 0 byte second byte 0 int scanline 0 int bits 0 bool low nibble false c image iterator iter this for bool b continue true b continue h file read status byte sizeof byte 1 switch status byte case rle command h file read status byte sizeof byte 1 switch status byte case rle endofline bits 0 scanline low nibble false break case rle endofbitmap b continue false break case rle delta read the delta values byte delta x byte delta y h file read delta x sizeof byte 1 h file read delta y sizeof byte 1 apply them bits delta x 2 scanline delta y break default h file read second byte sizeof byte 1 byte sline iter get row scanline for int i 0 i status byte i if low nibble if dword sline bits dword info p image head bi size image sline bits second byte 0x0f if i status byte 1 h file read second byte sizeof byte 1 bits else if dword sline bits dword info p image head bi size image sline bits byte second byte 0xf0 low nibble low nibble if status byte 2 1 1 h file read second byte sizeof byte 1 break break default byte sline iter get row scanline h file read second byte sizeof byte 1 for unsigned i 0 i status byte i if low nibble if dword sline bits dword info p image head bi size image sline bits second byte 0x0f bits else if dword sline bits dword info p image head bi size image sline bits byte second byte 0xf0 low nibble low nibble break break case bi rle8 byte status byte 0 byte second byte 0 int scanline 0 int bits 0 c image iterator iter this for bool b continue true b continue h file read status byte sizeof byte 1 switch status byte case rle command h file read status byte sizeof byte 1 switch status byte case rle endofline bits 0 scanline break case rle endofbitmap b continue false break case rle delta read the delta values byte delta x byte delta y h file read delta x sizeof byte 1 h file read delta y sizeof byte 1 apply them bits delta x scanline delta y break default h file read void iter get row scanline bits sizeof byte status byte 1 align run length to even number of bytes if status byte 1 1 h file read second byte sizeof byte 1 bits status byte break break default byte sline iter get row scanline h file read second byte sizeof byte 1 for unsigned i 0 i status byte i sline bits second byte bits break break default throw compression type not supported if b top down dib flip flanders catch char message strncpy info sz last error message 255 return false return true cximagebmp cxfile hfile hfile hfile hfile bftype bft_bitmap bfoffbits hfile seek_set dibreadbitmapinfo hfile dwcompression bicompression dwbitcount bibitcount bi_bitfields bisos2 bisize bisize btopdowndib biheight btopdowndib biheight biheight biwidth biheight bibitcount cximage_format_bmp bixpelspermeter biypelspermeter nescape prgb getpalette prgb bisos2 hfile prgb dibnumcolors dibnumcolors prgb rgbred prgb rgbtred prgb rgbblue prgb rgbtblue prgb rgbgreen prgb rgbtgreen prgb rgbreserved hfile prgb dibnumcolors nescape dwbitcount bfoffbits hfile bfoffbits seek_set dwcompression bi_bitfields dwcompression bi_rgb biheight biwidth hfile bfoffbits hfile bfoffbits seek_set dwcompression bi_rgb hfile pimage bisizeimage dwcompression bi_bitfields hfile bfoffbits bfoffbits hfile bfoffbits seek_set hfile pimage biheight biwidth pimage bfoffbits hfile bfoffbits seek_set dwcompression bi_rgb hfile pimage bisizeimage bi_rle4 status_byte second_byte low_nibble cimageiterator bcontinue bcontinue hfile status_byte status_byte rle_command hfile status_byte status_byte rle_endofline low_nibble rle_endofbitmap bcontinue rle_delta delta_x delta_y hfile delta_x hfile delta_y delta_x delta_y hfile second_byte getrow status_byte low_nibble pimage bisizeimage second_byte status_byte hfile second_byte pimage bisizeimage second_byte low_nibble low_nibble status_byte hfile second_byte getrow hfile second_byte status_byte low_nibble pimage bisizeimage second_byte pimage bisizeimage second_byte low_nibble low_nibble bi_rle8 status_byte second_byte cimageiterator bcontinue bcontinue hfile status_byte status_byte rle_command hfile status_byte status_byte rle_endofline rle_endofbitmap bcontinue rle_delta delta_x delta_y hfile delta_x hfile delta_y delta_x delta_y hfile getrow status_byte status_byte hfile second_byte status_byte getrow hfile second_byte status_byte second_byte btopdowndib szlasterror bool cx imagebmp encode cx file h file if h file null return false bitmapfileheader hdr hdr bf type 0x4d42 bm windows bitmap signature hdr bf size get size sizeof bitmapfileheader hdr bf reserved1 hdr bf reserved2 0 hdr bf off bits dword sizeof hdr head bi size get palette size copy attributes memcpy p dib head sizeof bitmapinfoheader write the file header h file write hdr sizeof bitmapfileheader 1 write the dib header and the pixels h file write p dib get size 1 return true cximagebmp cxfile hfile hfile bftype windows_bitmap_signature bfsize getsize bfreserved1 bfreserved2 bfoffbits bisize getpalettesize pdib hfile hfile pdib getsize bool cx imagebmp dib read bitmap info cx file fh bitmapinfoheader pdib if fh null pdib null return false if fh read pdib sizeof bitmapinfoheader 1 0 return false bitmapcoreheader bc switch pdib bi size what type of bitmap info is this case sizeof bitmapinfoheader break case 64 sizeof os2 bmp header fh seek 64 sizeof bitmapinfoheader seek cur break case sizeof bitmapcoreheader bc bitmapcoreheader pdib pdib bi size bc bc size pdib bi width dword bc bc width pdib bi height dword bc bc height pdib bi planes bc bc planes pdib bi bit count bc bc bit count pdib bi compression bi rgb pdib bi size image 0 pdib bix pels per meter 0 pdib biy pels per meter 0 pdib bi clr used 0 pdib bi clr important 0 fh seek long sizeof bitmapcoreheader sizeof bitmapinfoheader seek cur break default return false fix bitmap info pdib return true cximagebmp dibreadbitmapinfo cxfile bisize os2_bmp_header seek_cur bisize bcsize biwidth bcwidth biheight bcheight biplanes bcplanes bibitcount bcbitcount bicompression bi_rgb bisizeimage bixpelspermeter biypelspermeter biclrused biclrimportant seek_cur fixbitmapinfo cgdi thread p wnd hdc m rectscreen rect screen m rgnscreen create rect rgn indirect m rectscreen m nscrollpos 0 m pbmpoldbk null m pbmpoldcredits null m pbmpoldscreen null m pbmpoldmask null m ncreditsbmpwidth 0 m ncreditsbmpheight 0 cgdithread pwnd m_rectscreen rectscreen m_rgnscreen createrectrgnindirect m_rectscreen m_nscrollpos m_pbmpoldbk m_pbmpoldcredits m_pbmpoldscreen m_pbmpoldmask m_ncreditsbmpwidth m_ncreditsbmpheight int c credits thread calc credits height int n height 0 for int n 0 n m arcredits get size n c string s type m arcredits get at n left 1 if s type b it s a bitmap c bitmap bmp if bmp load bitmap m arcredits get at n mid 2 c string str str format t could not find bitmap resource s be sure to assign the bitmap a quoted resource name m arcredits get at n mid 2 afx message box str return 1 bitmap bm info bmp get bitmap bm info n height bm info bm height else if s type s it s a vertical space n height ttoi m arcredits get at n mid 2 else it s a text string int n font ttoi m arcredits get at n left 2 n height m arfontheights get at n font return n height ccreditsthread calccreditsheight nheight m_arcredits getsize cstring stype m_arcredits getat stype cbitmap loadbitmap m_arcredits getat cstring _t m_arcredits getat afxmessagebox bminfo getbitmap bminfo nheight bminfo bmheight stype nheight _ttoi m_arcredits getat nfont _ttoi m_arcredits getat nheight m_arfontheights getat nfont nheight void c credits thread init text 1st pair of digits identifies the font to use 2nd pair of digits identifies the color to use b bitmap s space moves down the specified number of pixels c string s tmp you may not modify this copyright message you may add your name if you changed or improved this code but you mot not delete any part of this message make it invisible etc start at the bottom of the screen s tmp format t s d m rectscreen height m arcredits add s tmp m arcredits add t 03 00 e mule s tmp format t 02 01 version s the app m strcurversionlong m arcredits add s tmp m arcredits add t 01 06 copyright c 2002 2006 merkur m arcredits add t s 50 m arcredits add t 02 04 developers m arcredits add t s 5 m arcredits add t 01 06 unknown1 m arcredits add t s 5 m arcredits add t 01 06 ornis m arcredits add t s 50 m arcredits add t 02 04 tester m arcredits add t s 5 m arcredits add t 01 06 monk m arcredits add t s 5 m arcredits add t 01 06 daan m arcredits add t s 5 m arcredits add t 01 06 elandal m arcredits add t s 5 m arcredits add t 01 06 frozen north m arcredits add t s 5 m arcredits add t 01 06 kayfam m arcredits add t s 5 m arcredits add t 01 06 khandurian m arcredits add t s 5 m arcredits add t 01 06 masta2002 m arcredits add t s 5 m arcredits add t 01 06 mr labr m arcredits add t s 5 m arcredits add t 01 06 nesi san m arcredits add t s 5 m arcredits add t 01 06 severed cross m arcredits add t s 5 m arcredits add t 01 06 skynetman m arcredits add t s 50 m arcredits add t 02 04 retired members m arcredits add t s 5 m arcredits add t 01 06 merkur the founder m arcredits add t s 5 m arcredits add t 01 06 tecxx m arcredits add t s 5 m arcredits add t 01 06 pach2 m arcredits add t s 5 m arcredits add t 01 06 juanjo m arcredits add t s 5 m arcredits add t 01 06 barry m arcredits add t s 5 m arcredits add t 01 06 dirus m arcredits add t s 50 m arcredits add t 02 04 thanks to these programmers m arcredits add t 02 04 for publishing useful codeparts m arcredits add t s 5 m arcredits add t 01 06 paolo messina resizable dialog class m arcredits add t s 5 m arcredits add t 01 6 pj naughter http download dialog m arcredits add t s 5 m arcredits add t 01 06 jim connor scrolling credits m arcredits add t s 5 m arcredits add t 01 06 yury goltsman extended progressbar m arcredits add t s 5 m arcredits add t 01 06 magomed g abdurakhmanov hyperlink ctrl m arcredits add t s 5 m arcredits add t 01 06 arthur westerman titled menu m arcredits add t s 5 m arcredits add t 01 06 tim kosse async socket proxysupport m arcredits add t s 5 m arcredits add t 01 06 keith rule memory dc m arcredits add t s 50 m arcredits add t 02 07 and thanks to the following m arcredits add t 02 07 people for translating e mule m arcredits add t 02 07 into different languages m arcredits add t s 20 m arcredits add t 01 06 arabic dody m arcredits add t s 05 m arcredits add t 01 06 albanian besmir m arcredits add t s 05 m arcredits add t 01 06 basque t xi ki m arcredits add t s 05 m arcredits add t 01 06 breton kad korvigello an drouizig m arcredits add t s 05 m arcredits add t 01 06 bulgarian dap ko dumper m arcredits add t s 05 m arcredits add t 01 06 catalan le chuck m arcredits add t s 05 m arcredits add t 01 06 chinese simplyfied tim chen qilu t m arcredits add t s 05 m arcredits add t 01 06 chinese traditional cml donlong ryan m arcredits add t s 05 m arcredits add t 01 06 czech patejl m arcredits add t s 05 m arcredits add t 01 06 danish tiede cirrus itchy m arcredits add t s 05 m arcredits add t 01 06 estonian symbio m arcredits add t s 05 m arcredits add t 01 06 dutch mr bean m arcredits add t s 05 m arcredits add t 01 06 finnish nikerabbit m arcredits add t s 05 m arcredits add t 01 06 french motte emzc lalrobin m arcredits add t s 05 m arcredits add t 01 06 galician juan emilio r m arcredits add t s 05 m arcredits add t 01 06 greek michael papadakis m arcredits add t s 05 m arcredits add t 01 06 italian trevi franky five m arcredits add t s 05 m arcredits add t 01 06 japanese duke dog shinro t m arcredits add t s 05 m arcredits add t 01 06 hebrew avi 3k m arcredits add t s 05 m arcredits add t 01 06 hungarian r0ll3r m arcredits add t s 05 m arcredits add t 01 06 korean pooz m arcredits add t s 05 m arcredits add t 01 06 latvian zivs m arcredits add t s 05 m arcredits add t 01 06 lithuanian daan m arcredits add t s 05 m arcredits add t 01 06 maltese reuben m arcredits add t s 05 m arcredits add t 01 06 norwegian bokmal hallvor m arcredits add t s 05 m arcredits add t 01 06 norwegian nynorsk iznogood m arcredits add t s 05 m arcredits add t 01 06 polish tomasz t mouse broniarek m arcredits add t s 05 m arcredits add t 01 06 portugese filipe lu s claro m arcredits add t s 05 m arcredits add t 01 06 portugese brasilian darth maul brasco m arcredits add t s 05 m arcredits add t 01 06 romanian dragos m arcredits add t s 05 m arcredits add t 01 06 russian t mac brmail m arcredits add t s 05 m arcredits add t 01 06 slowenian rok kralj m arcredits add t s 05 m arcredits add t 01 06 spanish castellano azuredraco javier l hell m arcredits add t s 05 m arcredits add t 01 06 swedish andre m arcredits add t s 05 m arcredits add t 01 06 turkish burak y m arcredits add t s 05 m arcredits add t 01 06 ukrainian kex m arcredits add t s 50 m arcredits add t 02 04 part of e mule is based on kademlia m arcredits add t s 5 m arcredits add t 02 04 peer to peer routing based on the xor metric m arcredits add t s 10 m arcredits add t 01 06 copyright c 2002 petar maymounkov m arcredits add t s 5 m arcredits add t 01 06 http kademlia scs cs nyu edu pause before repeating m arcredits add t s 100 ccreditsthread inittext cstring stmp stmp _t m_rectscreen m_arcredits stmp m_arcredits _t emule stmp _t theapp m_strcurversionlong m_arcredits stmp m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t frozen_north m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t mrlabr m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t severedcross m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t resizabledialog m_arcredits _t m_arcredits _t httpdownload m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t asyncsocket m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t emule m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t txiki m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t dapko m_arcredits _t m_arcredits _t lechuck m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t frankyfive m_arcredits _t m_arcredits _t dukedog m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t tmouse m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t darthmaul m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t _hell_ m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t emule m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t m_arcredits _t void c credits thread init colors define each color we ll be using m arcolors add palettergb 0 0 0 0 black m arcolors add palettergb 90 90 90 1 very dark gray m arcolors add palettergb 128 128 128 2 dark gray m arcolors add palettergb 192 192 192 3 light gray m arcolors add palettergb 200 50 50 4 very light gray m arcolors add palettergb 255 255 128 5 white m arcolors add palettergb 0 0 128 6 dark blue m arcolors add palettergb 128 128 255 7 light blue m arcolors add palettergb 0 106 0 8 dark green ccreditsthread initcolors m_arcolors m_arcolors m_arcolors m_arcolors m_arcolors m_arcolors m_arcolors m_arcolors m_arcolors void c credits thread init fonts create each font we ll need and add it to the fonts array cdc dc mem dc mem create compatibledc m dc c font p old font int n text height logfont lf font 0 small arial c font font0 new c font memset void lf 0 sizeof lf lf lf height 12 lf lf weight 500 lf lf quality nonantialiased quality tcscpy lf lf face name t arial font0 create font indirect lf m arfonts add font0 p old font dc mem select object font0 n text height dc mem get text extent t wy cy m arfontheights add n text height font 1 medium bold arial c font font1 new c font memset void lf 0 sizeof lf lf lf height 14 lf lf weight 600 lf lf quality nonantialiased quality tcscpy lf lf face name t arial font1 create font indirect lf m arfonts add font1 dc mem select object font1 n text height dc mem get text extent t wy cy m arfontheights add n text height font 2 large italic heavy bold times roman c font font2 new c font memset void lf 0 sizeof lf lf lf height 16 lf lf weight 700 lf lf italic true lf lf quality afx data b win95 nonantialiased quality antialiased quality tcscpy lf lf face name t arial font2 create font indirect lf m arfonts add font2 dc mem select object font2 n text height dc mem get text extent t wy cy m arfontheights add n text height font 3 c font font3 new c font memset void lf 0 sizeof lf lf lf height 25 lf lf weight 900 lf lf quality afx data b win95 nonantialiased quality antialiased quality tcscpy lf lf face name t arial font3 create font indirect lf m arfonts add font3 dc mem select object font3 n text height dc mem get text extent t wy cy m arfontheights add n text height dc mem select object p old font ccreditsthread initfonts dcmem dcmem createcompatibledc m_dc cfont poldfont ntextheight cfont cfont lfheight lfweight lfquality nonantialiased_quality _tcscpy lffacename _t createfontindirect m_arfonts poldfont dcmem selectobject ntextheight dcmem gettextextent _t m_arfontheights ntextheight cfont cfont lfheight lfweight lfquality nonantialiased_quality _tcscpy lffacename _t createfontindirect m_arfonts dcmem selectobject ntextheight dcmem gettextextent _t m_arfontheights ntextheight cfont cfont lfheight lfweight lfitalic lfquality afxdata bwin95 nonantialiased_quality antialiased_quality _tcscpy lffacename _t createfontindirect m_arfonts dcmem selectobject ntextheight dcmem gettextextent _t m_arfontheights ntextheight cfont cfont lfheight lfweight lfquality afxdata bwin95 nonantialiased_quality antialiased_quality _tcscpy lffacename _t createfontindirect m_arfonts dcmem selectobject ntextheight dcmem gettextextent _t m_arfontheights ntextheight dcmem selectobject poldfont void c credits thread create credits init fonts init colors init text m dc select clip rgn m rgnscreen m dcscreen create compatibledc m dc m bmpscreen create compatible bitmap m dc m rectscreen width m rectscreen height m pbmpoldscreen m dcscreen select object m bmpscreen m ncreditsbmpwidth m rectscreen width m ncreditsbmpheight calc credits height m dccredits create compatibledc m dc m bmpcredits create compatible bitmap m dc m ncreditsbmpwidth m ncreditsbmpheight m pbmpoldcredits m dccredits select object m bmpcredits m dccredits fill solid rect 0 0 m ncreditsbmpwidth m ncreditsbmpheight mask rgb c font p old font p old font m dccredits select object m arfonts get at 0 m dccredits set bk mode transparent int y 0 int n font int n color int n last font 1 int n last color 1 int n text height m dccredits get text extent t wy cy for int n 0 n m arcredits get size n c string s type m arcredits get at n left 1 if s type b it s a bitmap c bitmap bmp if bmp load bitmap m arcredits get at n mid 2 c string str str format t could not find bitmap resource s be sure to assign the bitmap a quoted resource name m arcredits get at n mid 2 afx message box str return bitmap bm info bmp get bitmap bm info cdc dc dc create compatibledc m dccredits c bitmap p old bmp dc select object bmp draw the bitmap m dccredits bit blt m rectscreen width bm info bm width 2 y bm info bm width bm info bm height dc 0 0 srccopy dc select object p old bmp bmp delete object y bm info bm height else if s type s it s a vertical space y ttoi m arcredits get at n mid 2 else it s a text string n font ttoi m arcredits get at n left 2 n color ttoi m arcredits get at n mid 3 2 if n font n last font m dccredits select object m arfonts get at n font n text height m arfontheights get at n font if n color n last color m dccredits set text color m arcolors get at n color c rect rect 0 y m rectscreen width y n text height m dccredits draw text m arcredits get at n mid 6 rect dt center y n text height m dccredits set bk color mask rgb m dccredits select object p old font create the mask bitmap m dcmask create compatibledc m dcscreen m bmpmask create bitmap m ncreditsbmpwidth m ncreditsbmpheight 1 1 null select the mask bitmap into the appropriate dc m pbmpoldmask m dcmask select object m bmpmask build mask based on transparent color m dcmask bit blt 0 0 m ncreditsbmpwidth m ncreditsbmpheight m dccredits 0 0 srccopy ccreditsthread createcredits initfonts initcolors inittext m_dc selectcliprgn m_rgnscreen m_dcscreen createcompatibledc m_dc m_bmpscreen createcompatiblebitmap m_dc m_rectscreen m_rectscreen m_pbmpoldscreen m_dcscreen selectobject m_bmpscreen m_ncreditsbmpwidth m_rectscreen m_ncreditsbmpheight calccreditsheight m_dccredits createcompatibledc m_dc m_bmpcredits createcompatiblebitmap m_dc m_ncreditsbmpwidth m_ncreditsbmpheight m_pbmpoldcredits m_dccredits selectobject m_bmpcredits m_dccredits fillsolidrect m_ncreditsbmpwidth m_ncreditsbmpheight mask_rgb cfont poldfont poldfont m_dccredits selectobject m_arfonts getat m_dccredits setbkmode nfont ncolor nlastfont nlastcolor ntextheight m_dccredits gettextextent _t m_arcredits getsize cstring stype m_arcredits getat stype cbitmap loadbitmap m_arcredits getat cstring _t m_arcredits getat afxmessagebox bminfo getbitmap bminfo createcompatibledc m_dccredits cbitmap poldbmp selectobject m_dccredits bitblt m_rectscreen bminfo bmwidth bminfo bmwidth bminfo bmheight selectobject poldbmp deleteobject bminfo bmheight stype _ttoi m_arcredits getat nfont _ttoi m_arcredits getat ncolor _ttoi m_arcredits getat nfont nlastfont m_dccredits selectobject m_arfonts getat nfont ntextheight m_arfontheights getat nfont ncolor nlastcolor m_dccredits settextcolor m_arcolors getat ncolor crect m_rectscreen ntextheight m_dccredits drawtext m_arcredits getat dt_center ntextheight m_dccredits setbkcolor mask_rgb m_dccredits selectobject poldfont m_dcmask createcompatibledc m_dcscreen m_bmpmask createbitmap m_ncreditsbmpwidth m_ncreditsbmpheight m_pbmpoldmask m_dcmask selectobject m_bmpmask m_dcmask bitblt m_ncreditsbmpwidth m_ncreditsbmpheight m_dccredits bool c credits thread init instance init thread locale bool b result cgdi thread init instance note because this is a separate thread we have to delete our gdi objects here while the handle maps are still available if m dcbk m hdc null m pbmpoldbk null m dcbk select object m pbmpoldbk m pbmpoldbk null m bmpbk delete object if m dcscreen m hdc null m pbmpoldscreen null m dcscreen select object m pbmpoldscreen m pbmpoldscreen null m bmpscreen delete object if m dccredits m hdc null m pbmpoldcredits null m dccredits select object m pbmpoldcredits m pbmpoldcredits null m bmpcredits delete object if m dcmask m hdc null m pbmpoldmask null m dcmask select object m pbmpoldmask m pbmpoldmask null m bmpmask delete object clean up the fonts we created for int n 0 n m arfonts get size n m arfonts get at n delete object delete m arfonts get at n m arfonts remove all return b result ccreditsthread initinstance initthreadlocale bresult cgdithread initinstance m_dcbk m_hdc m_pbmpoldbk m_dcbk selectobject m_pbmpoldbk m_pbmpoldbk m_bmpbk deleteobject m_dcscreen m_hdc m_pbmpoldscreen m_dcscreen selectobject m_pbmpoldscreen m_pbmpoldscreen m_bmpscreen deleteobject m_dccredits m_hdc m_pbmpoldcredits m_dccredits selectobject m_pbmpoldcredits m_pbmpoldcredits m_bmpcredits deleteobject m_dcmask m_hdc m_pbmpoldmask m_dcmask selectobject m_pbmpoldmask m_pbmpoldmask m_bmpmask deleteobject m_arfonts getsize m_arfonts getat deleteobject m_arfonts getat m_arfonts removeall bresult void c credits thread single step if this is our first time initialize the credits if m dccredits m hdc null create credits track scroll position static int n scrolly 0 timer variables large integer n frequency large integer n start large integer n end int n time in milliseconds bool b timer valid n start quad part 0 if query performance frequency n frequency b timer valid false else b timer valid true get start time query performance counter n start cgdi thread m csgdilock lock paint bk m dcscreen m dcscreen bit blt 0 0 m ncreditsbmpwidth m ncreditsbmpheight m dccredits 0 n scrolly srcinvert m dcscreen bit blt 0 0 m ncreditsbmpwidth m ncreditsbmpheight m dcmask 0 n scrolly srcand m dcscreen bit blt 0 0 m ncreditsbmpwidth m ncreditsbmpheight m dccredits 0 n scrolly srcinvert wait for vertical retrace if m bwaitvrt waitvrt m dc bit blt m rectscreen left m rectscreen top m rectscreen width m rectscreen height m dcscreen 0 0 srccopy gdi flush cgdi thread m csgdilock unlock continue scrolling n scrolly m nscrollinc if n scrolly m ncreditsbmpheight n scrolly 0 scrolling up if n scrolly 0 n scrolly m ncreditsbmpheight scrolling down delay scrolling by the specified time if b timer valid query performance counter n end n time in milliseconds int n end quad part n start quad part 1000 n frequency quad part if n time in milliseconds m ndelay sleep m ndelay n time in milliseconds else sleep m ndelay ccreditsthread singlestep m_dccredits m_hdc createcredits nscrolly large_integer nfrequency large_integer nstart large_integer nend ntimeinmilliseconds btimervalid nstart quadpart queryperformancefrequency nfrequency btimervalid btimervalid queryperformancecounter nstart cgdithread m_csgdilock paintbk m_dcscreen m_dcscreen bitblt m_ncreditsbmpwidth m_ncreditsbmpheight m_dccredits nscrolly m_dcscreen bitblt m_ncreditsbmpwidth m_ncreditsbmpheight m_dcmask nscrolly m_dcscreen bitblt m_ncreditsbmpwidth m_ncreditsbmpheight m_dccredits nscrolly m_bwaitvrt m_dc bitblt m_rectscreen m_rectscreen m_rectscreen m_rectscreen m_dcscreen gdiflush cgdithread m_csgdilock nscrolly m_nscrollinc nscrolly m_ncreditsbmpheight nscrolly nscrolly nscrolly m_ncreditsbmpheight btimervalid queryperformancecounter nend ntimeinmilliseconds nend quadpart nstart quadpart nfrequency quadpart ntimeinmilliseconds m_ndelay m_ndelay ntimeinmilliseconds m_ndelay void c credits thread paint bk cdc pdc save background the first time if m dcbk m hdc null m dcbk create compatibledc m dc m bmpbk create compatible bitmap m dc m rectscreen width m rectscreen height m pbmpoldbk m dcbk select object m bmpbk m dcbk bit blt 0 0 m rectscreen width m rectscreen height m dc m rectscreen left m rectscreen top srccopy pdc bit blt 0 0 m rectscreen width m rectscreen height m dcbk 0 0 srccopy ccreditsthread paintbk m_dcbk m_hdc m_dcbk createcompatibledc m_dc m_bmpbk createcompatiblebitmap m_dc m_rectscreen m_rectscreen m_pbmpoldbk m_dcbk selectobject m_bmpbk m_dcbk bitblt m_rectscreen m_rectscreen m_dc m_rectscreen m_rectscreen bitblt m_rectscreen m_rectscreen m_dcbk c credits thread c credits thread ccreditsthread ccreditsthread ccbb record ccbb record uint64 n start pos uint64 n end pos uint32 dwip ebbr status bbr status if n start pos n end pos assert false return m nstartpos n start pos m nendpos n end pos m dwip dwip m bbrstatus bbr status ccbbrecord ccbbrecord nstartpos nendpos ebbrstatus bbrstatus nstartpos nendpos m_nstartpos nstartpos m_nendpos nendpos m_dwip m_bbrstatus bbrstatus ccbb record ccbb record operator const ccbb record cv m nstartpos cv m nstartpos m nendpos cv m nendpos m dwip cv m dwip m bbrstatus cv m bbrstatus return this ccbbrecord ccbbrecord ccbbrecord m_nstartpos m_nstartpos m_nendpos m_nendpos m_dwip m_dwip m_bbrstatus m_bbrstatus bool ccbb record merge uint64 n start pos uint64 n end pos uint32 dwip ebbr status bbr status if m dwip dwip m bbrstatus bbr status n start pos m nendpos 1 n end pos 1 m nstartpos if n start pos m nendpos 1 m nendpos n end pos else if n end pos 1 m nstartpos m nstartpos n start pos else assert false return true else return false ccbbrecord nstartpos nendpos ebbrstatus bbrstatus m_dwip m_bbrstatus bbrstatus nstartpos m_nendpos nendpos m_nstartpos nstartpos m_nendpos m_nendpos nendpos nendpos m_nstartpos m_nstartpos nstartpos bool ccbb record can merge uint64 n start pos uint64 n end pos uint32 dwip ebbr status bbr status if m dwip dwip m bbrstatus bbr status n start pos m nendpos 1 n end pos 1 m nstartpos return true else return false ccbbrecord canmerge nstartpos nendpos ebbrstatus bbrstatus m_dwip m_bbrstatus bbrstatus nstartpos m_nendpos nendpos m_nstartpos void c corruption black box init em file size n file size m aarecords set size int ptr uint64 n file size uint64 partsize 1 partsize ccorruptionblackbox emfilesize nfilesize m_aarecords setsize int_ptr nfilesize void c corruption black box free m aarecords remove all m aarecords free extra ccorruptionblackbox m_aarecords removeall m_aarecords freeextra void c corruption black box transferred data uint64 n start pos uint64 n end pos const c up down client p sender if n end pos n start pos partsize assert false return if n start pos n end pos assert false return uint32 dw senderip p sender getip we store records seperated for each part so we don t have to search all entries everytime convert pos to relative block pos uint16 n part uint16 n start pos partsize uint64 n rel start pos n start pos uint64 n part partsize uint64 n rel end pos n end pos uint64 n part partsize if n rel end pos partsize data crosses the partborder split it n rel end pos partsize 1 uint64 n tmp start pos uint64 n part partsize n rel end pos 1 assert n tmp start pos partsize 0 remove later transferred data n tmp start pos n end pos p sender if n part uint m aarecords get count assert false m aarecords set size n part 1 int pos merge 1 uint64 ndbg rewritten 0 for int i 0 i m aarecords n part get count i if m aarecords n part i can merge n rel start pos n rel end pos dw senderip bbr none pos merge i check if there is already an pending entry and overwrite it else if m aarecords n part i m bbrstatus bbr none if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos old one is included in new one delete ndbg rewritten m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part remove at i i else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos old one includes new one check if the old one and new one have the same ip if dw senderip m aarecords n part i m dwip different ip means we have to split it 2 times uint64 n tmp end pos1 m aarecords n part i m nendpos uint64 n tmp start pos1 n rel end pos 1 uint64 n tmp start pos2 m aarecords n part i m nstartpos uint64 n tmp end pos2 n rel start pos 1 m aarecords n part i m nendpos n rel end pos m aarecords n part i m nstartpos n rel start pos uint32 dw oldip m aarecords n part i m dwip m aarecords n part i m dwip dw senderip m aarecords n part add ccbb record n tmp start pos1 n tmp end pos1 dw oldip m aarecords n part add ccbb record n tmp start pos2 n tmp end pos2 dw oldip and are done then debug only add debug log line dlp default false t corruption black box debug i bytes were rewritten and records replaced with new stats 1 n rel end pos n rel start pos 1 return else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nstartpos n rel end pos old one laps over new one on the right site assert n rel end pos m aarecords n part i m nstartpos 0 ndbg rewritten n rel end pos m aarecords n part i m nstartpos m aarecords n part i m nstartpos n rel end pos 1 else if m aarecords n part i m nendpos n rel start pos m aarecords n part i m nendpos n rel end pos old one laps over new one on the left site assert m aarecords n part i m nendpos n rel start pos 0 ndbg rewritten m aarecords n part i m nendpos n rel start pos m aarecords n part i m nendpos n rel start pos 1 if pos merge 1 verify m aarecords n part pos merge merge n rel start pos n rel end pos dw senderip bbr none else m aarecords n part add ccbb record n rel start pos n rel end pos dw senderip bbr none if ndbg rewritten 0 debug only add debug log line dlp default false t corruption black box debug i bytes were rewritten and records replaced with new stats 2 ndbg rewritten ccorruptionblackbox transferreddata nstartpos nendpos cupdownclient psender nendpos nstartpos nstartpos nendpos dwsenderip psender npart nstartpos nrelstartpos nstartpos npart nrelendpos nendpos npart nrelendpos nrelendpos ntmpstartpos npart nrelendpos ntmpstartpos transferreddata ntmpstartpos nendpos psender npart m_aarecords getcount m_aarecords setsize npart posmerge ndbgrewritten m_aarecords npart getcount m_aarecords npart canmerge nrelstartpos nrelendpos dwsenderip bbr_none posmerge m_aarecords npart m_bbrstatus bbr_none m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ndbgrewritten m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart removeat m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos dwsenderip m_aarecords npart m_dwip ntmpendpos1 m_aarecords npart m_nendpos ntmpstartpos1 nrelendpos ntmpstartpos2 m_aarecords npart m_nstartpos ntmpendpos2 nrelstartpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart m_nstartpos nrelstartpos dwoldip m_aarecords npart m_dwip m_aarecords npart m_dwip dwsenderip m_aarecords npart ccbbrecord ntmpstartpos1 ntmpendpos1 dwoldip m_aarecords npart ccbbrecord ntmpstartpos2 ntmpendpos2 dwoldip debug_only adddebuglogline dlp_default _t corruptionblackbox nrelendpos nrelstartpos m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nstartpos nrelendpos nrelendpos m_aarecords npart m_nstartpos ndbgrewritten nrelendpos m_aarecords npart m_nstartpos m_aarecords npart m_nstartpos nrelendpos m_aarecords npart m_nendpos nrelstartpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart m_nendpos nrelstartpos ndbgrewritten m_aarecords npart m_nendpos nrelstartpos m_aarecords npart m_nendpos nrelstartpos posmerge m_aarecords npart posmerge nrelstartpos nrelendpos dwsenderip bbr_none m_aarecords npart ccbbrecord nrelstartpos nrelendpos dwsenderip bbr_none ndbgrewritten debug_only adddebuglogline dlp_default _t corruptionblackbox ndbgrewritten void c corruption black box verified data uint64 n start pos uint64 n end pos if n end pos n start pos partsize assert false return convert pos to relative block pos uint16 n part uint16 n start pos partsize uint64 n rel start pos n start pos uint64 n part partsize uint64 n rel end pos n end pos uint64 n part partsize if n rel end pos partsize assert false return if n part uint m aarecords get count assert false m aarecords set size n part 1 uint64 n dbg verified bytes 0 uint32 n dbg old entries m aarecords n part get count ifdef debug c map int int int int map debug endif for int i 0 i m aarecords n part get count i if m aarecords n part i m bbrstatus bbr none m aarecords n part i m bbrstatus bbr verified if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr verified debug only map debug set at m aarecords n part i m dwip 1 else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos need to split it 2 uint64 n tmp end pos1 m aarecords n part i m nendpos uint64 n tmp start pos1 n rel end pos 1 uint64 n tmp start pos2 m aarecords n part i m nstartpos uint64 n tmp end pos2 n rel start pos 1 m aarecords n part i m nendpos n rel end pos m aarecords n part i m nstartpos n rel start pos m aarecords n part add ccbb record n tmp start pos1 n tmp end pos1 m aarecords n part i m dwip m aarecords n part i m bbrstatus m aarecords n part add ccbb record n tmp start pos2 n tmp end pos2 m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr verified debug only map debug set at m aarecords n part i m dwip 1 else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nstartpos n rel end pos need to split it uint64 n tmp end pos m aarecords n part i m nendpos uint64 n tmp start pos n rel end pos 1 m aarecords n part i m nendpos n rel end pos m aarecords n part add ccbb record n tmp start pos n tmp end pos m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr verified debug only map debug set at m aarecords n part i m dwip 1 else if m aarecords n part i m nendpos n rel start pos m aarecords n part i m nendpos n rel end pos need to split it uint64 n tmp start pos m aarecords n part i m nstartpos uint64 n tmp end pos n rel start pos 1 m aarecords n part i m nstartpos n rel start pos m aarecords n part add ccbb record n tmp start pos n tmp end pos m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr verified debug only map debug set at m aarecords n part i m dwip 1 ifdef debug uint32 n clients map debug get count else uint32 n clients 0 endif add debug log line dlp default false t found and marked u recorded bytes of u as verified in the corruption black box records u u records found u different clients n dbg verified bytes n end pos n start pos 1 m aarecords n part get count n dbg old entries n clients ccorruptionblackbox verifieddata nstartpos nendpos nendpos nstartpos npart nstartpos nrelstartpos nstartpos npart nrelendpos nendpos npart nrelendpos npart m_aarecords getcount m_aarecords setsize npart ndbgverifiedbytes ndbgoldentries m_aarecords npart getcount _debug cmap mapdebug m_aarecords npart getcount m_aarecords npart m_bbrstatus bbr_none m_aarecords npart m_bbrstatus bbr_verified m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_verified debug_only mapdebug setat m_aarecords npart m_dwip m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ntmpendpos1 m_aarecords npart m_nendpos ntmpstartpos1 nrelendpos ntmpstartpos2 m_aarecords npart m_nstartpos ntmpendpos2 nrelstartpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart ccbbrecord ntmpstartpos1 ntmpendpos1 m_aarecords npart m_dwip m_aarecords npart m_bbrstatus m_aarecords npart ccbbrecord ntmpstartpos2 ntmpendpos2 m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_verified debug_only mapdebug setat m_aarecords npart m_dwip m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nstartpos nrelendpos ntmpendpos m_aarecords npart m_nendpos ntmpstartpos nrelendpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart ccbbrecord ntmpstartpos ntmpendpos m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_verified debug_only mapdebug setat m_aarecords npart m_dwip m_aarecords npart m_nendpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ntmpstartpos m_aarecords npart m_nstartpos ntmpendpos nrelstartpos m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart ccbbrecord ntmpstartpos ntmpendpos m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_verified debug_only mapdebug setat m_aarecords npart m_dwip _debug nclients mapdebug getcount nclients adddebuglogline dlp_default _t corruptionblackbox ndbgverifiedbytes nendpos nstartpos m_aarecords npart getcount ndbgoldentries nclients void c corruption black box corrupted data uint64 n start pos uint64 n end pos if n end pos n start pos emblocksize assert false return convert pos to relative block pos uint16 n part uint16 n start pos partsize uint64 n rel start pos n start pos uint64 n part partsize uint64 n rel end pos n end pos uint64 n part partsize if n rel end pos partsize assert false return if n part uint m aarecords get count assert false m aarecords set size n part 1 uint64 n dbg verified bytes 0 c array uint32 uint32 a guilty clients for int i 0 i m aarecords n part get count i if m aarecords n part i m bbrstatus bbr none if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr corrupted a guilty clients add m aarecords n part i m dwip else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nendpos n rel end pos need to split it 2 uint64 n tmp end pos1 m aarecords n part i m nendpos uint64 n tmp start pos1 n rel end pos 1 uint64 n tmp start pos2 m aarecords n part i m nstartpos uint64 n tmp end pos2 n rel start pos 1 m aarecords n part i m nendpos n rel end pos m aarecords n part i m nstartpos n rel start pos m aarecords n part add ccbb record n tmp start pos1 n tmp end pos1 m aarecords n part i m dwip m aarecords n part i m bbrstatus m aarecords n part add ccbb record n tmp start pos2 n tmp end pos2 m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr corrupted a guilty clients add m aarecords n part i m dwip else if m aarecords n part i m nstartpos n rel start pos m aarecords n part i m nstartpos n rel end pos need to split it uint64 n tmp end pos m aarecords n part i m nendpos uint64 n tmp start pos n rel end pos 1 m aarecords n part i m nendpos n rel end pos m aarecords n part add ccbb record n tmp start pos n tmp end pos m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr corrupted a guilty clients add m aarecords n part i m dwip else if m aarecords n part i m nendpos n rel start pos m aarecords n part i m nendpos n rel end pos need to split it uint64 n tmp start pos m aarecords n part i m nstartpos uint64 n tmp end pos n rel start pos 1 m aarecords n part i m nstartpos n rel start pos m aarecords n part add ccbb record n tmp start pos n tmp end pos m aarecords n part i m dwip m aarecords n part i m bbrstatus n dbg verified bytes m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 m aarecords n part i m bbrstatus bbr corrupted a guilty clients add m aarecords n part i m dwip check if any i ps are already banned so we can skip the test for those for int k 0 k a guilty clients get count remove doubles for int y k 1 y a guilty clients get count if a guilty clients k a guilty clients y a guilty clients remove at y else y if the app clientlist is banned client a guilty clients k add debug log line dlp default false t corruption black box suspicous ip s is already banned skipping recheck ipstr a guilty clients k a guilty clients remove at k else k add debug log line dlp high false t found and marked i64u recorded bytes of i64u as corrupted in the corruption black box records u clients involved n dbg verified bytes n end pos n start pos 1 a guilty clients get count if a guilty clients get count 0 parse all recorded data for this file to produce a statistic for the involved clients first init arrays for the statistic c array uint64 uint64 a data corrupt c array uint64 uint64 a data verified a data corrupt set size a guilty clients get count a data verified set size a guilty clients get count for int j 0 j a guilty clients get count j a data corrupt j a data verified j 0 now the parsing for int n part 0 n part m aarecords get count n part for int i 0 i m aarecords n part get count i for int k 0 k a guilty clients get count k if m aarecords n part i m dwip a guilty clients k if m aarecords n part i m bbrstatus bbr corrupted corrupted data records are always counted as at least blocksize or bigger a data corrupt k max m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 emblocksize else if m aarecords n part i m bbrstatus bbr verified a data verified k m aarecords n part i m nendpos m aarecords n part i m nstartpos 1 for int k 0 k a guilty clients get count k calculate the percentage of corrupted data for each client and ban him if the limit is reached int n corrupt percentage if a data verified k a data corrupt k 0 n corrupt percentage int uint64 a data corrupt k 100 a data verified k a data corrupt k else add debug log line dlp high false t corruption black box programm error no records for guilty client found assert false n corrupt percentage 0 if n corrupt percentage cbb banthreshold c up down client p evil client the app clientlist find client byip a guilty clients k if p evil client null add debug log line dlp high false t corruption black box banning found client which send s of s corrupted data s cast itox bytes a data corrupt k cast itox bytes a data verified k a data corrupt k p evil client dbg get client info the app clientlist add track client p evil client p evil client ban t identified as sender of corrupt data else add debug log line dlp high false t corruption black box banning found client which send s of s corrupted data s cast itox bytes a data corrupt k cast itox bytes a data verified k a data corrupt k ipstr a guilty clients k the app clientlist add banned client a guilty clients k else c up down client p suspect client the app clientlist find client byip a guilty clients k if p suspect client null add debug log line dlp default false t corruption black box reporting found client which probably send s of s corrupted data but it is within the acceptable limit s cast itox bytes a data corrupt k cast itox bytes a data verified k a data corrupt k p suspect client dbg get client info the app clientlist add track client p suspect client else add debug log line dlp default false t corruption black box reporting found client which probably send s of s corrupted data but it is within the acceptable limit s cast itox bytes a data corrupt k cast itox bytes a data verified k a data corrupt k ipstr a guilty clients k ccorruptionblackbox corrupteddata nstartpos nendpos nendpos nstartpos npart nstartpos nrelstartpos nstartpos npart nrelendpos nendpos npart nrelendpos npart m_aarecords getcount m_aarecords setsize npart ndbgverifiedbytes carray aguiltyclients m_aarecords npart getcount m_aarecords npart m_bbrstatus bbr_none m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_corrupted aguiltyclients m_aarecords npart m_dwip m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ntmpendpos1 m_aarecords npart m_nendpos ntmpstartpos1 nrelendpos ntmpstartpos2 m_aarecords npart m_nstartpos ntmpendpos2 nrelstartpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart ccbbrecord ntmpstartpos1 ntmpendpos1 m_aarecords npart m_dwip m_aarecords npart m_bbrstatus m_aarecords npart ccbbrecord ntmpstartpos2 ntmpendpos2 m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_corrupted aguiltyclients m_aarecords npart m_dwip m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart m_nstartpos nrelendpos ntmpendpos m_aarecords npart m_nendpos ntmpstartpos nrelendpos m_aarecords npart m_nendpos nrelendpos m_aarecords npart ccbbrecord ntmpstartpos ntmpendpos m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_corrupted aguiltyclients m_aarecords npart m_dwip m_aarecords npart m_nendpos nrelstartpos m_aarecords npart m_nendpos nrelendpos ntmpstartpos m_aarecords npart m_nstartpos ntmpendpos nrelstartpos m_aarecords npart m_nstartpos nrelstartpos m_aarecords npart ccbbrecord ntmpstartpos ntmpendpos m_aarecords npart m_dwip m_aarecords npart m_bbrstatus ndbgverifiedbytes m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_corrupted aguiltyclients m_aarecords npart m_dwip ips aguiltyclients getcount aguiltyclients getcount aguiltyclients aguiltyclients aguiltyclients removeat theapp isbannedclient aguiltyclients adddebuglogline dlp_default _t corruptionblackbox aguiltyclients aguiltyclients removeat adddebuglogline dlp_high _t corruptionblackbox ndbgverifiedbytes nendpos nstartpos aguiltyclients getcount aguiltyclients getcount carray adatacorrupt carray adataverified adatacorrupt setsize aguiltyclients getcount adataverified setsize aguiltyclients getcount aguiltyclients getcount adatacorrupt adataverified npart npart m_aarecords getcount npart m_aarecords npart getcount aguiltyclients getcount m_aarecords npart m_dwip aguiltyclients m_aarecords npart m_bbrstatus bbr_corrupted adatacorrupt m_aarecords npart m_nendpos m_aarecords npart m_nstartpos m_aarecords npart m_bbrstatus bbr_verified adataverified m_aarecords npart m_nendpos m_aarecords npart m_nstartpos aguiltyclients getcount ncorruptpercentage adataverified adatacorrupt ncorruptpercentage adatacorrupt adataverified adatacorrupt adddebuglogline dlp_high _t corruptionblackbox ncorruptpercentage ncorruptpercentage cbb_banthreshold cupdownclient pevilclient theapp findclientbyip aguiltyclients pevilclient adddebuglogline dlp_high _t corruptionblackbox castitoxbytes adatacorrupt castitoxbytes adataverified adatacorrupt pevilclient dbggetclientinfo theapp addtrackclient pevilclient pevilclient _t adddebuglogline dlp_high _t corruptionblackbox castitoxbytes adatacorrupt castitoxbytes adataverified adatacorrupt aguiltyclients theapp addbannedclient aguiltyclients cupdownclient psuspectclient theapp findclientbyip aguiltyclients psuspectclient adddebuglogline dlp_default _t corruptionblackbox castitoxbytes adatacorrupt castitoxbytes adataverified adatacorrupt psuspectclient dbggetclientinfo theapp addtrackclient psuspectclient adddebuglogline dlp_default _t corruptionblackbox castitoxbytes adatacorrupt castitoxbytes adataverified adatacorrupt aguiltyclients c color frame ctrl c color frame ctrl m crbackcolor rgb 0 0 0 see also set background color m crframecolor rgb 0 255 255 see also set frame color m brushback create solid brush m crbackcolor m brushframe create solid brush m crframecolor ccolorframectrl ccolorframectrl m_crbackcolor setbackgroundcolor m_crframecolor setframecolor m_brushback createsolidbrush m_crbackcolor m_brushframe createsolidbrush m_crframecolor c color frame ctrl c color frame ctrl m brushframe delete object m brushback delete object ccolorframectrl ccolorframectrl m_brushframe deleteobject m_brushback deleteobject bool c color frame ctrl create dword dw style const rect rect c wnd p parent wnd uint nid bool result static c string class name afx register wnd class cs hredraw cs vredraw afx get app load standard cursor idc arrow result c wnd create ex ws ex staticedge class name null dw style rect left rect top rect right rect left rect bottom rect top p parent wnd get safe hwnd hmenu nid if result 0 invalidate return result ccolorframectrl dwstyle cwnd pparentwnd cstring classname afxregisterwndclass cs_hredraw cs_vredraw afxgetapp loadstandardcursor idc_arrow cwnd createex ws_ex_staticedge classname dwstyle pparentwnd getsafehwnd void c color frame ctrl set frame color colorref color m crframecolor color m brushframe delete object m brushframe create solid brush m crframecolor clear out the existing garbage re start with a clean plot invalidate ccolorframectrl setframecolor m_crframecolor m_brushframe deleteobject m_brushframe createsolidbrush m_crframecolor void c color frame ctrl set background color colorref color m crbackcolor color m brushback delete object m brushback create solid brush m crbackcolor clear out the existing garbage re start with a clean plot invalidate ccolorframectrl setbackgroundcolor m_crbackcolor m_brushback deleteobject m_brushback createsolidbrush m_crbackcolor void c color frame ctrl on paint c paintdc dc this device context for painting dc fill rect m rectclient m brushback dc frame rect m rectclient m brushframe ccolorframectrl onpaint cpaintdc fillrect m_rectclient m_brushback framerect m_rectclient m_brushframe void c color frame ctrl on size uint n type int cx int cy note on size automatically gets called during the setup of the control c wnd on size n type cx cy get client rect m rectclient ccolorframectrl onsize ntype onsize cwnd onsize ntype getclientrect m_rectclient c list view walker property sheet p list ctrl m upshinvokepage u psh invoke page position pos a files get head position while pos m aitems add a files get next pos m psh dw flags psh hashelp m wndmetadata m psp dw flags psp hashelp m wndmetadata m psp dw flags psp useiconid m wndmetadata m psp psz icon t metadata if m aitems get size 1 the prefs is ext controls enabled m wndmetadata set files m aitems add page m wndmetadata lpctstr p psh start page m ppshstartpage if m upshinvokepage 0 p psh start page makeintresource m upshinvokepage for int i 0 i m pages get size i c property page p page get page i if p page m psp psz template p psh start page m psh n start page i break clistviewwalkerpropertysheet plistctrl m_upshinvokepage upshinvokepage afiles getheadposition m_aitems afiles getnext m_psh dwflags psh_hashelp m_wndmetadata m_psp dwflags psp_hashelp m_wndmetadata m_psp dwflags psp_useiconid m_wndmetadata m_psp pszicon _t m_aitems getsize theprefs isextcontrolsenabled m_wndmetadata setfiles m_aitems addpage m_wndmetadata ppshstartpage m_ppshstartpage m_upshinvokepage ppshstartpage m_upshinvokepage m_pages getsize cpropertypage ppage getpage ppage m_psp psztemplate ppshstartpage m_psh nstartpage c collection file details sheet c collection file details sheet ccollectionfiledetailssheet ccollectionfiledetailssheet void c collection file details sheet update title if m aitems get size 1 set window text get res string ids details t static downcast c abstract file m aitems 0 get file name else set window text get res string ids details ccollectionfiledetailssheet updatetitle m_aitems getsize setwindowtext getresstring ids_details _t static_downcast cabstractfile m_aitems getfilename setwindowtext getresstring ids_details bool c collection file details sheet on init dialog enable stacked tabs false bool b result c list view walker property sheet on init dialog high color tab update image list this init window styles this enable save restore t collection file details sheet call this after on init dialog update title return b result ccollectionfiledetailssheet oninitdialog enablestackedtabs bresult clistviewwalkerpropertysheet oninitdialog highcolortab updateimagelist initwindowstyles enablesaverestore _t collectionfiledetailssheet oninitdialog updatetitle bresult void c collection file details sheet on destroy if m upshinvokepage 0 m ppshstartpage get page get active index m psp psz template c list view walker property sheet on destroy ccollectionfiledetailssheet ondestroy m_upshinvokepage m_ppshstartpage getpage getactiveindex m_psp psztemplate clistviewwalkerpropertysheet ondestroy lresult c collection file details sheet on data changed wparam lparam update title return 1 ccollectionfiledetailssheet ondatachanged updatetitle c collection file c collection file void ccollectionfile ccollectionfile c collection file c collection file c file dataio in data uint tagcount in data readu int32 for uint i 0 i tagcount i c tag toadd new c tag in data true if toadd taglist add toadd c tag p tag hash get tag ft filehash if p tag hash set file hash p tag hash get hash else assert 0 here we have two choices if the server client sent us a filetype we could use it though it could be wrong we always trust our filetype list and determine the filetype by the extension of the file if we received a filetype from server we use it if we did not receive a filetype we determine it by examining the file s extension but in no case we will use the receive file type when adding this search result to the download queue to avoid that we are using wrong file types in part files this has to be handled when creating the part files const c string rstr file type get str tag value ft filetype set file name get str tag value ft filename false rstr file type is empty set file size get int64 tag value ft filesize if rstr file type is empty if tcscmp rstr file type t ed2kftstr program 0 c string str detail file type get file type by name get file name if str detail file type is empty set file type str detail file type else set file type rstr file type else set file type rstr file type if get file size uint64 0 get file name compare t assert 0 ccollectionfile ccollectionfile cfiledataio in_data in_data readuint32 ctag ctag in_data ctag ptaghash gettag ft_filehash ptaghash setfilehash ptaghash gethash cstring rstrfiletype getstrtagvalue ft_filetype setfilename getstrtagvalue ft_filename rstrfiletype isempty setfilesize getint64tagvalue ft_filesize rstrfiletype isempty _tcscmp rstrfiletype _t ed2kftstr_program cstring strdetailfiletype getfiletypebyname getfilename strdetailfiletype isempty setfiletype strdetailfiletype setfiletype rstrfiletype setfiletype rstrfiletype getfilesize getfilename _t c collection file c collection file c abstract file p abstract file c abstract file p abstract file clear tags taglist add new c tag ft filehash p abstract file get file hash taglist add new c tag ft filesize p abstract file get file size true taglist add new c tag ft filename p abstract file get file name if p abstract file get file comment is empty taglist add new c tag ft filecomment p abstract file get file comment if p abstract file get file rating taglist add new c tag ft filerating p abstract file get file rating update file rating comment avail ccollectionfile ccollectionfile cabstractfile pabstractfile cabstractfile pabstractfile cleartags ctag ft_filehash pabstractfile getfilehash ctag ft_filesize pabstractfile getfilesize ctag ft_filename pabstractfile getfilename pabstractfile getfilecomment isempty ctag ft_filecomment pabstractfile getfilecomment pabstractfile getfilerating ctag ft_filerating pabstractfile getfilerating updatefileratingcommentavail c collection file c collection file void ccollectionfile ccollectionfile bool c collection file init from link c string s link ced2k link p link null ced2k file link p file link null try p link ced2k link create link from url s link if p link throw get res string ids err notafilelink p file link p link get file link if p file link throw get res string ids err notafilelink catch c string error c string str buffer str buffer format get res string ids err invalidlink error log error log statusbar get res string ids err linkerror str buffer return false taglist add new c tag ft filehash p file link get hash key md4cpy m abyfilehash p file link get hash key taglist add new c tag ft filesize p file link get size true set file size p file link get size taglist add new c tag ft filename p file link get name set file name p file link get name false false delete p link return true ccollectionfile initfromlink cstring slink ced2klink plink ced2kfilelink pfilelink plink ced2klink createlinkfromurl slink plink getresstring ids_err_notafilelink pfilelink plink getfilelink pfilelink getresstring ids_err_notafilelink cstring cstring strbuffer strbuffer getresstring ids_err_invalidlink logerror log_statusbar getresstring ids_err_linkerror strbuffer ctag ft_filehash pfilelink gethashkey m_abyfilehash pfilelink gethashkey ctag ft_filesize pfilelink getsize setfilesize pfilelink getsize ctag ft_filename pfilelink getname setfilename pfilelink getname plink void c collection file write collection info c file dataio out data out data writeu int32 taglist get size for int i 0 i taglist get size i c tag temp tag taglist get at i temp tag write new ed2k tag out data utf8str raw ccollectionfile writecollectioninfo cfiledataio out_data out_data writeuint32 getsize getsize ctag temptag getat temptag writenewed2ktag out_data utf8strraw void c collection file update file rating comment avail m bhascomment false uint u ratings 0 uint u user ratings 0 for position pos m kadnotes get head position pos null kademlia c entry entry m kadnotes get next pos if m bhascomment entry get str tag value tag description is empty m bhascomment true uint rating uint entry get int tag value tag filerating if rating 0 u ratings u user ratings rating if u ratings m uuserrating u user ratings u ratings else m uuserrating 0 ccollectionfile updatefileratingcommentavail m_bhascomment uratings uuserratings m_kadnotes getheadposition centry m_kadnotes getnext m_bhascomment getstrtagvalue tag_description isempty m_bhascomment getinttagvalue tag_filerating uratings uuserratings uratings m_uuserrating uuserratings uratings m_uuserrating c base64 coding c base64 coding cbase64coding cbase64coding c base64 coding c base64 coding cbase64coding cbase64coding bool c base64 coding encode const char source int len char destination string const char alphabet abcdefghijklmnopqrstuvwxy zabcdefghijklmnopqrstuvwxyz0123456789 int loop index 0 int number of bytes to encode len byte byte to add 0 byte byte 1 0 byte byte 2 0 byte byte 3 0 dword number of bytes encoded dword double number of bytes to encode double 0 75 1 now add in the cr lf pairs each line is truncated at 72 characters 2000 05 12 thanks go to ilia golubev ilia varicom co il for finding a bug here i was using number of bytes to encode rather than number of bytes encoded number of bytes encoded dword number of bytes encoded base64 number of characters per line 1 2 char destination destination string number of bytes encoded 0 while loop index number of bytes to encode output the first byte byte 1 source loop index byte to add alphabet byte 1 2 destination number of bytes encoded static cast char byte to add number of bytes encoded loop index if loop index number of bytes to encode we re at the end of the data to encode byte 2 0 byte to add alphabet byte 1 0x03 4 byte 2 0xf0 4 destination number of bytes encoded byte to add number of bytes encoded destination number of bytes encoded end of base64 encoded data number of bytes encoded destination number of bytes encoded end of base64 encoded data 1999 09 01 thanks go to yurong lin ylin dial pipex com for finding a bug here we must null terminate the string before letting c string have the buffer back destination number of bytes encoded 1 0 return true else byte 2 source loop index byte to add alphabet byte 1 0x03 4 byte 2 0xf0 4 destination number of bytes encoded byte to add number of bytes encoded loop index if loop index number of bytes to encode we ran out of bytes we need to add the last half of byte 2 and pad byte 3 0 byte to add alphabet byte 2 0x0f 2 byte 3 0xc0 6 destination number of bytes encoded byte to add number of bytes encoded destination number of bytes encoded end of base64 encoded data 1999 09 01 thanks go to yurong lin ylin dial pipex com for finding a bug here we must null terminate the string before letting c string have the buffer back destination number of bytes encoded 1 0 return true else byte 3 source loop index loop index byte to add alphabet byte 2 0x0f 2 byte 3 0xc0 6 destination number of bytes encoded byte to add number of bytes encoded byte to add alphabet byte 3 0x3f destination number of bytes encoded byte to add number of bytes encoded if number of bytes encoded base64 number of characters per line 0 destination number of bytes encoded carriage return number of bytes encoded destination number of bytes encoded line feed number of bytes encoded destination number of bytes encoded end of base64 encoded data 1999 09 01 thanks go to yurong lin ylin dial pipex com for finding a bug here we must null terminate the string before letting c string have the buffer back destination number of bytes encoded 1 0 return true cbase64coding destination_string abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 loop_index number_of_bytes_to_encode byte_to_add byte_1 byte_2 byte_3 number_of_bytes_encoded number_of_bytes_to_encode number_of_bytes_to_encode number_of_bytes_encoded number_of_bytes_encoded number_of_bytes_encoded base64_number_of_characters_per_line destination_string number_of_bytes_encoded loop_index number_of_bytes_to_encode byte_1 loop_index byte_to_add byte_1 number_of_bytes_encoded static_cast byte_to_add number_of_bytes_encoded loop_index loop_index number_of_bytes_to_encode byte_2 byte_to_add byte_1 byte_2 number_of_bytes_encoded byte_to_add number_of_bytes_encoded number_of_bytes_encoded end_of_base64_encoded_data number_of_bytes_encoded number_of_bytes_encoded end_of_base64_encoded_data cstring number_of_bytes_encoded byte_2 loop_index byte_to_add byte_1 byte_2 number_of_bytes_encoded byte_to_add number_of_bytes_encoded loop_index loop_index number_of_bytes_to_encode byte_2 byte_3 byte_to_add byte_2 byte_3 number_of_bytes_encoded byte_to_add number_of_bytes_encoded number_of_bytes_encoded end_of_base64_encoded_data cstring number_of_bytes_encoded byte_3 loop_index loop_index byte_to_add byte_2 byte_3 number_of_bytes_encoded byte_to_add number_of_bytes_encoded byte_to_add byte_3 number_of_bytes_encoded byte_to_add number_of_bytes_encoded number_of_bytes_encoded base64_number_of_characters_per_line number_of_bytes_encoded carriage_return number_of_bytes_encoded number_of_bytes_encoded line_feed number_of_bytes_encoded number_of_bytes_encoded end_of_base64_encoded_data cstring number_of_bytes_encoded c buttonst c buttonst m bispressed false m bisfocused false m bisdisabled false m bmouseonbutton false left aligned false marked false free resources false default type is flat button m bisflat true button will be tracked also if when the window is inactive like internet explorer m balwaystrack true by default draw border in flat button m bdrawborder true by default icon is aligned horizontally m byalign st align horiz by default use usual pressed style set pressed style btnst pressed leftright false by default for flat button don t draw the focus rect m bdrawflatfocus false by default the button is not the default button m bisdefault false invalid value since type still unknown m ntypestyle bs typemask by default the button is not a checkbox m bischeckbox false m ncheck 0 set default colors set default colors false no tooltip created m tooltip m hwnd null do not draw as a transparent button m bdrawtransparent false m pbmpoldbk null no url defined seturl null no cursor defined m hcursor null no associated menu ifndef btnst use bcmenu m hmenu null endif m hparentwndmenu null m bmenudisplayed false m bshowdisabledbitmap true m ptimageorg x 3 m ptimageorg y 3 no defined callbacks zero memory m cscallbacks sizeof m cscallbacks ifdef btnst use sound no defined sounds zero memory m cssounds sizeof m cssounds endif cbuttonst cbuttonst m_bispressed m_bisfocused m_bisdisabled m_bmouseonbutton leftaligned freeresources m_bisflat m_balwaystrack m_bdrawborder m_byalign st_align_horiz setpressedstyle btnst_pressed_leftright m_bdrawflatfocus m_bisdefault m_ntypestyle bs_typemask m_bischeckbox m_ncheck setdefaultcolors m_tooltip m_hwnd m_bdrawtransparent m_pbmpoldbk m_hcursor btnst_use_bcmenu m_hmenu m_hparentwndmenu m_bmenudisplayed m_bshowdisabledbitmap m_ptimageorg m_ptimageorg zeromemory m_cscallbacks m_cscallbacks btnst_use_sound zeromemory m_cssounds m_cssounds c buttonst c buttonst restore old bitmap if any if m dcbk m hdc m pbmpoldbk m dcbk select object m pbmpoldbk if free resources destroy the cursor if any if m hcursor destroy cursor m hcursor destroy the menu if any ifdef btnst use bcmenu if m menupopup m hmenu verify m menupopup destroy menu else if m hmenu verify destroy menu m hmenu endif cbuttonst cbuttonst m_dcbk m_hdc m_pbmpoldbk m_dcbk selectobject m_pbmpoldbk freeresources m_hcursor destroycursor m_hcursor btnst_use_bcmenu m_menupopup m_hmenu m_menupopup destroymenu m_hmenu destroymenu m_hmenu void c buttonst draw item lpdrawitemstruct lpdis cdc pdc cdc from handle lpdis hdc c pen p old pen checkbox if m bischeckbox m bispressed lpdis item state ods selected m ncheck 0 marked if else normal button or other button style m bispressed lpdis item state ods selected marked if there is a menu and it s displayed draw the button as pressed if ifdef btnst use bcmenu m menupopup m hmenu else m hmenu endif m bmenudisplayed m bispressed true else m bisfocused lpdis item state ods focus m bisdisabled lpdis item state ods disabled c rect item rect lpdis rc item pdc set bk mode transparent if m bisflat false if m bisfocused m bisdefault c brush br rgb 0 0 0 pdc frame rect item rect br item rect deflate rect 1 1 if if prepare draw paint button background draw transparent if m bdrawtransparent paint bk pdc else on draw background pdc item rect draw pressed button if m bispressed if m bisflat if m bdrawborder on draw border pdc item rect else c brush br btn shadow get sys color color btnshadow pdc frame rect item rect br btn shadow else else draw non pressed button c pen pen btn hi light ps solid 0 get sys color color btnhilight white c pen pen3d light ps solid 0 get sys color color 3dlight light gray c pen pen btn shadow ps solid 0 get sys color color btnshadow dark gray c pen pen3ddk shadow ps solid 0 get sys color color 3ddkshadow black if m bisflat if m bmouseonbutton m bdrawborder on draw border pdc item rect else draw top left borders white line p old pen pdc select object pen btn hi light pdc move to item rect left item rect bottom 1 pdc line to item rect left item rect top pdc line to item rect right item rect top light gray line pdc select object pen3d light pdc move to item rect left 1 item rect bottom 1 pdc line to item rect left 1 item rect top 1 pdc line to item rect right item rect top 1 draw bottom right borders black line pdc select object pen3ddk shadow pdc move to item rect left item rect bottom 1 pdc line to item rect right 1 item rect bottom 1 pdc line to item rect right 1 item rect top 1 dark gray line pdc select object pen btn shadow pdc move to item rect left 1 item rect bottom 2 pdc line to item rect right 2 item rect bottom 2 pdc line to item rect right 2 item rect top pdc select object p old pen else else read the button s title c string s title get window text s title c rect caption rect lpdis rc item draw the icon if m csicons 0 h icon draw the icon pdc s title is empty lpdis rc item caption rect m bispressed m bisdisabled if if m csbitmaps 0 h bitmap pdc set bk color rgb 255 255 255 draw the bitmap pdc s title is empty lpdis rc item caption rect m bispressed m bisdisabled if write the button title if any if s title is empty false draw the text pdc lpctstr s title lpdis rc item caption rect m bispressed m bisdisabled if if m bisflat false m bisflat m bdrawflatfocus draw the focus rect if m bisfocused c rect focus rect item rect if m bisflat focus rect deflate rect 3 3 pdc draw focus rect focus rect if if cbuttonst drawitem fromhandle cpen poldpen m_bischeckbox m_bispressed itemstate ods_selected m_ncheck m_bispressed itemstate ods_selected btnst_use_bcmenu m_menupopup m_hmenu m_hmenu m_bmenudisplayed m_bispressed m_bisfocused itemstate ods_focus m_bisdisabled itemstate ods_disabled crect itemrect rcitem setbkmode m_bisflat m_bisfocused m_bisdefault cbrush framerect itemrect itemrect deflaterect m_bdrawtransparent paintbk ondrawbackground itemrect m_bispressed m_bisflat m_bdrawborder ondrawborder itemrect cbrush brbtnshadow getsyscolor color_btnshadow framerect itemrect brbtnshadow cpen penbtnhilight ps_solid getsyscolor color_btnhilight cpen pen3dlight ps_solid getsyscolor color_3dlight cpen penbtnshadow ps_solid getsyscolor color_btnshadow cpen pen3ddkshadow ps_solid getsyscolor color_3ddkshadow m_bisflat m_bmouseonbutton m_bdrawborder ondrawborder itemrect poldpen selectobject penbtnhilight moveto itemrect itemrect lineto itemrect itemrect lineto itemrect itemrect selectobject pen3dlight moveto itemrect itemrect lineto itemrect itemrect lineto itemrect itemrect selectobject pen3ddkshadow moveto itemrect itemrect lineto itemrect itemrect lineto itemrect itemrect selectobject penbtnshadow moveto itemrect itemrect lineto itemrect itemrect lineto itemrect itemrect selectobject poldpen cstring stitle getwindowtext stitle crect captionrect rcitem m_csicons hicon drawtheicon stitle isempty rcitem captionrect m_bispressed m_bisdisabled m_csbitmaps hbitmap setbkcolor drawthebitmap stitle isempty rcitem captionrect m_bispressed m_bisdisabled stitle isempty drawthetext stitle rcitem captionrect m_bispressed m_bisdisabled m_bisflat m_bisflat m_bdrawflatfocus m_bisfocused crect focusrect itemrect m_bisflat focusrect deflaterect drawfocusrect focusrect bool c buttonst pre translate message msg p msg init tool tip m tooltip relay event p msg if p msg message wm lbuttondblclk p msg message wm lbuttondown return c button pre translate message p msg cbuttonst pretranslatemessage pmsg inittooltip m_tooltip relayevent pmsg pmsg wm_lbuttondblclk pmsg wm_lbuttondown cbutton pretranslatemessage pmsg void c buttonst pre subclass window uint nbs nbs get button style set initial control type m ntypestyle nbs bs typemask check if this is a checkbox if nbs bs checkbox m bischeckbox true set initial default state flag if m ntypestyle bs defpushbutton set default state for a default button m bisdefault true adjust style for default button m ntypestyle bs pushbutton if you should not set the owner draw before this call don t use the resource editor owner draw or modify style 0 bs ownerdraw before calling pre subclass window assert m ntypestyle bs ownerdraw switch to owner draw modify style bs typemask bs ownerdraw swp framechanged c button pre subclass window cbuttonst presubclasswindow getbuttonstyle m_ntypestyle bs_typemask bs_checkbox m_bischeckbox m_ntypestyle bs_defpushbutton m_bisdefault m_ntypestyle bs_pushbutton modifystyle bs_ownerdraw presubclasswindow m_ntypestyle bs_ownerdraw modifystyle bs_typemask bs_ownerdraw swp_framechanged cbutton presubclasswindow dword c buttonst set default colors bool b repaint m crcolors btnst color bk in get sys color color btnface m crcolors btnst color fg in get sys color color btntext m crcolors btnst color bk out get sys color color btnface m crcolors btnst color fg out get sys color color btntext m crcolors btnst color bk focus get sys color color btnface m crcolors btnst color fg focus get sys color color btntext if b repaint invalidate return btnst ok cbuttonst setdefaultcolors brepaint m_crcolors btnst_color_bk_in getsyscolor color_btnface m_crcolors btnst_color_fg_in getsyscolor color_btntext m_crcolors btnst_color_bk_out getsyscolor color_btnface m_crcolors btnst_color_fg_out getsyscolor color_btntext m_crcolors btnst_color_bk_focus getsyscolor color_btnface m_crcolors btnst_color_fg_focus getsyscolor color_btntext brepaint btnst_ok dword c buttonst set color byte by color index colorref cr color bool b repaint if by color index btnst max colors return btnst invalidindex set new color m crcolors by color index cr color if b repaint invalidate return btnst ok cbuttonst setcolor bycolorindex crcolor brepaint bycolorindex btnst_max_colors btnst_invalidindex m_crcolors bycolorindex crcolor brepaint btnst_ok dword c buttonst get color byte by color index colorref crp color if by color index btnst max colors return btnst invalidindex get color crp color m crcolors by color index return btnst ok cbuttonst getcolor bycolorindex crpcolor bycolorindex btnst_max_colors btnst_invalidindex crpcolor m_crcolors bycolorindex btnst_ok dword c buttonst offset color byte by color index short sh offset bool b repaint byte by red 0 byte by green 0 byte by blue 0 short sh offsetr sh offset short sh offsetg sh offset short sh offsetb sh offset if by color index btnst max colors return btnst invalidindex if sh offset 255 sh offset 255 return btnst badparam get rgb components of specified color by red getr value m crcolors by color index by green getg value m crcolors by color index by blue getb value m crcolors by color index calculate max allowed real offset if sh offset 0 if by red sh offset 255 sh offsetr 255 by red if by green sh offset 255 sh offsetg 255 by green if by blue sh offset 255 sh offsetb 255 by blue sh offset min min sh offsetr sh offsetg sh offsetb if else if by red sh offset 0 sh offsetr by red if by green sh offset 0 sh offsetg by green if by blue sh offset 0 sh offsetb by blue sh offset max max sh offsetr sh offsetg sh offsetb else set new color m crcolors by color index rgb by red sh offset by green sh offset by blue sh offset if b repaint invalidate return btnst ok cbuttonst offsetcolor bycolorindex shoffset brepaint byred bygreen byblue shoffsetr shoffset shoffsetg shoffset shoffsetb shoffset bycolorindex btnst_max_colors btnst_invalidindex shoffset shoffset btnst_badparam byred getrvalue m_crcolors bycolorindex bygreen getgvalue m_crcolors bycolorindex byblue getbvalue m_crcolors bycolorindex shoffset byred shoffset shoffsetr byred bygreen shoffset shoffsetg bygreen byblue shoffset shoffsetb byblue shoffset shoffsetr shoffsetg shoffsetb byred shoffset shoffsetr byred bygreen shoffset shoffsetg bygreen byblue shoffset shoffsetb byblue shoffset shoffsetr shoffsetg shoffsetb m_crcolors bycolorindex byred shoffset bygreen shoffset byblue shoffset brepaint btnst_ok dword c buttonst set check int n check bool b repaint if m bischeckbox if n check 0 m ncheck 0 else m ncheck 1 if b repaint invalidate if return btnst ok cbuttonst setcheck ncheck brepaint m_bischeckbox ncheck m_ncheck m_ncheck brepaint btnst_ok int c buttonst get check return m ncheck cbuttonst getcheck m_ncheck dword c buttonst seturl lpctstr lpszurl remove any existing url memset m szurl 0 sizeof m szurl if lpszurl store the url tcsncpy m szurl lpszurl max path if return btnst ok cbuttonst m_szurl m_szurl _tcsncpy m_szurl _max_path btnst_ok void c buttonst draw transparent bool b repaint m bdrawtransparent true restore old bitmap if any if m dcbk m hdc null m pbmpoldbk null m dcbk select object m pbmpoldbk if m bmpbk delete object m dcbk deletedc repaint the button if b repaint invalidate cbuttonst drawtransparent brepaint m_bdrawtransparent m_dcbk m_hdc m_pbmpoldbk m_dcbk selectobject m_pbmpoldbk m_bmpbk deleteobject m_dcbk brepaint dword c buttonst set bk cdc pdc if m bdrawtransparent pdc restore old bitmap if any if m dcbk m hdc null m pbmpoldbk null m dcbk select object m pbmpoldbk if m bmpbk delete object m dcbk deletedc c rect rect c rect rect1 get client rect rect get window rect rect1 get parent screen to client rect1 m dcbk create compatibledc pdc m bmpbk create compatible bitmap pdc rect width rect height m pbmpoldbk m dcbk select object m bmpbk m dcbk bit blt 0 0 rect width rect height pdc rect1 left rect1 top srccopy return btnst ok if return btnst badparam cbuttonst setbk m_bdrawtransparent m_dcbk m_hdc m_pbmpoldbk m_dcbk selectobject m_pbmpoldbk m_bmpbk deleteobject m_dcbk crect crect getclientrect getwindowrect getparent screentoclient m_dcbk createcompatibledc m_bmpbk createcompatiblebitmap m_pbmpoldbk m_dcbk selectobject m_bmpbk m_dcbk bitblt btnst_ok btnst_badparam bool c buttonst get default return m bisdefault cbuttonst getdefault m_bisdefault dword c buttonst set always track bool b always track m balwaystrack b always track return btnst ok cbuttonst setalwaystrack balwaystrack m_balwaystrack balwaystrack btnst_ok void c buttonst set tooltip text int n text bool b activate c string s text load string resource s text load string n text if string resource is not empty if s text is empty false set tooltip text lpctstr s text b activate cbuttonst settooltiptext ntext bactivate cstring stext stext loadstring ntext stext isempty settooltiptext stext bactivate void c buttonst set tooltip text lpctstr lpsz text bool b activate we cannot accept null pointer if lpsz text null return initialize tool tip init tool tip if there is no tooltip defined then add it if m tooltip get tool count 0 c rect rect btn get client rect rect btn m tooltip add tool this lpsz text rect btn 1 if set text for tooltip m tooltip update tip text lpsz text this 1 m tooltip activate b activate cbuttonst settooltiptext lpsztext bactivate lpsztext tooltip inittooltip m_tooltip gettoolcount crect rectbtn getclientrect rectbtn m_tooltip addtool lpsztext rectbtn m_tooltip updatetiptext lpsztext m_tooltip bactivate void c buttonst activate tooltip bool b activate if there is no tooltip then do nothing if m tooltip get tool count 0 return activate tooltip m tooltip activate b activate cbuttonst activatetooltip bactivate m_tooltip gettoolcount m_tooltip bactivate dword c buttonst set btn cursor int n cursor id bool b repaint hinstance h inst resource null destroy any previous cursor if m hcursor destroy cursor m hcursor m hcursor null if load cursor if n cursor id h inst resource afx find resource handle makeintresource n cursor id rt group cursor load cursor resource m hcursor hcursor load image h inst resource makeintresource n cursor id image cursor 0 0 0 repaint the button if b repaint invalidate if something wrong if m hcursor null return btnst invalidresource if return btnst ok cbuttonst setbtncursor ncursorid brepaint hinstresource m_hcursor destroycursor m_hcursor m_hcursor ncursorid hinstresource afxfindresourcehandle ncursorid rt_group_cursor m_hcursor loadimage hinstresource ncursorid image_cursor brepaint m_hcursor btnst_invalidresource btnst_ok dword c buttonst set flat bool b flat bool b repaint m bisflat b flat if b repaint invalidate return btnst ok cbuttonst setflat bflat brepaint m_bisflat bflat brepaint btnst_ok dword c buttonst set align byte by align bool b repaint switch by align case st align horiz case st align horiz right case st align vert case st align overlap m byalign by align if b repaint invalidate return btnst ok break switch return btnst invalidalign cbuttonst setalign byalign brepaint byalign st_align_horiz st_align_horiz_right st_align_vert st_align_overlap m_byalign byalign brepaint btnst_ok btnst_invalidalign dword c buttonst set pressed style byte by style bool b repaint switch by style case btnst pressed leftright m ptpressedoffset x 1 m ptpressedoffset y 1 break case btnst pressed topbottom m ptpressedoffset x 0 m ptpressedoffset y 2 break default return btnst invalidpressedstyle switch if b repaint invalidate return btnst ok cbuttonst setpressedstyle bystyle brepaint bystyle btnst_pressed_leftright m_ptpressedoffset m_ptpressedoffset btnst_pressed_topbottom m_ptpressedoffset m_ptpressedoffset btnst_invalidpressedstyle brepaint btnst_ok dword c buttonst draw border bool b draw border bool b repaint m bdrawborder b draw border repaint the button if b repaint invalidate return btnst ok cbuttonst drawborder bdrawborder brepaint m_bdrawborder bdrawborder brepaint btnst_ok dword c buttonst draw flat focus bool b draw flat focus bool b repaint m bdrawflatfocus b draw flat focus repaint the button if b repaint invalidate return btnst ok cbuttonst drawflatfocus bdrawflatfocus brepaint m_bdrawflatfocus bdrawflatfocus brepaint btnst_ok dword c buttonst set icon hicon h icon in hicon h icon out bool b ret value iconinfo ii free any loaded resource free resources if h icon in icon when mouse over button m csicons 0 h icon h icon in get icon dimension zero memory ii sizeof iconinfo b ret value get icon info h icon in ii if b ret value false free resources return btnst invalidresource if m csicons 0 dw width dword ii x hotspot 2 m csicons 0 dw height dword ii y hotspot 2 verify delete object ii hbm mask verify delete object ii hbm color icon when mouse outside button if h icon out if h icon out btnst auto gray h icon out create grayscale icon h icon in if m csicons 1 h icon h icon out get icon dimension zero memory ii sizeof iconinfo b ret value get icon info h icon out ii if b ret value false free resources return btnst invalidresource if m csicons 1 dw width dword ii x hotspot 2 m csicons 1 dw height dword ii y hotspot 2 verify delete object ii hbm mask verify delete object ii hbm color if if invalidate return btnst ok cbuttonst seticon hiconin hiconout bretvalue freeresources hiconin m_csicons hicon hiconin zeromemory bretvalue geticoninfo hiconin bretvalue freeresources btnst_invalidresource m_csicons dwwidth xhotspot m_csicons dwheight yhotspot deleteobject hbmmask deleteobject hbmcolor hiconout hiconout btnst_auto_gray hiconout creategrayscaleicon hiconin m_csicons hicon hiconout zeromemory bretvalue geticoninfo hiconout bretvalue freeresources btnst_invalidresource m_csicons dwwidth xhotspot m_csicons dwheight yhotspot deleteobject hbmmask deleteobject hbmcolor btnst_ok dword c buttonst set icon lpctstr psz icon in lpctstr psz icon out hicon h icon in null hicon h icon out null set icon when the mouse is in the button h icon in the app load icon psz icon in 16 16 set icon when the mouse is out the button if psz icon out if uint psz icon out uint btnst auto gray h icon out btnst auto gray else h icon out the app load icon psz icon out 16 16 if return set icon h icon in h icon out cbuttonst seticon psziconin psziconout hiconin hiconout hiconin theapp loadicon psziconin psziconout psziconout btnst_auto_gray hiconout btnst_auto_gray hiconout theapp loadicon psziconout seticon hiconin hiconout dword c buttonst set bitmaps int n bitmap in colorref cr trans color in int n bitmap out colorref cr trans color out hbitmap h bitmap in null hbitmap h bitmap out null hinstance h inst resource null find correct resource handle h inst resource afx find resource handle makeintresource n bitmap in rt bitmap load bitmap in h bitmap in hbitmap load image h inst resource makeintresource n bitmap in image bitmap 0 0 0 load bitmap out if n bitmap out h bitmap out hbitmap load image h inst resource makeintresource n bitmap out image bitmap 0 0 0 return set bitmaps h bitmap in cr trans color in h bitmap out cr trans color out cbuttonst setbitmaps nbitmapin crtranscolorin nbitmapout crtranscolorout hbitmapin hbitmapout hinstresource hinstresource afxfindresourcehandle nbitmapin rt_bitmap hbitmapin loadimage hinstresource nbitmapin image_bitmap nbitmapout hbitmapout loadimage hinstresource nbitmapout image_bitmap setbitmaps hbitmapin crtranscolorin hbitmapout crtranscolorout dword c buttonst set bitmaps hbitmap h bitmap in colorref cr trans color in hbitmap h bitmap out colorref cr trans color out int n ret value bitmap cs bitmap size free any loaded resource free resources if h bitmap in m csbitmaps 0 h bitmap h bitmap in m csbitmaps 0 cr transparent cr trans color in get bitmap size n ret value get object h bitmap in sizeof cs bitmap size cs bitmap size if n ret value 0 free resources return btnst invalidresource if m csbitmaps 0 dw width dword cs bitmap size bm width m csbitmaps 0 dw height dword cs bitmap size bm height create mask for bitmap in m csbitmaps 0 h mask create bitmap mask h bitmap in m csbitmaps 0 dw width m csbitmaps 0 dw height cr trans color in if m csbitmaps 0 h mask null free resources return btnst failedmask if if h bitmap out m csbitmaps 1 h bitmap h bitmap out m csbitmaps 1 cr transparent cr trans color out get bitmap size n ret value get object h bitmap out sizeof cs bitmap size cs bitmap size if n ret value 0 free resources return btnst invalidresource if m csbitmaps 1 dw width dword cs bitmap size bm width m csbitmaps 1 dw height dword cs bitmap size bm height create mask for bitmap out m csbitmaps 1 h mask create bitmap mask h bitmap out m csbitmaps 1 dw width m csbitmaps 1 dw height cr trans color out if m csbitmaps 1 h mask null free resources return btnst failedmask if if if invalidate return btnst ok cbuttonst setbitmaps hbitmapin crtranscolorin hbitmapout crtranscolorout nretvalue csbitmapsize freeresources hbitmapin m_csbitmaps hbitmap hbitmapin m_csbitmaps crtransparent crtranscolorin nretvalue getobject hbitmapin csbitmapsize csbitmapsize nretvalue freeresources btnst_invalidresource m_csbitmaps dwwidth csbitmapsize bmwidth m_csbitmaps dwheight csbitmapsize bmheight m_csbitmaps hmask createbitmapmask hbitmapin m_csbitmaps dwwidth m_csbitmaps dwheight crtranscolorin m_csbitmaps hmask freeresources btnst_failedmask hbitmapout m_csbitmaps hbitmap hbitmapout m_csbitmaps crtransparent crtranscolorout nretvalue getobject hbitmapout csbitmapsize csbitmapsize nretvalue freeresources btnst_invalidresource m_csbitmaps dwwidth csbitmapsize bmwidth m_csbitmaps dwheight csbitmapsize bmheight m_csbitmaps hmask createbitmapmask hbitmapout m_csbitmaps dwwidth m_csbitmaps dwheight crtranscolorout m_csbitmaps hmask freeresources btnst_failedmask btnst_ok void c buttonst size to content if m csicons 0 h icon m ptimageorg x 0 m ptimageorg y 0 set window pos null 1 1 m csicons 0 dw width m csicons 0 dw height swp nomove swp nozorder swp noredraw swp noactivate if else if m csbitmaps 0 h bitmap m ptimageorg x 0 m ptimageorg y 0 set window pos null 1 1 m csbitmaps 0 dw width m csbitmaps 0 dw height swp nomove swp nozorder swp noredraw swp noactivate if cbuttonst sizetocontent m_csicons hicon m_ptimageorg m_ptimageorg setwindowpos m_csicons dwwidth m_csicons dwheight swp_nomove swp_nozorder swp_noredraw swp_noactivate m_csbitmaps hbitmap m_ptimageorg m_ptimageorg setwindowpos m_csbitmaps dwwidth m_csbitmaps dwheight swp_nomove swp_nozorder swp_noredraw swp_noactivate dword c buttonst set menu uint n menu hwnd h parent wnd bool b repaint hinstance h inst resource null destroy any previous menu if m hmenu verify destroy menu m hmenu m hmenu null m hparentwndmenu null m bmenudisplayed false if load menu if n menu find correct resource handle h inst resource afx find resource handle makeintresource n menu rt menu load menu resource m hmenu load menu h inst resource makeintresource n menu m hparentwndmenu h parent wnd if something wrong if m hmenu null return btnst invalidresource if repaint the button if b repaint invalidate return btnst ok cbuttonst setmenu nmenu hparentwnd brepaint hinstresource m_hmenu destroymenu m_hmenu m_hmenu m_hparentwndmenu m_bmenudisplayed nmenu hinstresource afxfindresourcehandle nmenu rt_menu m_hmenu loadmenu hinstresource nmenu m_hparentwndmenu hparentwnd m_hmenu btnst_invalidresource brepaint btnst_ok dword c buttonst set menu callback hwnd h wnd uint n message lparam l param m cscallbacks h wnd h wnd m cscallbacks n message n message m cscallbacks l param l param return btnst ok cbuttonst setmenucallback hwnd nmessage lparam m_cscallbacks hwnd hwnd m_cscallbacks nmessage nmessage m_cscallbacks lparam lparam btnst_ok bool c buttonst on set cursor c wnd p wnd uint n hit test uint message if a cursor was specified then use it if m hcursor null set cursor m hcursor return true if return c button on set cursor p wnd n hit test message cbuttonst onsetcursor cwnd pwnd nhittest m_hcursor setcursor m_hcursor cbutton onsetcursor pwnd nhittest void c buttonst on kill focus c wnd p new wnd c button on kill focus p new wnd cancel hover cbuttonst onkillfocus cwnd pnewwnd cbutton onkillfocus pnewwnd cancelhover void c buttonst on mouse move uint n flags c point point c wnd wnd under mouse null c wnd wnd active this trackmouseevent cstme c button on mouse move n flags point client to screen point wnd under mouse window from point point if the mouse enter the button with the left button pressed then do nothing if n flags mk lbutton m bmouseonbutton false return if our button is not flat then do nothing if m bisflat false return if m balwaystrack false wnd active get active window if wnd under mouse wnd under mouse m hwnd m hwnd wnd active if m bmouseonbutton m bmouseonbutton true invalidate ifdef btnst use sound play sound if m cssounds 0 lpsz sound play sound m cssounds 0 lpsz sound m cssounds 0 h mod m cssounds 0 dw flags endif cstme cb size sizeof cstme cstme dw flags tme leave cstme hwnd track m hwnd trackmouseevent cstme if else cancel hover cbuttonst onmousemove nflags cpoint cwnd wndundermouse cwnd wndactive cbutton onmousemove nflags clienttoscreen wndundermouse windowfrompoint nflags mk_lbutton m_bmouseonbutton m_bisflat m_balwaystrack wndactive getactivewindow wndundermouse wndundermouse m_hwnd m_hwnd wndactive m_bmouseonbutton m_bmouseonbutton btnst_use_sound m_cssounds lpszsound playsound m_cssounds lpszsound m_cssounds hmod m_cssounds dwflags cbsize dwflags tme_leave hwndtrack m_hwnd _trackmouseevent cancelhover void c buttonst on sys color change c button on sys color change m dcbk deletedc m bmpbk delete object set default colors cbuttonst onsyscolorchange cbutton onsyscolorchange m_dcbk m_bmpbk deleteobject setdefaultcolors bool c buttonst on clicked set focus ifdef btnst use sound play sound if m cssounds 1 lpsz sound play sound m cssounds 1 lpsz sound m cssounds 1 h mod m cssounds 1 dw flags endif if m bischeckbox m ncheck m ncheck invalidate if else handle the menu if any ifdef btnst use bcmenu if m menupopup m hmenu else if m hmenu endif c rect r wnd get window rect r wnd m bmenudisplayed true invalidate ifdef btnst use bcmenu bc menu psub bc menu m menupopup get sub menu 0 if m cscallbacks h wnd send message m cscallbacks h wnd m cscallbacks n message wparam psub m cscallbacks l param dword dw ret value psub track popup menu tpm leftalign tpm leftbutton tpm rightbutton tpm nonotify tpm returncmd r wnd left r wnd bottom this null else hmenu h sub menu get sub menu m hmenu 0 if m cscallbacks h wnd send message m cscallbacks h wnd m cscallbacks n message wparam h sub menu m cscallbacks l param dword dw ret value track popup menu ex h sub menu tpm leftalign tpm leftbutton tpm rightbutton tpm nonotify tpm returncmd r wnd left r wnd bottom m hparentwndmenu null endif m bmenudisplayed false invalidate if dw ret value post message m hparentwndmenu wm command makewparam dw ret value 0 lparam null if else handle the url if any if tcslen m szurl 0 shellexecuteinfo cssei memset cssei 0 sizeof cssei cssei cb size sizeof shellexecuteinfo cssei f mask see mask flag no ui cssei lp verb t open cssei lp file m szurl cssei n show sw showmaximized shell execute ex cssei if else else return false cbuttonst onclicked setfocus btnst_use_sound m_cssounds lpszsound playsound m_cssounds lpszsound m_cssounds hmod m_cssounds dwflags m_bischeckbox m_ncheck m_ncheck btnst_use_bcmenu m_menupopup m_hmenu m_hmenu crect rwnd getwindowrect rwnd m_bmenudisplayed btnst_use_bcmenu bcmenu bcmenu m_menupopup getsubmenu m_cscallbacks hwnd sendmessage m_cscallbacks hwnd m_cscallbacks nmessage m_cscallbacks lparam dwretvalue trackpopupmenu tpm_leftalign tpm_leftbutton tpm_rightbutton tpm_nonotify tpm_returncmd rwnd rwnd hsubmenu getsubmenu m_hmenu m_cscallbacks hwnd sendmessage m_cscallbacks hwnd m_cscallbacks nmessage hsubmenu m_cscallbacks lparam dwretvalue trackpopupmenuex hsubmenu tpm_leftalign tpm_leftbutton tpm_rightbutton tpm_nonotify tpm_returncmd rwnd rwnd m_hparentwndmenu m_bmenudisplayed dwretvalue postmessage m_hparentwndmenu wm_command dwretvalue _tcslen m_szurl cbsize fmask see_mask_flag_no_ui lpverb _t lpfile m_szurl nshow sw_showmaximized shellexecuteex void c buttonst on activate uint n state c wnd p wnd other bool b minimized c button on activate n state p wnd other b minimized if n state wa inactive marked cancel hover cbuttonst onactivate nstate cwnd pwndother bminimized cbutton onactivate nstate pwndother bminimized nstate wa_inactive cancelhover void c buttonst on enable bool b enable c button on enable b enable if b enable false c wnd p wnd get parent get next dlg tab item this if p wnd p wnd set focus else get parent set focus cancel hover if cbuttonst onenable benable cbutton onenable benable benable cwnd pwnd getparent getnextdlgtabitem pwnd pwnd setfocus getparent setfocus cancelhover void c buttonst on cancel mode c button on cancel mode cancel hover cbuttonst oncancelmode cbutton oncancelmode cancelhover uint c buttonst on get dlg code uint n code c button on get dlg code tell the system if we want default state handling losing default state always allowed n code m bisdefault dlgc defpushbutton dlgc undefpushbutton return n code cbuttonst ongetdlgcode ncode cbutton ongetdlgcode ncode m_bisdefault dlgc_defpushbutton dlgc_undefpushbutton ncode hbrush c buttonst ctl color cdc pdc uint n ctl color return hbrush get stock object null brush cbuttonst ctlcolor nctlcolor getstockobject null_brush hicon c buttonst create grayscale icon hicon h icon hicon h gray icon null hdc h maindc null h memdc1 null h memdc2 null bitmap bmp hbitmap h old bmp1 null h old bmp2 null iconinfo csii cs grayii bool b ret value false b ret value get icon info h icon csii if b ret value false return null h maindc getdc null h memdc1 create compatibledc h maindc h memdc2 create compatibledc h maindc if h maindc null h memdc1 null h memdc2 null return null if get object csii hbm color sizeof bitmap bmp dword dw width csii x hotspot 2 dword dw height csii y hotspot 2 cs grayii hbm color create bitmap dw width dw height bmp bm planes bmp bm bits pixel null if cs grayii hbm color h old bmp1 hbitmap select object h memdc1 csii hbm color h old bmp2 hbitmap select object h memdc2 cs grayii hbm color bit blt h memdc2 0 0 dw width dw height h memdc1 0 0 srccopy dword dw loopy 0 dw loopx 0 colorref cr pixel 0 byte by new pixel 0 for dw loopy 0 dw loopy dw height dw loopy for dw loopx 0 dw loopx dw width dw loopx cr pixel get pixel h memdc1 dw loopx dw loopy by new pixel byte getr value cr pixel 0 299 getg value cr pixel 0 587 getb value cr pixel 0 114 if cr pixel set pixel h memdc2 dw loopx dw loopy rgb by new pixel by new pixel by new pixel for for select object h memdc1 h old bmp1 select object h memdc2 h old bmp2 cs grayii hbm mask csii hbm mask cs grayii f icon true h gray icon create icon indirect cs grayii if verify delete object cs grayii hbm color delete object cs grayii hbm mask if verify delete object csii hbm color verify delete object csii hbm mask verify deletedc h memdc1 verify deletedc h memdc2 releasedc null h maindc return h gray icon cbuttonst creategrayscaleicon hicon hgrayicon hmaindc hmemdc1 hmemdc2 holdbmp1 holdbmp2 csgrayii bretvalue bretvalue geticoninfo hicon bretvalue hmaindc hmemdc1 createcompatibledc hmaindc hmemdc2 createcompatibledc hmaindc hmaindc hmemdc1 hmemdc2 getobject hbmcolor dwwidth xhotspot dwheight yhotspot csgrayii hbmcolor createbitmap dwwidth dwheight bmplanes bmbitspixel csgrayii hbmcolor holdbmp1 selectobject hmemdc1 hbmcolor holdbmp2 selectobject hmemdc2 csgrayii hbmcolor bitblt hmemdc2 dwwidth dwheight hmemdc1 dwloopy dwloopx crpixel bynewpixel dwloopy dwloopy dwheight dwloopy dwloopx dwloopx dwwidth dwloopx crpixel getpixel hmemdc1 dwloopx dwloopy bynewpixel getrvalue crpixel getgvalue crpixel getbvalue crpixel crpixel setpixel hmemdc2 dwloopx dwloopy bynewpixel bynewpixel bynewpixel selectobject hmemdc1 holdbmp1 selectobject hmemdc2 holdbmp2 csgrayii hbmmask hbmmask csgrayii ficon hgrayicon createiconindirect csgrayii deleteobject csgrayii hbmcolor deleteobject csgrayii hbmmask deleteobject hbmcolor deleteobject hbmmask hmemdc1 hmemdc2 hmaindc hgrayicon dword c buttonst on draw background cdc pdc lpcrect p rect colorref cr color if m bmouseonbutton m bispressed cr color m crcolors btnst color bk in else if m bisfocused cr color m crcolors btnst color bk focus else cr color m crcolors btnst color bk out else c brush br background cr color pdc fill rect p rect br background return btnst ok cbuttonst ondrawbackground prect crcolor m_bmouseonbutton m_bispressed crcolor m_crcolors btnst_color_bk_in m_bisfocused crcolor m_crcolors btnst_color_bk_focus crcolor m_crcolors btnst_color_bk_out cbrush brbackground crcolor fillrect prect brbackground btnst_ok dword c buttonst on draw border cdc pdc lpcrect p rect if m bispressed pdc draw3d rect p rect get sys color color btnshadow get sys color color btnhilight else pdc draw3d rect p rect get sys color color btnhilight get sys color color btnshadow return btnst ok cbuttonst ondrawborder prect m_bispressed draw3drect prect getsyscolor color_btnshadow getsyscolor color_btnhilight draw3drect prect getsyscolor color_btnhilight getsyscolor color_btnshadow btnst_ok lresult c buttonst on set check wparam w param lparam l param assert m bischeckbox switch w param case bst checked case bst indeterminate indeterminate state is handled like checked state set check 1 break default set check 0 break switch return 0 cbuttonst onsetcheck wparam lparam m_bischeckbox wparam bst_checked bst_indeterminate setcheck setcheck lresult c buttonst on get check wparam w param lparam l param assert m bischeckbox return get check cbuttonst ongetcheck wparam lparam m_bischeckbox getcheck lresult c buttonst on set style wparam w param lparam l param uint n new type w param bs typemask update default state flag if n new type bs defpushbutton m bisdefault true if else if n new type bs pushbutton losing default state always allowed m bisdefault false if can t change control type after owner draw is set let the system process changes to other style bits and redrawing while keeping owner draw style return def window proc bm setstyle w param bs typemask bs ownerdraw l param cbuttonst onsetstyle wparam lparam nnewtype wparam bs_typemask nnewtype bs_defpushbutton m_bisdefault nnewtype bs_pushbutton m_bisdefault defwindowproc bm_setstyle wparam bs_typemask bs_ownerdraw lparam lresult c buttonst on mouse leave wparam w param lparam l param cancel hover return 0 cbuttonst onmouseleave wparam lparam cancelhover void c buttonst free resources bool b check fornull if b check fornull destroy icons note the following two lines must be here even if bound checker says they are unnecessary if m csicons 0 h icon verify destroy icon m csicons 0 h icon if m csicons 1 h icon verify destroy icon m csicons 1 h icon destroy bitmaps if m csbitmaps 0 h bitmap verify delete object m csbitmaps 0 h bitmap if m csbitmaps 1 h bitmap verify delete object m csbitmaps 1 h bitmap destroy mask bitmaps if m csbitmaps 0 h mask verify delete object m csbitmaps 0 h mask if m csbitmaps 1 h mask verify delete object m csbitmaps 1 h mask if zero memory m csicons sizeof m csicons zero memory m csbitmaps sizeof m csbitmaps cbuttonst freeresources bcheckfornull bcheckfornull boundchecker m_csicons hicon destroyicon m_csicons hicon m_csicons hicon destroyicon m_csicons hicon m_csbitmaps hbitmap deleteobject m_csbitmaps hbitmap m_csbitmaps hbitmap deleteobject m_csbitmaps hbitmap m_csbitmaps hmask deleteobject m_csbitmaps hmask m_csbitmaps hmask deleteobject m_csbitmaps hmask zeromemory m_csicons m_csicons zeromemory m_csbitmaps m_csbitmaps void c buttonst prepare image rect bool b has title rect rp item c rect rp title bool b is pressed dword dw width dword dw height c rect rp image c rect r btn rp image copy rect rp item switch m byalign case st align horiz if b has title false center image horizontally rp image left rp image width long dw width 2 else image must be placed just inside the focus rect rp image left m ptimageorg x rp title left dw width m ptimageorg x center image vertically rp image top rp image height long dw height 2 break case st align horiz right get client rect r btn if b has title false center image horizontally rp image left rp image width long dw width 2 else image must be placed just inside the focus rect rp title right rp title width dw width m ptimageorg x rp title left m ptimageorg x rp image left r btn right dw width m ptimageorg x center image vertically rp image top rp image height long dw height 2 break case st align vert center image horizontally rp image left rp image width long dw width 2 if b has title false center image vertically rp image top rp image height long dw height 2 else rp image top m ptimageorg y rp title top dw height break case st align overlap break switch if button is pressed then press image also if b is pressed m bischeckbox false rp image offset rect m ptpressedoffset x m ptpressedoffset y cbuttonst prepareimagerect bhastitle rpitem crect rptitle bispressed dwwidth dwheight crect rpimage crect rbtn rpimage copyrect rpitem m_byalign st_align_horiz bhastitle rpimage rpimage dwwidth rpimage m_ptimageorg rptitle dwwidth m_ptimageorg rpimage rpimage dwheight st_align_horiz_right getclientrect rbtn bhastitle rpimage rpimage dwwidth rptitle rptitle dwwidth m_ptimageorg rptitle m_ptimageorg rpimage rbtn dwwidth m_ptimageorg rpimage rpimage dwheight st_align_vert rpimage rpimage dwwidth bhastitle rpimage rpimage dwheight rpimage m_ptimageorg rptitle dwheight st_align_overlap bispressed m_bischeckbox rpimage offsetrect m_ptpressedoffset m_ptpressedoffset hbitmap c buttonst create bitmap mask hbitmap h source bitmap dword dw width dword dw height colorref cr trans color hbitmap h mask null hdc hdc src null hdc hdc dest null hbitmap hbm srct null hbitmap hbm destt null colorref cr save bk colorref cr save dest text h mask create bitmap dw width dw height 1 1 null if h mask null return null hdc src create compatibledc null hdc dest create compatibledc null hbm srct hbitmap select object hdc src h source bitmap hbm destt hbitmap select object hdc dest h mask cr save bk set bk color hdc src cr trans color bit blt hdc dest 0 0 dw width dw height hdc src 0 0 srccopy cr save dest text set text color hdc src rgb 255 255 255 set bk color hdc src rgb 0 0 0 bit blt hdc src 0 0 dw width dw height hdc dest 0 0 srcand set text color hdc dest cr save dest text set bk color hdc src cr save bk select object hdc src hbm srct select object hdc dest hbm destt deletedc hdc src deletedc hdc dest return h mask cbuttonst createbitmapmask hsourcebitmap dwwidth dwheight crtranscolor hmask hdcsrc hdcdest hbmsrct hbmdestt crsavebk crsavedesttext hmask createbitmap dwwidth dwheight hmask hdcsrc createcompatibledc hdcdest createcompatibledc hbmsrct selectobject hdcsrc hsourcebitmap hbmdestt selectobject hdcdest hmask crsavebk setbkcolor hdcsrc crtranscolor bitblt hdcdest dwwidth dwheight hdcsrc crsavedesttext settextcolor hdcsrc setbkcolor hdcsrc bitblt hdcsrc dwwidth dwheight hdcdest settextcolor hdcdest crsavedesttext setbkcolor hdcsrc crsavebk selectobject hdcsrc hbmsrct selectobject hdcdest hbmdestt hdcsrc hdcdest hmask void c buttonst draw the icon cdc pdc bool b has title rect rp item c rect rp caption bool b is pressed bool b is disabled byte by index 0 select the icon to use if m bischeckbox b is pressed m bischeckbox b is pressed m bmouseonbutton by index 0 else by index m csicons 1 h icon null 0 1 c rect r image prepare image rect b has title rp item rp caption b is pressed m csicons by index dw width m csicons by index dw height r image ole pdc draw state r image top left r image size m csicons by index h icon b is disabled dss disabled dss normal c brush null cbuttonst drawtheicon bhastitle rpitem crect rpcaption bispressed bisdisabled byindex m_bischeckbox bispressed m_bischeckbox bispressed m_bmouseonbutton byindex byindex m_csicons hicon crect rimage prepareimagerect bhastitle rpitem rpcaption bispressed m_csicons byindex dwwidth m_csicons byindex dwheight rimage drawstate rimage topleft rimage m_csicons byindex hicon bisdisabled dss_disabled dss_normal cbrush void c buttonst draw the bitmap cdc pdc bool b has title rect rp item c rect rp caption bool b is pressed bool b is disabled hdc hdc bmp mem null hbitmap hbm old bmp null hdc hdc mem null hbitmap hbmt null byte by index 0 select the bitmap to use if m bischeckbox b is pressed m bischeckbox b is pressed m bmouseonbutton by index 0 else by index m csbitmaps 1 h bitmap null 0 1 c rect r image prepare image rect b has title rp item rp caption b is pressed m csbitmaps by index dw width m csbitmaps by index dw height r image hdc bmp mem create compatibledc pdc m hdc hbm old bmp hbitmap select object hdc bmp mem m csbitmaps by index h bitmap hdc mem create compatibledc null hbmt hbitmap select object hdc mem m csbitmaps by index h mask if b is disabled m bshowdisabledbitmap hdc hdc null hbitmap h bitmap null hdc create compatibledc pdc m hdc h bitmap create compatible bitmap pdc m hdc m csbitmaps by index dw width m csbitmaps by index dw height hbitmap h old bmp2 hbitmap select object hdc h bitmap rect r rect r rect left 0 r rect top 0 r rect right r image right 1 r rect bottom r image bottom 1 fill rect hdc r rect hbrush rgb 255 255 255 colorref cr old color set bk color hdc rgb 255 255 255 bit blt hdc 0 0 m csbitmaps by index dw width m csbitmaps by index dw height hdc mem 0 0 srcand bit blt hdc 0 0 m csbitmaps by index dw width m csbitmaps by index dw height hdc bmp mem 0 0 srcpaint set bk color hdc cr old color select object hdc h old bmp2 deletedc hdc pdc draw state c point r image left 1 r image top c size m csbitmaps by index dw width m csbitmaps by index dw height h bitmap dst bitmap dss disabled verify delete object h bitmap if else bit blt pdc m hdc r image left r image top m csbitmaps by index dw width m csbitmaps by index dw height hdc mem 0 0 srcand bit blt pdc m hdc r image left r image top m csbitmaps by index dw width m csbitmaps by index dw height hdc bmp mem 0 0 srcpaint else select object hdc mem hbmt deletedc hdc mem select object hdc bmp mem hbm old bmp deletedc hdc bmp mem cbuttonst drawthebitmap bhastitle rpitem crect rpcaption bispressed bisdisabled hdcbmpmem hbmoldbmp hdcmem byindex m_bischeckbox bispressed m_bischeckbox bispressed m_bmouseonbutton byindex byindex m_csbitmaps hbitmap crect rimage prepareimagerect bhastitle rpitem rpcaption bispressed m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight rimage hdcbmpmem createcompatibledc m_hdc hbmoldbmp selectobject hdcbmpmem m_csbitmaps byindex hbitmap hdcmem createcompatibledc selectobject hdcmem m_csbitmaps byindex hmask bisdisabled m_bshowdisabledbitmap hbitmap createcompatibledc m_hdc hbitmap createcompatiblebitmap m_hdc m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight holdbmp2 selectobject hbitmap rrect rrect rrect rrect rimage rrect rimage fillrect rrect croldcolor setbkcolor bitblt m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight hdcmem bitblt m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight hdcbmpmem setbkcolor croldcolor selectobject holdbmp2 drawstate cpoint rimage rimage csize m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight hbitmap dst_bitmap dss_disabled deleteobject hbitmap bitblt m_hdc rimage rimage m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight hdcmem bitblt m_hdc rimage rimage m_csbitmaps byindex dwwidth m_csbitmaps byindex dwheight hdcbmpmem selectobject hdcmem hdcmem selectobject hdcbmpmem hbmoldbmp hdcbmpmem void c buttonst draw the text cdc pdc lpctstr lpsz text rect rp item c rect rp caption bool b is pressed bool b is disabled draw the button s title if button is pressed then press title also if m bispressed m bischeckbox false rp caption offset rect m ptpressedoffset x m ptpressedoffset y only for debug c brush br btn shadow rgb 255 0 0 pdc frame rect r caption br btn shadow center text c rect center rect rp caption pdc draw text lpsz text 1 rp caption dt wordbreak dt center dt calcrect if left aligned rp caption offset rect center rect width rp caption width 2 center rect height rp caption height 2 else rp caption offset rect 8 center rect height rp caption height 2 rfu rp caption offset rect 0 center rect height rp caption height 2 rp caption offset rect center rect width rp caption width 4 center rect height rp caption height 2 pdc set bk mode transparent pdc draw state r caption top left r caption size lpctstr s title b is disabled dss disabled dss normal true 0 c brush null if m bisdisabled rp caption offset rect 1 1 pdc set text color get sys color color 3dhilight pdc draw text lpsz text 1 rp caption dt wordbreak dt center rp caption offset rect 1 1 pdc set text color get sys color color 3dshadow pdc draw text lpsz text 1 rp caption dt wordbreak dt center if else if m bmouseonbutton m bispressed pdc set text color m crcolors btnst color fg in pdc set bk color m crcolors btnst color bk in if else pdc set text color m crcolors btnst color fg out pdc set bk color m crcolors btnst color bk out else pdc draw text lpsz text 1 rp caption dt wordbreak dt center if cbuttonst drawthetext lpsztext rpitem crect rpcaption bispressed bisdisabled m_bispressed m_bischeckbox rpcaption offsetrect m_ptpressedoffset m_ptpressedoffset cbrush brbtnshadow framerect rcaption brbtnshadow crect centerrect rpcaption drawtext lpsztext rpcaption dt_wordbreak dt_center dt_calcrect leftaligned rpcaption offsetrect centerrect rpcaption centerrect rpcaption rpcaption offsetrect centerrect rpcaption rpcaption offsetrect centerrect rpcaption rpcaption offsetrect centerrect rpcaption centerrect rpcaption setbkmode drawstate rcaption topleft rcaption stitle bisdisabled dss_disabled dss_normal cbrush m_bisdisabled rpcaption offsetrect settextcolor getsyscolor color_3dhilight drawtext lpsztext rpcaption dt_wordbreak dt_center rpcaption offsetrect settextcolor getsyscolor color_3dshadow drawtext lpsztext rpcaption dt_wordbreak dt_center m_bmouseonbutton m_bispressed settextcolor m_crcolors btnst_color_fg_in setbkcolor m_crcolors btnst_color_bk_in settextcolor m_crcolors btnst_color_fg_out setbkcolor m_crcolors btnst_color_bk_out drawtext lpsztext rpcaption dt_wordbreak dt_center void c buttonst paint bk cdc pdc c clientdc cldc get parent c rect rect c rect rect1 get client rect rect get window rect rect1 get parent screen to client rect1 if m dcbk m hdc null m dcbk create compatibledc cldc m bmpbk create compatible bitmap cldc rect width rect height m pbmpoldbk m dcbk select object m bmpbk m dcbk bit blt 0 0 rect width rect height cldc rect1 left rect1 top srccopy if pdc bit blt 0 0 rect width rect height m dcbk 0 0 srccopy cbuttonst paintbk cclientdc getparent crect crect getclientrect getwindowrect getparent screentoclient m_dcbk m_hdc m_dcbk createcompatibledc m_bmpbk createcompatiblebitmap m_pbmpoldbk m_dcbk selectobject m_bmpbk m_dcbk bitblt bitblt m_dcbk void c buttonst init tool tip if m tooltip m hwnd null create tool tip control m tooltip create this create inactive m tooltip activate false enable multiline m tooltip send message ttm setmaxtipwidth 0 400 if cbuttonst inittooltip m_tooltip m_hwnd tooltip m_tooltip m_tooltip m_tooltip sendmessage ttm_setmaxtipwidth void c buttonst cancel hover only for flat buttons if m bisflat if m bmouseonbutton m bmouseonbutton false invalidate if if cbuttonst cancelhover m_bisflat m_bmouseonbutton m_bmouseonbutton caich sync thread caich sync thread caichsyncthread caichsyncthread bool caich sync thread init instance dbg set thread name aich sync thread init thread locale return true caichsyncthread initinstance dbgsetthreadname aichsyncthread initthreadlocale int caich sync thread run if the app emuledlg is running return 0 we need to keep a lock on this file while the thread is running c single lock lock known2 met caich hash set m mutknown2file lock known2 met lock c safe file file bool b just created convert to known2 to known264 file we collect all masterhashs which we find in the known2 met and store them in a list c list caich hash li known2 hashs c string fullpath the prefs get config dir fullpath append known2 met filename c file exception fexp uint32 n last verified pos 0 if b just created file open fullpath c file mode create c file mode read write c file mode no truncate c file os sequential scan c file type binary c file share deny none fexp if fexp m cause c file exception file not found c string str error t failed to load known2 met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false try if file get length 1 uint8 header file readu int8 if header known2 met version afx throw file exception c file exception end of file 0 file get file name setvbuf file m pstream null iofbf 16384 uint32 n existing size uint file get length uint32 n hash count while file get position n existing size li known2 hashs add tail caich hash file n hash count file readu int32 if file get position n hash count caich hash get hash size n existing size afx throw file exception c file exception end of file 0 file get file name skip the rest of this hashset file seek n hash count caich hash get hash size c file current n last verified pos uint file get position else file writeu int8 known2 met version catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err met bad known2 met filename truncate the file to the size to the last verified valid pos try file set length n last verified pos if file get length 0 file seek to begin file writeu int8 known2 met version catch c file exception error2 error2 delete else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err servermet unknown buffer error delete return false now we check that all files which are in the sharedfilelist have a corresponding hash in out list those how don t are added to the hashinglist c list caich hash li used hashs c single lock sharelock the app sharedfiles m mutwritelist sharelock lock for int i 0 i the app sharedfiles get count i c known file p cur file the app sharedfiles get file by index i if p cur file null p cur file is part file if the app emuledlg null the app emuledlg is running in case of shutdown while still hashing return 0 if p cur file getaich hashset get status aich hashsetcomplete bool b found false for position pos li known2 hashs get head position pos 0 caich hash current hash li known2 hashs get next pos if current hash p cur file getaich hashset get master hash b found true li used hashs add tail current hash the app queue debug log line false t s s current hash get string p cur file get file name ifdef debug in debugmode we load and verify all hashsets assert p cur file getaich hashset load hash set p cur file getaich hashset dbg test p cur file getaich hashset free hash set endif break if b found hashset is available everything fine with this file continue p cur file getaich hashset set status aich error m litohash add tail p cur file sharelock unlock removed all unused aich hashsets from known2 met if the prefs is remembering downloaded files li used hashs get count li known2 hashs get count file seek to begin try uint8 header file readu int8 if header known2 met version afx throw file exception c file exception end of file 0 file get file name uint32 n existing size uint file get length uint32 n hash count ulonglong pos write pos file get position ulonglong pos read pos file get position uint32 n purge count 0 while file get position n existing size caich hash aich hash file n hash count file readu int32 if file get position n hash count caich hash get hash size n existing size afx throw file exception c file exception end of file 0 file get file name if li used hashs find aich hash null unused hashset skip the rest of this hashset file seek n hash count caich hash get hash size c file current n purge count else if n purge count 0 used hashset but it does not need to be moved as nothing changed yet file seek n hash count caich hash get hash size c file current pos write pos file get position else used hashset move position in file byte buffer new byte n hash count caich hash get hash size file read buffer n hash count caich hash get hash size pos read pos file get position file seek pos write pos c file begin file write aich hash get raw hash caich hash get hash size file writeu int32 n hash count file write buffer n hash count caich hash get hash size delete buffer pos write pos file get position file seek pos read pos c file begin pos read pos file get position file set length pos write pos the app queue debug log line false t cleaned up known2 met removed u hashsets s n purge count cast itox bytes pos read pos pos write pos file flush file close catch c file exception error if error m cause c file exception end of file we just parsed this files some ms ago should never happen here assert false else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err servermet unknown buffer error delete return false lock known2 met unlock warn the user if he just upgraded if the prefs is first start m litohash is empty b just created log warning get res string ids aich warnuser if m litohash is empty the app queue log line true get res string ids aich synctotal m litohash get count the app emuledlg sharedfileswnd sharedfilesctrl setaich hashing m litohash get count let first all normal hashing be done before starting out synchashing c single lock s lock1 the app hashing mut only one filehash at a time while the app sharedfiles get hashing count 0 sleep 100 s lock1 lock uint32 c done 0 for position pos m litohash get head position pos 0 c done if the app emuledlg null the app emuledlg is running in case of shutdown while still hashing return 0 the app emuledlg sharedfileswnd sharedfilesctrl setaich hashing m litohash get count c done if the app emuledlg sharedfileswnd sharedfilesctrl m hwnd null the app emuledlg sharedfileswnd sharedfilesctrl show files count c known file p cur file m litohash get next pos just to be sure that the file hasnt been deleted lately if the app knownfiles is known file p cur file the app sharedfiles get file byid p cur file get file hash continue the app queue log line false get res string ids aich calcfile p cur file get file name if p cur file createaich hash set only the app queue debug log line false t failed to create aich hashset while sync for file s p cur file get file name the app emuledlg sharedfileswnd sharedfilesctrl setaich hashing 0 if the app emuledlg sharedfileswnd sharedfilesctrl m hwnd null the app emuledlg sharedfileswnd sharedfilesctrl show files count s lock1 unlock the app queue debug log line false t aich sync thread finished return 0 caichsyncthread theapp isrunning csinglelock lockknown2met caichhashset m_mutknown2file lockknown2met csafefile bjustcreated converttoknown2toknown264 clist caichhash liknown2hashs cstring theprefs getconfigdir known2_met_filename cfileexception nlastverifiedpos bjustcreated cfile modecreate cfile modereadwrite cfile modenotruncate cfile ossequentialscan cfile typebinary cfile sharedenynone m_cause cfileexception filenotfound cstring strerror _t known2_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror getlength readuint8 known2_met_version afxthrowfileexception cfileexception endoffile getfilename m_pstream _iofbf nexistingsize getlength nhashcount getposition nexistingsize liknown2hashs addtail caichhash nhashcount readuint32 getposition nhashcount caichhash gethashsize nexistingsize afxthrowfileexception cfileexception endoffile getfilename nhashcount caichhash gethashsize cfile nlastverifiedpos getposition writeuint8 known2_met_version cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_met_bad known2_met_filename setlength nlastverifiedpos getlength seektobegin writeuint8 known2_met_version cfileexception max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_servermet_unknown clist caichhash liusedhashs csinglelock theapp m_mutwritelist theapp getcount cknownfile pcurfile theapp getfilebyindex pcurfile pcurfile ispartfile theapp theapp isrunning pcurfile getaichhashset getstatus aich_hashsetcomplete bfound liknown2hashs getheadposition caichhash current_hash liknown2hashs getnext current_hash pcurfile getaichhashset getmasterhash bfound liusedhashs addtail current_hash theapp queuedebuglogline _t current_hash getstring pcurfile getfilename _debug pcurfile getaichhashset loadhashset pcurfile getaichhashset dbgtest pcurfile getaichhashset freehashset bfound pcurfile getaichhashset setstatus aich_error m_litohash addtail pcurfile theprefs isrememberingdownloadedfiles liusedhashs getcount liknown2hashs getcount seektobegin readuint8 known2_met_version afxthrowfileexception cfileexception endoffile getfilename nexistingsize getlength nhashcount poswritepos getposition posreadpos getposition npurgecount getposition nexistingsize caichhash aichhash nhashcount readuint32 getposition nhashcount caichhash gethashsize nexistingsize afxthrowfileexception cfileexception endoffile getfilename liusedhashs aichhash nhashcount caichhash gethashsize cfile npurgecount npurgecount nhashcount caichhash gethashsize cfile poswritepos getposition nhashcount caichhash gethashsize nhashcount caichhash gethashsize posreadpos getposition poswritepos cfile aichhash getrawhash caichhash gethashsize writeuint32 nhashcount nhashcount caichhash gethashsize poswritepos getposition posreadpos cfile posreadpos getposition setlength poswritepos theapp queuedebuglogline _t npurgecount castitoxbytes posreadpos poswritepos cfileexception m_cause cfileexception endoffile max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_servermet_unknown lockknown2met theprefs isfirststart m_litohash isempty bjustcreated logwarning getresstring ids_aich_warnuser m_litohash isempty theapp queuelogline getresstring ids_aich_synctotal m_litohash getcount theapp setaichhashing m_litohash getcount csinglelock slock1 theapp hashing_mut theapp gethashingcount slock1 cdone m_litohash getheadposition cdone theapp theapp isrunning theapp setaichhashing m_litohash getcount cdone theapp m_hwnd theapp showfilescount cknownfile pcurfile m_litohash getnext theapp isknownfile pcurfile theapp getfilebyid pcurfile getfilehash theapp queuelogline getresstring ids_aich_calcfile pcurfile getfilename pcurfile createaichhashsetonly theapp queuedebuglogline _t pcurfile getfilename theapp setaichhashing theapp m_hwnd theapp showfilescount slock1 theapp queuedebuglogline _t aichsyncthread bool caich sync thread convert to known2 to known264 c safe file p target file converting known2 met to known2 64 met to support large files changing hashcount from uint16 to uint32 there still exists a lock on known2 64 met and it should be not opened at this point c string oldfullpath the prefs get config dir oldfullpath append old known2 met filename c string newfullpath the prefs get config dir newfullpath append known2 met filename if path file exists newfullpath path file exists oldfullpath only continue if the old file doe and the new file does not exists return false c safe file oldfile c file exception fexp if oldfile open oldfullpath c file mode read c file os sequential scan c file type binary c file share deny none fexp if fexp m cause c file exception file not found c string str error t failed to load old known2 met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error else known2 met also doesn t exists so nothing to convert return false if p target file open newfullpath c file mode create c file mode read write c file os sequential scan c file type binary c file share deny none fexp if fexp m cause c file exception file not found c string str error t failed to load known2 met filename t file tchar sz error max cfexp errormsg if fexp get error message sz error arrsize sz error str error t str error sz error log error log statusbar t s str error return false the app queue log line false get res string ids convertingknown2met old known2 met filename known2 met filename try p target file writeu int8 known2 met version uint32 n hash count while oldfile get position oldfile get length caich hash aich hash oldfile n hash count oldfile readu int16 if oldfile get position n hash count caich hash get hash size oldfile get length afx throw file exception c file exception end of file 0 oldfile get file name byte buffer new byte n hash count caich hash get hash size oldfile read buffer n hash count caich hash get hash size p target file write aich hash get raw hash caich hash get hash size p target file writeu int32 n hash count p target file write buffer n hash count caich hash get hash size delete buffer p target file flush oldfile close catch c file exception error if error m cause c file exception end of file log error log statusbar get res string ids err met bad old known2 met filename assert false else tchar buffer max cfexp errormsg error get error message buffer arrsize buffer log error log statusbar get res string ids err servermet unknown buffer error delete the app queue log line false get res string ids convertingknown2failed p target file close return false the app queue log line false get res string ids convertingknown2done fixme large files uncomment delete file oldfullpath p target file seek to begin return true caichsyncthread converttoknown2toknown264 csafefile ptargetfile known2_64 known2_64 cstring theprefs getconfigdir old_known2_met_filename cstring theprefs getconfigdir known2_met_filename pathfileexists pathfileexists csafefile cfileexception cfile moderead cfile ossequentialscan cfile typebinary cfile sharedenynone m_cause cfileexception filenotfound cstring strerror _t old_known2_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror ptargetfile cfile modecreate cfile modereadwrite cfile ossequentialscan cfile typebinary cfile sharedenynone m_cause cfileexception filenotfound cstring strerror _t known2_met_filename _t szerror max_cfexp_errormsg geterrormessage szerror szerror strerror _t strerror szerror logerror log_statusbar _t strerror theapp queuelogline getresstring ids_convertingknown2met old_known2_met_filename known2_met_filename ptargetfile writeuint8 known2_met_version nhashcount getposition getlength caichhash aichhash nhashcount readuint16 getposition nhashcount caichhash gethashsize getlength afxthrowfileexception cfileexception endoffile getfilename nhashcount caichhash gethashsize nhashcount caichhash gethashsize ptargetfile aichhash getrawhash caichhash gethashsize ptargetfile writeuint32 nhashcount ptargetfile nhashcount caichhash gethashsize ptargetfile cfileexception m_cause cfileexception endoffile logerror log_statusbar getresstring ids_err_met_bad old_known2_met_filename max_cfexp_errormsg geterrormessage logerror log_statusbar getresstring ids_err_servermet_unknown theapp queuelogline getresstring ids_convertingknown2failed ptargetfile theapp queuelogline getresstring ids_convertingknown2done deletefile ptargetfile seektobegin c dialog c add friend idd m pshowfriend null m icnwnd null cdialog caddfriend m_pshowfriend m_icnwnd c add friend c add friend if m icnwnd verify destroy icon m icnwnd caddfriend caddfriend m_icnwnd destroyicon m_icnwnd void c add friend localize set window text m pshowfriend get res string ids details get res string ids addafriend get dlg item idc info1 set window text get res string ids paf reqinfo get dlg item idc info2 set window text get res string ids paf moreinfo get dlg item idc add set window text get res string ids add get dlg item idcancel set window text m pshowfriend get res string ids fd close get res string ids cancel get dlg item idc static31 set window text get res string ids cd uname get dlg item idc static32 set window text get res string ids cd uhash get dlg item idc static34 set window text m pshowfriend get res string ids userid t get res string ids cd uip get dlg item idc static35 set window text get res string ids port t set dlg item text idc last seen label get res string ids lastseen t set dlg item text idc last chatted label get res string ids lastchatted t caddfriend setwindowtext m_pshowfriend getresstring ids_details getresstring ids_addafriend getdlgitem idc_info1 setwindowtext getresstring ids_paf_reqinfo getdlgitem idc_info2 setwindowtext getresstring ids_paf_moreinfo getdlgitem idc_add setwindowtext getresstring ids_add getdlgitem setwindowtext m_pshowfriend getresstring ids_fd_close getresstring ids_cancel getdlgitem idc_static31 setwindowtext getresstring ids_cd_uname getdlgitem idc_static32 setwindowtext getresstring ids_cd_uhash getdlgitem idc_static34 setwindowtext m_pshowfriend getresstring ids_userid _t getresstring ids_cd_uip getdlgitem idc_static35 setwindowtext getresstring ids_port _t setdlgitemtext idc_last_seen_label getresstring ids_lastseen _t setdlgitemtext idc_last_chatted_label getresstring ids_lastchatted _t bool c add friend on init dialog c dialog on init dialog init window styles this localize if m pshowfriend set icon m icnwnd the app load icon t client details false send dlg item message idc ip em setreadonly true send dlg item message idc port em setreadonly true send dlg item message idc username em setreadonly true set dlg item int idc ip m pshowfriend m dwlastusedip false set dlg item int idc port m pshowfriend m nlastusedport false set dlg item text idc username m pshowfriend m strname if m pshowfriend m dwhashash set dlg item text idc userhash md4str m pshowfriend m abyuserhash else set dlg item text idc userhash t if m pshowfriend m dwlastseen c time t time t m pshowfriend m dwlastseen set dlg item text idc edit2 t format the prefs get date time format if m pshowfriend m dwlastchatted c time t time t m pshowfriend m dwlastchatted set dlg item text idc last chatted t format the prefs get date time format get dlg item idc add show window sw hide else set icon m icnwnd the app load icon t add friend false c edit get dlg item idc username set limit text the prefs get max user nick length set dlg item text idc userhash t return true caddfriend oninitdialog cdialog oninitdialog initwindowstyles m_pshowfriend seticon m_icnwnd theapp loadicon _t clientdetails senddlgitemmessage idc_ip em_setreadonly senddlgitemmessage idc_port em_setreadonly senddlgitemmessage idc_username em_setreadonly setdlgitemint idc_ip m_pshowfriend m_dwlastusedip setdlgitemint idc_port m_pshowfriend m_nlastusedport setdlgitemtext idc_username m_pshowfriend m_strname m_pshowfriend m_dwhashash setdlgitemtext idc_userhash m_pshowfriend m_abyuserhash setdlgitemtext idc_userhash _t m_pshowfriend m_dwlastseen ctime time_t m_pshowfriend m_dwlastseen setdlgitemtext idc_edit2 theprefs getdatetimeformat m_pshowfriend m_dwlastchatted ctime time_t m_pshowfriend m_dwlastchatted setdlgitemtext idc_last_chatted theprefs getdatetimeformat getdlgitem idc_add showwindow sw_hide seticon m_icnwnd theapp loadicon _t addfriend cedit getdlgitem idc_username setlimittext theprefs getmaxusernicklength setdlgitemtext idc_userhash _t void c add friend do data exchange c data exchange pdx c dialog do data exchange pdx caddfriend dodataexchange cdataexchange cdialog dodataexchange void c add friend on add btn if m pshowfriend c string str buff uint32 ip get dlg item text idc ip str buff uint u1 u2 u3 u4 u port 0 if stscanf str buff t u u u u u u1 u2 u3 u4 u port 5 u1 255 u2 255 u3 255 u4 255 u port 65535 u port 0 if stscanf str buff t u u u u u1 u2 u3 u4 4 u1 255 u2 255 u3 255 u4 255 afx message box get res string ids err novalidfriendinfo get dlg item idc ip set focus return in addr ia friend ia friend s un s un b s b1 byte u1 ia friend s un s un b s b2 byte u2 ia friend s un s un b s b3 byte u3 ia friend s un s un b s b4 byte u4 ip ia friend s un s addr if u port 0 get dlg item text idc port str buff if stscanf str buff t u u port 1 afx message box get res string ids err novalidfriendinfo get dlg item idc port set focus return c string str user name get dlg item text idc username str user name str user name trim str user name str user name left the prefs get max user nick length why did we offer an edit control for entering the userhash but did not store it if the app friendlist add friend null 0 ip uint16 u port 0 str user name 0 afx message box get res string ids wrn friendduplipport get dlg item idc ip set focus return else no update friend s data for now too much work to synchronize update all possible available related data in the client list on cancel caddfriend onaddbtn m_pshowfriend cstring strbuff getdlgitemtext idc_ip strbuff uport _stscanf strbuff _t uport uport uport _stscanf strbuff _t afxmessagebox getresstring ids_err_novalidfriendinfo getdlgitem idc_ip setfocus in_addr iafriend iafriend s_un s_un_b s_b1 iafriend s_un s_un_b s_b2 iafriend s_un s_un_b s_b3 iafriend s_un s_un_b s_b4 iafriend s_un s_addr uport getdlgitemtext idc_port strbuff _stscanf strbuff _t uport afxmessagebox getresstring ids_err_novalidfriendinfo getdlgitem idc_port setfocus cstring strusername getdlgitemtext idc_username strusername strusername strusername strusername theprefs getmaxusernicklength theapp addfriend uport strusername afxmessagebox getresstring ids_wrn_friendduplipport getdlgitem idc_ip setfocus oncancel c3d preview control c3d preview control m isliderpos 0 use flat c3dpreviewcontrol c3dpreviewcontrol m_isliderpos c3d preview control c3d preview control c3dpreviewcontrol c3dpreviewcontrol void c3d preview control set slider pos int i pos if i pos 5 i pos 5 m isliderpos i pos if get safe hwnd invalidate update window c3dpreviewcontrol setsliderpos ipos ipos ipos m_isliderpos ipos getsafehwnd updatewindow void c3d preview control on paint c paintdc dc this device context for painting rect outline rec outline rec top 0 outline rec bottom 18 outline rec left 0 outline rec right 34 c brush gdi brush rgb 104 104 104 c brush p old brush dc select object gdi brush eklmn select a new brush dc frame rect outline rec gdi brush dc select object p old brush eklmn recover an old brush s preview set file size uint64 32 s preview fill rgb 192 192 255 s preview draw preview dc 1 1 m isliderpos c3dpreviewcontrol onpaint cpaintdc outline_rec outline_rec outline_rec outline_rec outline_rec cbrush gdibrush cbrush poldbrush selectobject gdibrush framerect outline_rec gdibrush selectobject poldbrush s_preview setfilesize s_preview s_preview drawpreview m_isliderpos virtual int type write char char type ch stream put ch return ch int_type writechar char_type _stream virtual size type write chars const char buf size type len stream write buf len return len size_type writechars size_type _stream virtual size type write chars const char type buf size type len stream write reinterpret cast const char buf len return len size_type writechars char_type size_type _stream reinterpret_cast virtual int type write char char type ch stream put ch return ch int_type writechar char_type _stream virtual size type write chars const char buf size type len stream write buf len return len size_type writechars size_type _stream virtual size type write chars const char type buf size type len stream write reinterpret cast const char buf len return len size_type writechars char_type size_type _stream reinterpret_cast virtual void close file close _file virtual void close file close _file virtual int type write char char type ch stream put ch return ch int_type writechar char_type _stream virtual size type write chars const char buf size type len stream write buf len return len size_type writechars size_type _stream virtual size type write chars const char type buf size type len stream write reinterpret cast const char buf len return len size_type writechars char_type size_type _stream reinterpret_cast virtual int type write char char type ch stream put ch return ch int_type writechar char_type _stream virtual size type write chars const char buf size type len stream write buf len return len size_type writechars size_type _stream virtual size type write chars const char type buf size type len stream write reinterpret cast const char buf len return len size_type writechars char_type size_type _stream reinterpret_cast virtual void close file close _file virtual void close file close _file void set buffer char type buf size t size beg buf cur buf end buf size setbuffer char_type size_t _beg _cur _end id3 memorywriter this set buffer null 0 id3_memorywriter setbuffer id3 memorywriter char type buf size t size this set buffer buf size id3_memorywriter char_type size_t setbuffer virtual size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type virtual size type write chars const char type buf size type len size type remaining end cur size type size remaining len len remaining memcpy cur buf size cur size return size size_type writechars char_type size_type size_type _end _cur size_type _cur _cur virtual pos type get cur return cur beg pos_type getcur _cur _beg virtual pos type get beg return beg beg pos_type getbeg _beg _beg virtual pos type get end return end beg pos_type getend _end _beg void set buffer char type buf size t size beg buf cur buf end buf size setbuffer char_type size_t _beg _cur _end id3 memorywriter this set buffer null 0 id3_memorywriter setbuffer id3 memorywriter char type buf size t size this set buffer buf size id3_memorywriter char_type size_t setbuffer virtual size type write chars const char buf size type len return this write chars reinterpret cast const char type buf len size_type writechars size_type writechars reinterpret_cast char_type virtual size type write chars const char type buf size type len size type remaining end cur size type size remaining len len remaining memcpy cur buf size cur size return size size_type writechars char_type size_type size_type _end _cur size_type _cur _cur virtual pos type get cur return cur beg pos_type getcur _cur _beg virtual pos type get beg return beg beg pos_type getbeg _beg _beg size t id3 tagimpl size const if this num frames 0 return 0 id3 tagheader hdr hdr set spec this get spec size t bytes used hdr size size t frame bytes 0 for const iterator cur frames begin cur frames end cur if cur cur set spec this get spec frame bytes cur size if frame bytes return 0 bytes used frame bytes add 30 for sync if this get unsync bytes used bytes used 3 bytes used this padding size bytes used return bytes used size_t id3_tagimpl numframes id3_tagheader setspec getspec size_t bytesused size_t framebytes const_iterator _frames _frames setspec getspec framebytes framebytes bytesused framebytes getunsync bytesused bytesused bytesused paddingsize bytesused bytesused size t id3 tagimpl padding size size t cur size const luint new size 0 if padding is switched off if is padded return 0 if the old tag was large enough to hold the new tag then we will simply pad out the difference that way the new tag can be written without shuffling the rest of the song file around if this get prepended bytes id3 tagheader size 0 this get prepended bytes id3 tagheader size cur size this get prepended bytes id3 tagheader size cur size id3 padmax new size this get prepended bytes id3 tagheader size else luint temp size cur size id3 getdatasize this this get appended bytes id3 tagheader size this method of automatic padding rounds the complete file up to the nearest 2k if the file will already be an even multiple of 2k with the tag included then we just add another 2k of padding temp size temp size id3 padmultiple 1 id3 padmultiple the size of the new tag is the new filesize minus the audio data new size temp size id3 getdatasize this this get appended bytes id3 tagheader size return new size cur size size_t id3_tagimpl paddingsize size_t cursize newsize _is_padded getprependedbytes id3_tagheader getprependedbytes id3_tagheader cursize getprependedbytes id3_tagheader cursize id3_padmax newsize getprependedbytes id3_tagheader tempsize cursize id3_getdatasize getappendedbytes id3_tagheader tempsize tempsize id3_padmultiple id3_padmultiple newsize tempsize id3_getdatasize getappendedbytes id3_tagheader newsize cursize void id3 tagimpl render ext header uchar buffer if this get spec id3v2 3 0 return id3_tagimpl renderextheader getspec id3v2_3_0 void id3 tagimpl parse file ifstream file if id3e noerror open readable file this get file name file log this return id3 ifstreamreader ifsr file parse reader ifsr file close id3_tagimpl parsefile id3e_noerror openreadablefile getfilename id3_ifstreamreader parsereader void id3 tagimpl parse reader id3 reader reader size t mp3 core size size t bytes till sync io windowed reader wr reader wr set beg wr get cur file tags clear file size reader get end id3 reader pos type beg wr get beg id3 reader pos type cur wr get cur id3 reader pos type end wr get end id3 reader pos type last cur if tags to parse test id3tt id3v2 do last cur parse tags at the beginning of the file first if id3 v2 parse this wr file tags add id3tt id3v2 cur wr get cur wr set beg cur while wr at end cur last add silly padding outside the tag to prepended bytes if wr at end wr peek char 0 id3d notice id3 tagimpl parse reader found padding outside tag do last cur cur wr get cur 1 wr set beg cur wr set cur cur while wr at end cur last wr peek char 0 if wr at end file size cur beg 4 wr peek char 255 unfortunatly this is necessary for finding an invalid padding wr set cur cur 1 cur is known by peek char if wr read char 0 wr read char 0 wr peek char 0 three empty bytes found enough for me this is stupid padding cur 3 those are now allready read in excluding the peek char since it will be added by do do last cur cur wr get cur 1 wr set beg cur wr set cur cur while wr at end cur last wr peek char 0 else wr set cur cur prepended bytes cur beg go looking for the first sync byte to add to bytes till sync by not adding it to prepended bytes we preserve this unknown data the routine s only effect is helping the lib to find things as bitrate etc beg wr get beg if wr at end wr peek char 0xff no sync byte so either this is not followed by a mp3 file or it s a f lac file or an encapsulating format better check it id3d notice id3 tagimpl parse reader didn t find mp3 sync byte if file size cur beg 4 there is room to search for some kind of id unsigned char buf 5 wr read chars buf 4 buf 4 0 check for riff an encapsulating format id if strncmp char buf riff 4 0 strncmp char buf rifx 4 0 next 4 bytes are riff size skip them cur wr get cur 4 wr set cur cur loop until first possible sync byte if wr at end wr peek char 0xff do last cur cur wr get cur 1 wr set cur cur while wr at end cur last wr peek char 0xff else if strncmp char buf f lac 4 0 a flac file no need looking for a sync byte beg cur else since we set the cursor 4 bytes ahead for looking for riff rifx or f lac better set it back but peek char allready checked the first one so we add one cur cur 1 wr set cur cur go looking for a sync byte if wr at end wr peek char 0xff no sync byte we have an unknown byte do last cur cur wr get cur 1 wr set cur cur while wr at end cur last wr peek char 0xff if file size cur beg 4 else remaining size is smaller than 4 bytes can t be useful but leave it for now beg cur file close return bytes till sync cur beg cur wr set cur end if file size prepended bytes do last cur id3d notice id3 tagimpl parse reader beg wr get beg id3d notice id3 tagimpl parse reader cur wr get cur id3d notice id3 tagimpl parse reader end wr get end then the tags at the end id3d notice id3 tagimpl parse reader musicmatch cur wr get cur if tags to parse test id3tt musicmatch mm parse this wr id3d notice id3 tagimpl parse reader musicmatch cur wr get cur file tags add id3tt musicmatch wr set end wr get cur id3d notice id3 tagimpl parse reader lyr3v1 cur wr get cur if tags to parse test id3tt lyrics3 lyr3 v1 parse this wr id3d notice id3 tagimpl parse reader lyr3v1 cur wr get cur file tags add id3tt lyrics3 wr set end wr get cur id3d notice id3 tagimpl parse reader lyr3v2 cur wr get cur if tags to parse test id3tt lyrics3v2 lyr3 v2 parse this wr id3d notice id3 tagimpl parse reader lyr3v2 cur wr get cur file tags add id3tt lyrics3v2 cur wr get cur wr set cur wr get end set to end to seek id3v1 tag check for id3v1 tag and set end accordingly id3d notice id3 tagimpl parse reader id3v1 cur wr get cur if tags to parse test id3tt id3v1 id3 v1 parse this wr id3d notice id3 tagimpl parse reader id3v1 cur wr get cur file tags add id3tt id3v1 wr set cur cur wr set end cur id3d notice id3 tagimpl parse reader id3v1 cur wr get cur if tags to parse test id3tt id3v1 id3 v1 parse this wr id3d notice id3 tagimpl parse reader id3v1 cur wr get cur wr set end wr get cur file tags add id3tt id3v1 cur wr get cur while cur last appended bytes end cur now get the mp3 header mp3 core size file size appended bytes prepended bytes bytes till sync if mp3 core size 4 it has at least the size for a mp3 header a mp3 header is 4 bytes wr set beg prepended bytes bytes till sync wr set cur prepended bytes bytes till sync wr set end file size appended bytes mp3 info new mp3 info id3d notice id3 tagimpl parse reader mp3header cur wr get cur if mp3 info parse wr mp3 core size id3d notice id3 tagimpl parse reader mp3header cur wr get cur else delete mp3 info mp3 info null else this set padding false no need to pad an empty file id3_tagimpl parsereader id3_reader size_t mp3_core_size size_t bytes_till_sync windowedreader setbeg getcur _file_tags _file_size getend id3_reader pos_type getbeg id3_reader pos_type getcur id3_reader pos_type getend id3_reader pos_type _tags_to_parse id3tt_id3v2 _file_tags id3tt_id3v2 getcur setbeg atend _prepended_bytes atend peekchar id3d_notice id3_tagimpl parsereader getcur setbeg setcur atend peekchar atend _file_size peekchar setcur peekchar readchar readchar peekchar peekchar getcur setbeg setcur atend peekchar setcur _prepended_bytes bytes_till_sync _prepended_bytes getbeg atend peekchar flac id3d_notice id3_tagimpl parsereader _file_size readchars getcur setcur atend peekchar getcur setcur atend peekchar flac flac peekchar setcur atend peekchar getcur setcur atend peekchar _file_size bytes_till_sync setcur _file_size _prepended_bytes id3d_notice id3_tagimpl parsereader getbeg id3d_notice id3_tagimpl parsereader getcur id3d_notice id3_tagimpl parsereader getend id3d_notice id3_tagimpl parsereader getcur _tags_to_parse id3tt_musicmatch id3d_notice id3_tagimpl parsereader getcur _file_tags id3tt_musicmatch setend getcur id3d_notice id3_tagimpl parsereader getcur _tags_to_parse id3tt_lyrics3 id3d_notice id3_tagimpl parsereader getcur _file_tags id3tt_lyrics3 setend getcur id3d_notice id3_tagimpl parsereader getcur _tags_to_parse id3tt_lyrics3v2 id3d_notice id3_tagimpl parsereader getcur _file_tags id3tt_lyrics3v2 getcur setcur getend id3d_notice id3_tagimpl parsereader getcur _tags_to_parse id3tt_id3v1 id3d_notice id3_tagimpl parsereader getcur _file_tags id3tt_id3v1 setcur setend id3d_notice id3_tagimpl parsereader getcur _tags_to_parse id3tt_id3v1 id3d_notice id3_tagimpl parsereader getcur setend getcur _file_tags id3tt_id3v1 getcur _appended_bytes mp3_core_size _file_size _appended_bytes _prepended_bytes bytes_till_sync mp3_core_size setbeg _prepended_bytes bytes_till_sync setcur _prepended_bytes bytes_till_sync setend _file_size _appended_bytes _mp3_info mp3info id3d_notice id3_tagimpl parsereader getcur _mp3_info mp3_core_size id3d_notice id3_tagimpl parsereader getcur _mp3_info _mp3_info setpadding mp3 info null need to do this before this clear this clear if name this link name _mp3_info mp3 info null need to do this before this clear this tag _mp3_info id3 tagimpl id3 tagimpl this clear id3_tagimpl id3_tagimpl void id3 tagimpl clear for iterator cur frames begin cur frames end cur if cur delete cur cur null frames clear cursor frames begin is padded true hdr clear hdr set spec id3v2 latest tags to parse clear if mp3 info delete mp3 info also deletes mp3 header mp3 info null changed true id3_tagimpl _frames _frames _frames _cursor _frames _is_padded _hdr _hdr setspec id3v2_latest _tags_to_parse _mp3_info _mp3_info _mp3_header _mp3_info _changed bool id3 tagimpl has changed const bool changed changed if changed for const iterator fi frames begin fi frames end fi if fi changed fi has changed if changed break return changed id3_tagimpl haschanged _changed const_iterator _frames _frames haschanged bool id3 tagimpl set unsync bool b bool changed hdr set unsync b changed changed changed return changed id3_tagimpl setunsync _hdr setunsync _changed _changed bool id3 tagimpl set extended bool ext bool changed hdr set extended ext changed changed changed return changed id3_tagimpl setextended _hdr setextended _changed _changed bool id3 tagimpl set experimental bool exp bool changed hdr set experimental exp changed changed changed return changed id3_tagimpl setexperimental _hdr setexperimental _changed _changed bool id3 tagimpl set padding bool pad bool changed is padded pad changed changed changed if changed is padded pad return changed id3_tagimpl setpadding _is_padded _changed _changed _is_padded bool id3 tagimpl get unsync const return hdr get unsync id3_tagimpl getunsync _hdr getunsync bool id3 tagimpl get extended const return hdr get extended id3_tagimpl getextended _hdr getextended bool id3 tagimpl get experimental const return hdr get experimental id3_tagimpl getexperimental _hdr getexperimental bool id3 tagimpl get footer const return hdr get footer id3_tagimpl getfooter _hdr getfooter size t id3 tagimpl get extended bytes const if this get extended if this get spec id3v2 4 0 return 6 minimal id3v2 4 ext header size else if this get spec id3v2 3 0 return 10 minimal id3v2 3 ext header size else return 0 not implemented else return 0 size_t id3_tagimpl getextendedbytes getextended getspec id3v2_4_0 getspec id3v2_3_0 void id3 tagimpl add frame const id3 frame frame this add frame frame id3_tagimpl addframe id3_frame addframe void id3 tagimpl add frame const id3 frame frame if frame id3 frame frm new id3 frame frame this attach frame frm id3_tagimpl addframe id3_frame id3_frame id3_frame attachframe bool id3 tagimpl attach frame id3 frame frame if null frame log this return false id3 throw id3e nodata frames push back frame cursor frames begin changed true return true id3_tagimpl attachframe id3_frame id3_throw id3e_nodata _frames push_back _cursor _frames _changed id3 frame id3 tagimpl remove frame const id3 frame frame id3 frame frm null iterator fi find frame if fi frames end frm fi frames erase fi cursor frames begin changed true return frm id3_frame id3_tagimpl removeframe id3_frame id3_frame _frames _frames _cursor _frames _changed id3 tagimpl operator const id3 tag r tag this clear this set unsync r tag get unsync this set extended r tag get extended header this set experimental r tag get experimental id3 tag const iterator iter r tag create iterator const id3 frame frame null while null frame iter get next this attach frame new id3 frame frame delete iter return this id3_tagimpl id3_tag rtag setunsync rtag getunsync setextended rtag getextendedheader setexperimental rtag getexperimental id3_tag constiterator rtag createiterator id3_frame getnext attachframe id3_frame id3 v2spec id3 tagimpl get spec const return hdr get spec id3_v2spec id3_tagimpl getspec _hdr getspec bool id3 tagimpl set spec id3 v2spec spec bool changed hdr set spec spec changed changed changed return changed id3_tagimpl setspec id3_v2spec _hdr setspec _changed _changed size t id3 tagimpl isv2 tag id3 reader reader io exit trigger et reader size t tag size 0 string id io read text reader id3 tagheader id size string ver io read text reader 2 char flags reader read char string size io read text reader 4 if id id3 tagheader id uchar ver 0 0xff uchar ver 1 0xff uchar size 0 0x80 uchar size 1 0x80 uchar size 2 0x80 uchar size 3 0x80 io string reader sr size tag size io readu int28 sr id3 tagheader size else if id id3 tagheader id clog isv2 tag not an id3v2 tag header endl else if uchar ver 0 0xff clog isv2 tag major offset endl else if uchar ver 1 0xff clog isv2 tag minor offset endl else if uchar size 0 0x80 clog isv2 tag 1st size offset endl else if uchar size 1 0x80 clog isv2 tag 2nd size offset endl else if uchar size 2 0x80 clog isv2 tag 3rd size offset endl else if uchar size 3 0x80 clog isv2 tag 4th size offset endl else clog shouldn t get here endl return tag size size_t id3_tagimpl isv2tag id3_reader exittrigger size_t tagsize readtext id3_tagheader id_size readtext readchar readtext id3_tagheader stringreader tagsize readuint28 id3_tagheader id3_tagheader isv2tag isv2tag isv2tag isv2tag isv2tag isv2tag isv2tag tagsize id3 frame id3 tagimpl find id3 frameid id const id3 frame frame null reset the cursor if it isn t set if frames end cursor cursor frames begin for int i count 0 i count 2 frame null i count we want to cycle through the list to find the matching frame we should begin from the cursor search each successive frame wrapping if necessary the enclosing loop and the assignment statments below ensure that we first begin at the cursor and search to the end of the list and if unsuccessful start from the beginning of the list and search to the cursor const iterator begin 0 i count cursor frames begin end 0 i count frames end cursor search from the cursor to the end for const iterator cur begin cur end cur if cur null cur getid id we ve found a valid frame set the cursor to be the next element frame cur cursor cur break return frame id3_frame id3_tagimpl id3_frameid id3_frame _frames _cursor _cursor _frames icount icount icount const_iterator icount _cursor _frames icount _frames _cursor const_iterator _cursor id3 frame id3 tagimpl find id3 frameid id id3 fieldid fldid uint32 data const id3 frame frame null reset the cursor if it isn t set if frames end cursor cursor frames begin for int i count 0 i count 2 frame null i count we want to cycle through the list to find the matching frame we should begin from the cursor search each successive frame wrapping if necessary the enclosing loop and the assignment statments below ensure that we first begin at the cursor and search to the end of the list and if unsuccessful start from the beginning of the list and search to the cursor const iterator begin 0 i count cursor frames begin end 0 i count frames end cursor search from the cursor to the end for const iterator cur begin cur end cur if cur null cur getid id cur get field fldid get data we ve found a valid frame set the cursor to be the next element frame cur cursor cur break return frame id3_frame id3_tagimpl id3_frameid id3_fieldid id3_frame _frames _cursor _cursor _frames icount icount icount const_iterator icount _cursor _frames icount _frames _cursor const_iterator getfield _cursor id3 frame id3 tagimpl find id3 frameid id id3 fieldid fldid w string data const id3 frame frame null reset the cursor if it isn t set if frames end cursor cursor frames begin for int i count 0 i count 2 frame null i count we want to cycle through the list to find the matching frame we should begin from the cursor search each successive frame wrapping if necessary the enclosing loop and the assignment statments below ensure that we first begin at the cursor and search to the end of the list and if unsuccessful start from the beginning of the list and search to the cursor const iterator begin 0 i count cursor frames begin end 0 i count frames end cursor search from the cursor to the end for const iterator cur begin cur end cur if cur null cur getid id cur contains fldid id3 field fld cur get field fldid if null fld continue w string text tow string fld get raw unicode text fld size if text data we ve found a valid frame set cursor to be the next element frame cur cursor cur break return frame id3_frame id3_tagimpl id3_frameid id3_fieldid wstring id3_frame _frames _cursor _cursor _frames icount icount icount const_iterator icount _cursor _frames icount _frames _cursor const_iterator id3_field getfield wstring towstring getrawunicodetext _cursor id3 tagimpl const iterator id3 tagimpl find const id3 frame frame const const iterator cur frames begin for cur frames end cur if cur frame break return cur id3_tagimpl const_iterator id3_tagimpl id3_frame const_iterator _frames _frames id3 tagimpl iterator id3 tagimpl find const id3 frame frame iterator cur frames begin for cur frames end cur if cur frame break return cur id3_tagimpl id3_tagimpl id3_frame _frames _frames size t id3 tagimpl link const char file info flags t tag types tags to parse set tag types if null file info return 0 file name file info changed true this parse file return this get prepended bytes size_t id3_tagimpl fileinfo flags_t tag_types _tags_to_parse tag_types fileinfo _file_name fileinfo _changed parsefile getprependedbytes size t id3 tagimpl link id3 reader reader flags t tag types tags to parse set tag types file name changed true this parse reader reader return this get prepended bytes size_t id3_tagimpl id3_reader flags_t tag_types _tags_to_parse tag_types _file_name _changed parsereader getprependedbytes flags t id3 tagimpl update flags t ul tag flag flags t tags id3tt none fstream file string filename this get file name id3 err err open writable file filename file file size get file size file if err id3e nofile err create file filename file if err id3e readonly return tags if ul tag flag id3tt id3v2 this has changed prepended bytes renderv2 to file this file if prepended bytes tags id3tt id3v2 if ul tag flag id3tt id3v1 this has tag type id3tt id3v1 this has changed size t tag bytes renderv1 to file this file if tag bytes only add the tag bytes if there wasn t an id3v1 tag before if file tags test id3tt id3v1 appended bytes tag bytes tags id3tt id3v1 changed false file tags add tags file size get file size file file close return tags flags_t id3_tagimpl flags_t ultagflag flags_t id3tt_none getfilename id3_err openwritablefile _file_size getfilesize id3e_nofile createfile id3e_readonly ultagflag id3tt_id3v2 haschanged _prepended_bytes renderv2tofile _prepended_bytes id3tt_id3v2 ultagflag id3tt_id3v1 hastagtype id3tt_id3v1 haschanged size_t tag_bytes renderv1tofile tag_bytes tag_bytes _file_tags id3tt_id3v1 _appended_bytes tag_bytes id3tt_id3v1 _changed _file_tags _file_size getfilesize flags t id3 tagimpl strip flags t ul tag flag flags t ul tags id3tt none const size t data size id3 getdatasize this first remove the v2 tag if requested if ul tag flag id3tt prepended file tags get fstream file if id3e noerror open writable file this get file name file return ul tags file size get file size file we will remove the id3v2 tag in place since it comes at the beginning of the file we ll effectively move all the data that comes after the tag back n bytes where n is the size of the id3v2 tag once we ve copied the data we ll truncate the file file seekg this get prepended bytes ios beg uchar auc buffer bufsiz the n bytes remaining variable indicates how many bytes are to be copied size t n bytes to copy data size here we increase the n bytes to copy by the size of any tags that appear at the end of the file if we don t want to strip them if ul tag flag id3tt appended n bytes to copy this get appended bytes the n bytes remaining variable indicates how many bytes are left to be moved in the actual file the n bytes copied variable keeps track of how many actual bytes were copied or moved so far size t n bytes remaining n bytes to copy n bytes copied 0 while file eof if defined gnuc gnuc 2 size t n bytes to read size t dami min unsigned int n bytes remaining n bytes copied unsigned int bufsiz else size t n bytes to read min unsigned int n bytes remaining n bytes copied unsigned int bufsiz endif file read char auc buffer n bytes to read size t n bytes read file gcount if n bytes read n bytes to read todo log this cerr attempted to write n bytes read bytes only wrote n bytes written endl if n bytes read 0 long offset n bytes read this get prepended bytes file seekp offset ios cur file write char auc buffer n bytes read file seekg this get prepended bytes ios cur n bytes copied n bytes read if n bytes copied n bytes to copy n bytes to read bufsiz break file close size t n new file size data size if file tags get id3tt appended ul tag flag id3tt appended ul tags file tags get id3tt appended else if we re not stripping the appended tags be sure to increase the file size by those bytes n new file size this get appended bytes if ul tag flag id3tt prepended file tags get id3tt prepended if we re stripping the id3v2 tag there s no need to adjust the new file size since it doesn t account for the id3v2 tag size ul tags file tags get id3tt prepended else add the original prepended tag size since we don t want to delete it and the new file size represents the file size not counting the id3v2 tag n new file size this get prepended bytes if ul tags truncate file name c str n new file size 1 log this return 0 id3 throw id3e nofile prepended bytes ul tags id3tt prepended 0 prepended bytes appended bytes ul tags id3tt appended 0 appended bytes file size data size prepended bytes appended bytes changed file tags remove ul tags changed return ul tags flags_t id3_tagimpl flags_t ultagflag flags_t ultags id3tt_none size_t data_size id3_getdatasize ultagflag id3tt_prepended _file_tags id3e_noerror openwritablefile getfilename ultags _file_size getfilesize getprependedbytes aucbuffer nbytesremaining size_t nbytestocopy data_size nbytestocopy ultagflag id3tt_appended nbytestocopy getappendedbytes nbytesremaining nbytescopied size_t nbytesremaining nbytestocopy nbytescopied __gnuc__ __gnuc__ size_t nbytestoread size_t nbytesremaining nbytescopied size_t nbytestoread nbytesremaining nbytescopied aucbuffer nbytestoread size_t nbytesread nbytesread nbytestoread nbytesread nbyteswritten nbytesread nbytesread getprependedbytes aucbuffer nbytesread getprependedbytes nbytescopied nbytesread nbytescopied nbytestocopy nbytestoread size_t nnewfilesize data_size _file_tags id3tt_appended ultagflag id3tt_appended ultags _file_tags id3tt_appended nnewfilesize getappendedbytes ultagflag id3tt_prepended _file_tags id3tt_prepended ultags _file_tags id3tt_prepended _not_ nnewfilesize getprependedbytes ultags _file_name c_str nnewfilesize id3_throw id3e_nofile _prepended_bytes ultags id3tt_prepended _prepended_bytes _appended_bytes ultags id3tt_appended _appended_bytes _file_size data_size _prepended_bytes _appended_bytes _changed _file_tags ultags _changed ultags size t id3 tagimpl link const char file info bool parseid3v1 bool parse lyrics3 flags t tt id3tt none if parseid3v1 tt id3tt id3v1 if parse lyrics3 tt id3tt lyrics return this link file info tt size_t id3_tagimpl fileinfo parselyrics3 flags_t id3tt_none id3tt_id3v1 parselyrics3 id3tt_lyrics fileinfo frames the find method is guaranteed to return all matching frames before it wraps around to return the first matching frame all id3 frame objects are comprised of a collection of id3 field objects id3_frame id3_field use an std auto ptr here to handle object cleanup automatically id3 frame iterator iter my frame create iterator id3 field my field null while null my field iter get next auto_ptr id3_frame myframe createiterator id3_field myfield myfield getnext do something with my field delete iter myfield do something with my field myfield code example best illustrates these differences code code tag update endcode that is all there is to it now all you have to do is use the find method to locate the frames you are interested in is the following formatted cdm frames from the unreleased id3v2 2 01 draft specification author dirk mahoney frees any resources for which the object is responsible including all frames and files after a call to clear the object can be used again for any new or existing tag impl clear _impl indicates whether the tag has been altered since the last parse render or update this method is primarily intended as a status indicator for applications and for applications that use the parse and render methods delete impl _impl or encryption i ds and clearing a frame or field all constitute a change to the tag as do calls to the set unsync set extended header and set padding methods ids setunsync setextendedheader setpadding code if my tag has changed mytag haschanged see render return the overestimated number of bytes required to store a binary bool id3 tag set unsync bool b id3_tag setunsync this option is currently ignored as id3lib doesn t yet create extended headers this option only applies when rendering tags for id3v2 versions that support extended headers code my tag set extended header true mytag setextendedheader turns extended header rendering on or off dependant on the value of the param p frame a pointer to the frame that is being added to the tag sa id3 frame void id3 tag add frame const id3 frame frame pframe id3_frame id3_tag addframe id3_frame attaches a frame to the tag the tag takes responsibility for releasing the frame s memory when tag goes out of scope this method accepts responsibility for the attached frame s memory and will delete the frame and its contents when the tag goes out of scope or is deleted therefore be sure the frame isn t attached to other tags code id3 frame frame new id3 frame my tag attach frame frame id3_frame id3_frame mytag attachframe size t id3 tag parse const uchar buffer size t bytes size_t id3_tag size_t turns a binary tag into a series of id3 frame objects attached to the tag id3_frame id3 tag my tag uchar header id3 tagheadersize uchar buffer id3_tag mytag id3_tagheadersize like look for titles artists etc endcode header read from param header the byte header read in from the data source param buffer the remainder of the tag not including the data source read in from the data source size t size id3 tag isv2 tag header if 0 size size_t id3_tag isv2tag b string buf buf reserve id3 tagheader size size buf append reinterpret cast const b string value type header id3 tagheader size buf append reinterpret cast const b string value type buffer size return this parse buf data buf size renders the tag and writes it to the attached file the type of tag rendered can be specified as a parameter the default is to update only the id3v2 tag see the id3 tagtype enumeration for the constants that bstring id3_tagheader reinterpret_cast bstring value_type id3_tagheader reinterpret_cast bstring value_type id3_tagtype one string is missing and this is this string read a further tag size bytes in from our data source tagsize size t id3 tag isv2 tag const uchar const data size_t id3_tag isv2tag size t id3 tag isv2 tag id3 reader reader size_t id3_tag isv2tag id3_reader return tmp filename impl get file name c str else return null finds frame with given frame id _tmp_filename _impl getfilename c_str if there are multiple frames in the tag with the same id which for some frames is allowed then subsequent calls to find will return code id3 frame my frame if my frame my tag find id3fid title id3_frame myframe myframe mytag id3fid_title the contents into a buffer display the contents in a window etc parameter if you supply an id3 frameid you must also supply a data value to compare against this method will then return the first frame that has a matching frame id3_frameid the third parameter for example code found it do something with it code const id3 frame id3 tag find id3 frameid id const id3_frame id3_tag id3_frameid finds frame with given frame id fld id and integer data id3 frame id3 tag find id3 frameid id id3 fieldid fld uint32 data const id3_frame id3_tag id3_frameid id3_fieldid this returns the first comment frame that uses unicode as its text encdoing name find param id the id of the frame that is to be located finds frame with given frame id fld id and ascii data string str data return impl find id fld str _impl finds frame with given frame id fld id and unicode data id3 frame id3 tag find id3 frameid id id3 fieldid fld const unicode t data const id3_frame id3_tag id3_frameid id3_fieldid unicode_t bool id3 tag set experimental bool exp return impl set experimental exp bool id3 tag get unsync const return impl get unsync bool id3 tag get extended header const id3_tag setexperimental _impl setexperimental id3_tag getunsync _impl getunsync id3_tag getextendedheader method indexing is 0 based that is the first frame is number 0 and the last frame in a tag that holds n frames is n 1 if you wish to have a more comlex searching facility then at least for param n index the index of the frame that is to be retrieved return a pointer to the requested frame or null if no such frame id3 frame id3 tag get frame num size t num const const size t num frames this num frames nindex id3_frame id3_tag getframenum size_t size_t numframes numframes changed false this clear changed false _changed _changed bool set data size size t size bool changed size data size changed changed changed data size size return changed setdatasize size_t _data_size _changed _changed _data_size virtual bool clear bool changed this set data size 0 if this get spec id3v2 unknown this set spec id3v2 latest changed true changed flags clear changed changed changed changed return changed setdatasize getspec id3v2_unknown setspec id3v2_latest _flags _changed _changed id3 header operator const id3 header rhs if this rhs this set spec rhs get spec this set data size rhs get spec this flags rhs flags return this id3_header id3_header setspec getspec setdatasize getspec _flags _flags bool id3 header set spec id3 v2spec spec static id3 header info spec info warning ext size are minimum sizes they can be bigger sizeof sizeof sizeof is ext ext experim frid frsz frfl header size bit 3 3 0 false 0 false id3v2 2 0 3 3 0 true 8 true id3v2 2 1 4 4 2 false 10 false id3v2 3 0 4 4 2 false 6 false id3v2 4 0 bool changed false if spec id3v2 earliest spec id3v2 latest changed spec id3v2 unknown spec id3v2 unknown info null else changed spec spec spec spec info spec info spec id3v2 earliest changed changed changed return changed id3_header setspec id3_v2spec id3_header _spec_info id3v2_2_0 id3v2_2_1 id3v2_3_0 id3v2_4_0 id3v2_earliest id3v2_latest _spec id3v2_unknown _spec id3v2_unknown _info _spec _spec _info _spec_info _spec id3v2_earliest _changed _changed bool set unsync bool b bool changed flags set header flag unsync b changed changed changed return changed setunsync _flags header_flag_unsync _changed _changed bool set extended bool b bool changed flags set header flag extended b changed changed changed return changed setextended _flags header_flag_extended _changed _changed bool set experimental bool b bool changed flags set header flag experimental b changed changed changed return changed setexperimental _flags header_flag_experimental _changed _changed bool set footer bool b bool changed flags set header flag footer b changed changed changed return changed setfooter _flags header_flag_footer _changed _changed bool id3 tagheader set spec id3 v2spec spec bool changed this id3 header set spec spec if changed if info flags set header flag experimental info is experimental flags set header flag extended info is extended return changed id3_tagheader setspec id3_v2spec id3_header setspec _info _flags header_flag_experimental _info is_experimental _flags header_flag_extended _info is_extended size t id3 tagheader size const size t bytes used id3 tagheader size if info is extended bytes used info extended bytes return bytes used size_t id3_tagheader size_t bytesused id3_tagheader _info is_extended bytesused _info extended_bytes bytesused void id3 tagheader render id3 writer writer const writer write chars uchar id strlen id writer write char id3 v2spectover id3v2 latest writer write char id3 v2spectorev id3v2 latest set the flags byte in the header writer write char static cast uchar flags get mask8 io writeu int28 writer this get data size now includes the extended header now we render the extended header if flags test header flag extended if this get spec id3v2 4 0 io writeu int28 writer 6 write 4 bytes of v2 4 0 ext header containing size 6 io writebe number writer 1 1 write that it has only one flag byte value 1 io writebe number writer 0 1 write flag byte with value 0 else if this get spec id3v2 3 0 io writebe number writer 6 sizeof uint32 for size t i 0 i 6 i if writer write char 0 id3 writer end of writer break else not implemented id3_tagheader id3_writer writechars writechar id3_v2spectover id3v2_latest writechar id3_v2spectorev id3v2_latest writechar static_cast _flags writeuint28 getdatasize _flags header_flag_extended getspec id3v2_4_0 writeuint28 writebenumber writebenumber getspec id3v2_3_0 writebenumber size_t writechar id3_writer end_of_writer bool id3 tagheader parse id3 reader reader io exit trigger et reader if id3 tag isv2 tag reader id3d notice id3 tagheader parse not an id3v2 header return false uchar id 3 reader read chars id 3 the spec version is determined with the major and minor offse ts uchar major reader read char uchar minor reader read char this set spec id3 verrevtov2spec major minor get the flags at the appropriate offset flags set static cast id3 flags type reader read char set the data size this set data size io readu int28 reader if flags test header flag extended this get spec id3v2 2 1 couldn t find anything about this in the draft specifying 2 2 1 http www id3 org pipermail id3v2 2000 april 000126 html flags set header flag extended false info extended bytes 0 rest is checked at parse extended et set exit pos reader get cur return true id3_tagheader id3_reader exittrigger id3_tag isv2tag id3d_notice id3_tagheader readchars offsets readchar readchar setspec id3_verrevtov2spec _flags static_cast id3_flags readchar setdatasize readuint28 _flags header_flag_extended getspec id3v2_2_1 _flags header_flag_extended _info extended_bytes parseextended setexitpos getcur void id3 tagheader parse extended id3 reader reader if this get spec id3v2 3 0 extended header size xx xx xx xx extended flags xx xx size of padding xx xx xx xx skip over header size we are not using it anyway we calculate it reader set cur reader get cur 4 extended header size io readbe number reader 4 extended header size uint16 tmpval io readbe number reader 2 extended flags skip over padding size we are not using it anyway reader set cur reader get cur 4 size of padding io readbe number reader 4 size of padding if tmpval 0 there is only one flag defined in id3v2 3 0 crc skip over crc data we are not using it anyway reader set cur reader get cur 4 crc io readbe number reader 4 crc info extended bytes 14 else info extended bytes 10 if this get spec id3v2 4 0 extended header size 4 0xxxxxxx number of flag bytes 01 extended flags xx uint16 i uint16 extrabytes io readu int28 reader const int extflagbytes reader read char number of flag bytes id3 flags extflags 1 id3v2 4 0 has 1 flag byte extflagbytes should be equal to 1 for i 0 i extflagbytes i extflags i new id3 flags extflags i set reader read char flags extrabytes 0 extflags 0 test ext header flag bit1 id3v2 4 0 ext header flag bit 1 should be 0 if extflags 0 test ext header flag bit2 id3v2 4 0 ext header flag bit 2 tag is an update read size extrabytes 1 add a byte for the char containing the extflagdatasize const int extheaderflagdatasize reader read char extrabytes extheaderflagdatasize set the cursor right we are not parsing the data no one is using extended flags anyway reader set cur reader get cur extheaderflagdatasize reader read chars buf extheaderflagdatasize buf should be at least 127 bytes max extended header flagdata size if extflags 0 test ext header flag bit3 id3v2 4 0 ext header flag bit 3 crc data present read size extrabytes 1 add a byte for the char containing the extflagdatasize const int extheaderflagdatasize reader read char extrabytes extheaderflagdatasize set the cursor right we are not parsing the data no one is using extended flags anyway reader set cur reader get cur extheaderflagdatasize reader read chars buf extheaderflagdatasize buf should be at least 127 bytes max extended header flagdata size if extflags 0 test ext header flag bit4 id3v2 4 0 ext header flag bit 4 tag restrictions read size extrabytes 1 add a byte for the char containing the extflagdatasize const int extheaderflagdatasize reader read char extrabytes extheaderflagdatasize set the cursor right we are not parsing the data no one is using extended flags anyway reader set cur reader get cur extheaderflagdatasize reader read chars buf extheaderflagdatasize buf should be at least 127 bytes max extended header flagdata size info extended bytes 5 extflagbytes extrabytes a bit unorthodox but since we are not using any of the extended header but were merely parsing it to get the cursor right we delete it be gone flags set header flag extended false if info data size info extended bytes info extended bytes 0 else there is a tag with a higher or lower version than supported id3_tagheader parseextended id3_reader getspec id3v2_3_0 setcur getcur readbenumber readbenumber setcur getcur readbenumber id3v2_3_0 setcur getcur readbenumber _info extended_bytes _info extended_bytes getspec id3v2_4_0 readuint28 readchar id3_flags id3v2_4_0 id3_flags readchar ext_header_flag_bit1 id3v2_4_0 ext_header_flag_bit2 id3v2_4_0 readchar setcur getcur readchars ext_header_flag_bit3 id3v2_4_0 readchar setcur getcur readchars ext_header_flag_bit4 id3v2_4_0 readchar setcur getcur readchars _info extended_bytes _flags header_flag_extended _info _data_size _info extended_bytes _info extended_bytes virtual size type read chars char buf size type len return this read chars reinterpret cast uchar buf len size_type readchars size_type readchars reinterpret_cast virtual size type read chars char type buf size type len stream read char buf len return stream gcount size_type readchars char_type size_type _stream _stream virtual pos type get end pos type cur this get cur stream seekg 0 ios end pos type end this get cur this set cur cur return end pos_type getend pos_type getcur _stream pos_type getcur setcur virtual size type read chars char buf size type len return this read chars reinterpret cast uchar buf len size_type readchars size_type readchars reinterpret_cast virtual size type read chars char type buf size type len stream read char buf len return stream gcount size_type readchars char_type size_type _stream _stream virtual pos type get end pos type cur this get cur stream seekg 0 ios end pos type end this get cur this set cur cur return end pos_type getend pos_type getcur _stream pos_type getcur setcur virtual void close file close _file virtual void close file close _file void set buffer const char type buf size type size beg buf cur buf end buf size setbuffer char_type size_type _beg _cur _end id3 memoryreader this set buffer null 0 id3_memoryreader setbuffer id3 memoryreader const char type buf size type size this set buffer buf size id3_memoryreader char_type size_type setbuffer id3 memoryreader const char buf size type size this set buffer reinterpret cast const char type buf size id3_memoryreader size_type setbuffer reinterpret_cast char_type virtual int type peek char if this at end return cur return end of reader int_type peekchar atend _cur end_of_reader virtual size type read chars char buf size type len return this read chars reinterpret cast char type buf len size_type readchars size_type readchars reinterpret_cast char_type virtual pos type get cur return cur beg pos_type getcur _cur _beg virtual pos type get beg return beg beg pos_type getbeg _beg _beg virtual pos type get end return end beg pos_type getend _end _beg virtual pos type set cur pos type pos pos type end this get end size type size pos end pos end cur beg size return this get cur pos_type setcur pos_type pos_type getend size_type _cur _beg getcur id3 memoryreader read chars char type buf size type len size type size dami min size type len end cur memcpy buf cur size cur size return size id3_memoryreader readchars char_type size_type size_type size_type _end _cur _cur _cur void set buffer const char type buf size type size beg buf cur buf end buf size setbuffer char_type size_type _beg _cur _end id3 memoryreader this set buffer null 0 id3_memoryreader setbuffer id3 memoryreader const char type buf size type size this set buffer buf size id3_memoryreader char_type size_type setbuffer id3 memoryreader const char buf size type size this set buffer reinterpret cast const char type buf size id3_memoryreader size_type setbuffer reinterpret_cast char_type virtual int type peek char if this at end return cur return end of reader int_type peekchar atend _cur end_of_reader virtual size type read chars char buf size type len return this read chars reinterpret cast char type buf len size_type readchars size_type readchars reinterpret_cast char_type virtual pos type get cur return cur beg pos_type getcur _cur _beg virtual pos type get beg return beg beg pos_type getbeg _beg _beg virtual pos type get end return end beg pos_type getend _end _beg virtual pos type set cur pos type pos pos type end this get end size type size pos end pos end cur beg size return this get cur pos_type setcur pos_type pos_type getend size_type _cur _beg getcur void mp3 info clean if mp3 header output null delete mp3 header output mp3 header output null mp3info _mp3_header_output _mp3_header_output _mp3_header_output bool mp3 info parse id3 reader reader size t mp3size mp3 bitrates mp3 bitrates 2 3 16 mpeg 1 layer i mp3bitrate none mp3bitrate 32k mp3bitrate 64k mp3bitrate 96k mp3bitrate 128k mp3bitrate 160k mp3bitrate 192k mp3bitrate 224k mp3bitrate 256k mp3bitrate 288k mp3bitrate 320k mp3bitrate 352k mp3bitrate 384k mp3bitrate 416k mp3bitrate 448k mp3bitrate false mpeg 1 layer ii mp3bitrate none mp3bitrate 32k mp3bitrate 48k mp3bitrate 56k mp3bitrate 64k mp3bitrate 80k mp3bitrate 96k mp3bitrate 112k mp3bitrate 128k mp3bitrate 160k mp3bitrate 192k mp3bitrate 224k mp3bitrate 256k mp3bitrate 320k mp3bitrate 384k mp3bitrate false mpeg 1 layer iii mp3bitrate none mp3bitrate 32k mp3bitrate 40k mp3bitrate 48k mp3bitrate 56k mp3bitrate 64k mp3bitrate 80k mp3bitrate 96k mp3bitrate 112k mp3bitrate 128k mp3bitrate 160k mp3bitrate 192k mp3bitrate 224k mp3bitrate 256k mp3bitrate 320k mp3bitrate false mpeg 2 or 2 5 layer i mp3bitrate none mp3bitrate 32k mp3bitrate 48k mp3bitrate 56k mp3bitrate 64k mp3bitrate 80k mp3bitrate 96k mp3bitrate 112k mp3bitrate 128k mp3bitrate 144k mp3bitrate 160k mp3bitrate 176k mp3bitrate 192k mp3bitrate 224k mp3bitrate 256k mp3bitrate false mpeg 2 or 2 5 layer ii mp3bitrate none mp3bitrate 8k mp3bitrate 16k mp3bitrate 24k mp3bitrate 32k mp3bitrate 40k mp3bitrate 48k mp3bitrate 56k mp3bitrate 64k mp3bitrate 80k mp3bitrate 96k mp3bitrate 112k mp3bitrate 128k mp3bitrate 144k mp3bitrate 160k mp3bitrate false mpeg 2 or 2 5 layer iii mp3bitrate none mp3bitrate 8k mp3bitrate 16k mp3bitrate 24k mp3bitrate 32k mp3bitrate 40k mp3bitrate 48k mp3bitrate 56k mp3bitrate 64k mp3bitrate 80k mp3bitrate 96k mp3bitrate 112k mp3bitrate 128k mp3bitrate 144k mp3bitrate 160k mp3bitrate false mp3 frequencies mp3 frequencies 4 4 mp3frequencies 11025hz mp3frequencies 12000hz mp3frequencies 8000hz mp3frequencies reserved mpegversion 2 5 mp3frequencies reserved mp3frequencies reserved mp3frequencies reserved mp3frequencies reserved mpegversion reserved mp3frequencies 22050hz mp3frequencies 24000hz mp3frequencies 16000hz mp3frequencies reserved mpegversion 2 mp3frequencies 44100hz mp3frequencies 48000hz mp3frequencies 32000hz mp3frequencies reserved mpegversion 1 mp3 header internal tmpheader const size t headersize 4 char buf headersize 1 1 to hold the 0 char id3 reader pos type beg reader get cur id3 reader pos type end beg headersize reader set cur beg int bitrate index mp3 header output layer mpeglayer false mp3 header output version mpegversion false mp3 header output bitrate mp3bitrate false mp3 header output channelmode mp3channelmode false mp3 header output modeext mp3modeext false mp3 header output emphasis mp3emphasis false mp3 header output crc mp3crc mismatch mp3 header output frequency 0 mp3 header output framesize 0 mp3 header output frames 0 mp3 header output time 0 mp3 header output vbr bitrate 0 reader read chars buf headersize buf headersize 0 copy the pointer to the struct if buf 0 0xff 0xff buf 1 0xe0 0xe0 first 11 bits should be 1 this clean return false tmpheader reinterpret cast mp3 header internal buf bitrate index 0 switch tmpheader id case 3 mp3 header output version mpegversion 1 bitrate index 0 break case 2 mp3 header output version mpegversion 2 bitrate index 1 break case 1 this clean return false wouldn t know how to handle it break case 0 mp3 header output version mpegversion 2 5 bitrate index 1 break default this clean return false break switch tmpheader layer case 3 mp3 header output layer mpeglayer i break case 2 mp3 header output layer mpeglayer ii break case 1 mp3 header output layer mpeglayer iii break case 0 this clean return false wouldn t know how to handle it break default this clean return false how can two unsigned bits be something else break mpegversion layer and bitrate are all valid mp3 header output bitrate mp3 bitrates bitrate index 3 tmpheader layer tmpheader bitrate index if mp3 header output bitrate mp3bitrate false this clean return false mp3 header output frequency mp3 frequencies tmpheader id tmpheader frequency if mp3 header output frequency mp3frequencies reserved this clean return false mp3 header output privatebit bool tmpheader private bit mp3 header output copyrighted bool tmpheader copyright mp3 header output original bool tmpheader original mp3 header output crc mp3 crc bool tmpheader protection bit switch tmpheader mode case 3 mp3 header output channelmode mp3channelmode single channel break case 2 mp3 header output channelmode mp3channelmode dual channel break case 1 mp3 header output channelmode mp3channelmode joint stereo break case 0 mp3 header output channelmode mp3channelmode stereo break default this clean return false wouldn t know how to handle it break if mp3 header output channelmode mp3channelmode joint stereo these have a different meaning for different layers better give them a generic name in the enum switch tmpheader mode ext case 3 mp3 header output modeext mp3modeext 3 break case 2 mp3 header output modeext mp3modeext 2 break case 1 mp3 header output modeext mp3modeext 1 break case 0 mp3 header output modeext mp3modeext 0 break default this clean return false wouldn t know how to handle it break else it s valid to have a valid false one in this case since it s only used with joint stereo mp3 header output modeext mp3modeext false switch tmpheader emphasis case 3 mp3 header output emphasis mp3emphasis ccit j17 break case 2 mp3 header output emphasis mp3emphasis reserved break case 1 mp3 header output emphasis mp3emphasis 50 15ms break case 0 mp3 header output emphasis mp3emphasis none break default this clean return false wouldn t know how to handle it break http www mp3 tech org programmer frame header html if mp3 header output bitrate mp3bitrate none mp3 header output frequency 0 switch mp3 header output layer case mpeglayer i layer 1 mp3 header output framesize 4 12 mp3 header output bitrate mp3 header output frequency tmpheader padding bit 1 0 break case mpeglayer ii layer 2 mp3 header output framesize 144 mp3 header output bitrate mp3 header output frequency tmpheader padding bit 1 0 break case mpeglayer iii layer 3 if mp3 header output version mpegversion 2 5 mp3 header output framesize 144 mp3 header output bitrate mp3 header output frequency tmpheader padding bit 1 0 mpeg1 else mp3 header output framesize 72000 mp3 header output bitrate mp3 header output frequency tmpheader padding bit 1 0 mpeg2 mpeg2 5 break if mp3 header output layer mpeglayer i mp3 header output framesize fto nearest i float 48 float mp3 header output bitrate mp3 header output frequency tmpheader padding bit 4 0 else mp3 header output framesize fto nearest i float 144 float mp3 header output bitrate mp3 header output frequency tmpheader padding bit 1 0 else mp3 header output framesize 0 unable to determine const size t crcsize 2 size t sideinfo len if mp3 header output version mpegversion 1 mpeg 1 sideinfo len mp3 header output channelmode mp3channelmode single channel 4 17 4 32 else mpeg 2 sideinfo len mp3 header output channelmode mp3channelmode single channel 4 9 4 17 int vbr header offest beg sideinfo len int vbr frames 0 sideinfo len 2 add two for the crc itself if mp3 header output crc mp3crc ok mp3size sideinfo len mp3 header output crc mp3crc error size if mp3 header output crc mp3crc ok char audiodata 38 1 mp3info id3_reader size_t mp3_bitrates _mp3_bitrates mp3bitrate_none mp3bitrate_32k mp3bitrate_64k mp3bitrate_96k mp3bitrate_128k mp3bitrate_160k mp3bitrate_192k mp3bitrate_224k mp3bitrate_256k mp3bitrate_288k mp3bitrate_320k mp3bitrate_352k mp3bitrate_384k mp3bitrate_416k mp3bitrate_448k mp3bitrate_false mp3bitrate_none mp3bitrate_32k mp3bitrate_48k mp3bitrate_56k mp3bitrate_64k mp3bitrate_80k mp3bitrate_96k mp3bitrate_112k mp3bitrate_128k mp3bitrate_160k mp3bitrate_192k mp3bitrate_224k mp3bitrate_256k mp3bitrate_320k mp3bitrate_384k mp3bitrate_false mp3bitrate_none mp3bitrate_32k mp3bitrate_40k mp3bitrate_48k mp3bitrate_56k mp3bitrate_64k mp3bitrate_80k mp3bitrate_96k mp3bitrate_112k mp3bitrate_128k mp3bitrate_160k mp3bitrate_192k mp3bitrate_224k mp3bitrate_256k mp3bitrate_320k mp3bitrate_false mp3bitrate_none mp3bitrate_32k mp3bitrate_48k mp3bitrate_56k mp3bitrate_64k mp3bitrate_80k mp3bitrate_96k mp3bitrate_112k mp3bitrate_128k mp3bitrate_144k mp3bitrate_160k mp3bitrate_176k mp3bitrate_192k mp3bitrate_224k mp3bitrate_256k mp3bitrate_false mp3bitrate_none mp3bitrate_8k mp3bitrate_16k mp3bitrate_24k mp3bitrate_32k mp3bitrate_40k mp3bitrate_48k mp3bitrate_56k mp3bitrate_64k mp3bitrate_80k mp3bitrate_96k mp3bitrate_112k mp3bitrate_128k mp3bitrate_144k mp3bitrate_160k mp3bitrate_false mp3bitrate_none mp3bitrate_8k mp3bitrate_16k mp3bitrate_24k mp3bitrate_32k mp3bitrate_40k mp3bitrate_48k mp3bitrate_56k mp3bitrate_64k mp3bitrate_80k mp3bitrate_96k mp3bitrate_112k mp3bitrate_128k mp3bitrate_144k mp3bitrate_160k mp3bitrate_false mp3_frequencies _mp3_frequencies mp3frequencies_11025hz mp3frequencies_12000hz mp3frequencies_8000hz mp3frequencies_reserved mpegversion_2_5 mp3frequencies_reserved mp3frequencies_reserved mp3frequencies_reserved mp3frequencies_reserved mpegversion_reserved mp3frequencies_22050hz mp3frequencies_24000hz mp3frequencies_16000hz mp3frequencies_reserved mpegversion_2 mp3frequencies_44100hz mp3frequencies_48000hz mp3frequencies_32000hz mp3frequencies_reserved mpegversion_1 _mp3_header_internal _tmpheader size_t id3_reader pos_type getcur id3_reader pos_type setcur bitrate_index _mp3_header_output mpeglayer_false _mp3_header_output mpegversion_false _mp3_header_output mp3bitrate_false _mp3_header_output mp3channelmode_false _mp3_header_output mp3modeext_false _mp3_header_output mp3emphasis_false _mp3_header_output mp3crc_mismatch _mp3_header_output _mp3_header_output _mp3_header_output _mp3_header_output _mp3_header_output vbr_bitrate readchars _tmpheader reinterpret_cast _mp3_header_internal bitrate_index _tmpheader _mp3_header_output mpegversion_1 bitrate_index _mp3_header_output mpegversion_2 bitrate_index _mp3_header_output mpegversion_2_5 bitrate_index _tmpheader _mp3_header_output mpeglayer_i _mp3_header_output mpeglayer_ii _mp3_header_output mpeglayer_iii _mp3_header_output _mp3_bitrates bitrate_index _tmpheader _tmpheader bitrate_index _mp3_header_output mp3bitrate_false _mp3_header_output _mp3_frequencies _tmpheader _tmpheader _mp3_header_output mp3frequencies_reserved _mp3_header_output _tmpheader private_bit _mp3_header_output _tmpheader _mp3_header_output _tmpheader _mp3_header_output mp3_crc _tmpheader protection_bit _tmpheader _mp3_header_output mp3channelmode_single_channel _mp3_header_output mp3channelmode_dual_channel _mp3_header_output mp3channelmode_joint_stereo _mp3_header_output mp3channelmode_stereo _mp3_header_output mp3channelmode_joint_stereo _tmpheader mode_ext _mp3_header_output mp3modeext_3 _mp3_header_output mp3modeext_2 _mp3_header_output mp3modeext_1 _mp3_header_output mp3modeext_0 _mp3_header_output mp3modeext_false _tmpheader _mp3_header_output mp3emphasis_ccit_j17 _mp3_header_output mp3emphasis_reserved _mp3_header_output mp3emphasis_50_15ms _mp3_header_output mp3emphasis_none frame_header _mp3_header_output mp3bitrate_none _mp3_header_output _mp3_header_output mpeglayer_i _mp3_header_output _mp3_header_output _mp3_header_output _tmpheader padding_bit mpeglayer_ii _mp3_header_output _mp3_header_output _mp3_header_output _tmpheader padding_bit mpeglayer_iii _mp3_header_output mpegversion_2_5 _mp3_header_output _mp3_header_output _mp3_header_output _tmpheader padding_bit _mp3_header_output _mp3_header_output _mp3_header_output _tmpheader padding_bit _mp3_header_output mpeglayer_i _mp3_header_output fto_nearest_i _mp3_header_output _mp3_header_output _tmpheader padding_bit _mp3_header_output fto_nearest_i _mp3_header_output _mp3_header_output _tmpheader padding_bit _mp3_header_output size_t size_t sideinfo_len _mp3_header_output mpegversion_1 sideinfo_len _mp3_header_output mp3channelmode_single_channel sideinfo_len _mp3_header_output mp3channelmode_single_channel vbr_header_offest sideinfo_len vbr_frames sideinfo_len _mp3_header_output mp3crc_ok sideinfo_len _mp3_header_output mp3crc_error_size _mp3_header_output mp3crc_ok size t id3 frameheader size const if info return 0 return info frame bytes id info frame bytes size info frame bytes flags size_t id3_frameheader _info _info frame_bytes_id _info frame_bytes_size _info frame_bytes_flags bool id3 frameheader parse id3 reader reader id3d notice id3 frameheader parse get cur reader get cur io exit trigger et reader if info return false if reader get end reader get cur 10 return false string textid io read text reader info frame bytes id id3d notice id3 frameheader parse textid textid id3d notice id3 frameheader parse get cur reader get cur id3 frameid fid id3 findframeid textid c str if id3fid noframe fid this set unknown frame textid c str id3d notice id3 frameheader parse unknown frame id else this set frameid fid uint32 data size io readbe number reader info frame bytes size id3d notice id3 frameheader parse data size data size id3d notice id3 frameheader parse get cur reader get cur this set data size data size uint32 flags io readbe number reader info frame bytes flags flags add flags id3d notice id3 frameheader parse flags flags id3d notice id3 frameheader parse get cur reader get cur et set exit pos reader get cur return true id3_frameheader id3_reader id3d_notice id3_frameheader getcur getcur exittrigger _info getend getcur readtext _info frame_bytes_id id3d_notice id3_frameheader id3d_notice id3_frameheader getcur getcur id3_frameid id3_findframeid c_str id3fid_noframe setunknownframe c_str id3d_notice id3_frameheader setframeid datasize readbenumber _info frame_bytes_size id3d_notice id3_frameheader datasize datasize id3d_notice id3_frameheader getcur getcur setdatasize datasize readbenumber _info frame_bytes_flags _flags id3d_notice id3_frameheader id3d_notice id3_frameheader getcur getcur setexitpos getcur void id3 frameheader render id3 writer writer const size t size 0 if null frame def todo log this id3d warning id3 frameheader render frame def is null return id3 throw id3e invalidframeid char textid if info frame bytes id strlen frame def s short textid textid frame def s short textid else textid frame def s long textid id3d notice id3 frameheader render writing textid int info frame bytes size bytes writer write chars uchar textid info frame bytes id io writebe number writer data size info frame bytes size io writebe number writer flags get info frame bytes flags id3_frameheader id3_writer size_t _frame_def id3d_warning id3_frameheader _frame_def id3_throw id3e_invalidframeid _info frame_bytes_id _frame_def sshorttextid _frame_def sshorttextid _frame_def slongtextid id3d_notice id3_frameheader _info frame_bytes_size writechars _info frame_bytes_id writebenumber _data_size _info frame_bytes_size writebenumber _flags _info frame_bytes_flags bool id3 frameheader set frameid id3 frameid id if id id3fid noframe id this get frameid return false frame def id3 findframedef id flags set tagalter frame def b tag discard flags set filealter frame def b file discard changed true return true id3_frameheader setframeid id3_frameid id3fid_noframe getframeid _frame_def id3_findframedef _flags _frame_def btagdiscard _flags _frame_def bfilediscard _changed id3 frameid id3 frameheader get frameid const id3 frameid eid id3fid noframe if null frame def eid frame def eid return eid id3_frameid id3_frameheader getframeid id3_frameid id3fid_noframe _frame_def _frame_def const char id3 frameheader get textid const char textid if info frame def if info frame bytes id strlen frame def s short textid textid frame def s short textid else textid frame def s long textid return textid id3_frameheader gettextid _info _frame_def _info frame_bytes_id _frame_def sshorttextid _frame_def sshorttextid _frame_def slongtextid const id3 framedef id3 frameheader get frame def const return frame def id3_framedef id3_frameheader getframedef _frame_def bool id3 frameheader clear bool changed this id3 header clear if dyn frame def delete frame def dyn frame def false changed true if frame def frame def null changed true return changed id3_frameheader id3_header _dyn_frame_def _frame_def _dyn_frame_def _frame_def _frame_def id3 frameheader id3 frameheader operator const id3 frameheader hdr if this hdr this clear this id3 header operator hdr if hdr dyn frame def frame def hdr frame def else frame def new id3 framedef if null frame def todo throw something here frame def eid hdr frame def eid frame def b tag discard hdr frame def b tag discard frame def b file discard hdr frame def b file discard frame def ae field defs hdr frame def ae field defs strcpy frame def s short textid hdr frame def s short textid strcpy frame def s long textid hdr frame def s long textid dyn frame def true return this id3_frameheader id3_frameheader id3_frameheader id3_header _dyn_frame_def _frame_def _frame_def _frame_def id3_framedef _frame_def _frame_def _frame_def _frame_def btagdiscard _frame_def btagdiscard _frame_def bfilediscard _frame_def bfilediscard _frame_def aefielddefs _frame_def aefielddefs _frame_def sshorttextid _frame_def sshorttextid _frame_def slongtextid _frame_def slongtextid _dyn_frame_def void id3 frameheader set unknown frame const char id clear frame def new id3 framedef if null frame def log this return frame def eid id3fid noframe frame def b tag discard false frame def b file discard false frame def ae field defs id3 fielddef default frame def s description null if strlen id 3 strcpy frame def s short textid id strcpy frame def s long textid else strcpy frame def s long textid id strcpy frame def s short textid dyn frame def true id3_frameheader setunknownframe _frame_def id3_framedef _frame_def _frame_def id3fid_noframe _frame_def btagdiscard _frame_def bfilediscard _frame_def aefielddefs id3_fielddef _frame_def sdescription _frame_def sshorttextid _frame_def slongtextid _frame_def slongtextid _frame_def sshorttextid _dyn_frame_def bool set flags uint16 f bool b bool changed flags set f b changed changed changed return changed setflags _flags _changed _changed void id3 frameimpl render id3 writer writer const return immediately if we have no fields which usually means we re trying to render a frame which has been cleared or hasn t been initialized if this num fields return id3 frameheader hdr const size t hdr size hdr size 1 write out the field data to the buffer with the assumption that we won t be decompressing since this is the usual behavior string flds io string writer fld writer flds size t orig size 0 if this get compression render fields fld writer this orig size flds size id3d notice id3 frameimpl render uncompressed fields else io compressed writer cr fld writer render fields cr this cr flush orig size cr get orig size id3d notice id3 frameimpl render compressed fields orig size orig size size t fld size flds size id3d notice id3 frameimpl render field size fld size no need to not write empty frames why would we not they can be used to fill up padding space which is even recommended in the id3 spec if fld size 0 id3d warning id3 frameimpl render no field data return determine which flags need to be set uchar eid this get encryptionid gid this get groupingid id3 frameid fid this getid if fid id3fid noframe const char tid this get textid hdr set unknown frame tid else hdr set frameid fid hdr set encryption eid 0 hdr set grouping gid 0 hdr set compression orig size fld size hdr set data size fld size hdr get compression 4 0 hdr get encryption 1 0 hdr get grouping 1 0 write out the header hdr render writer if fld size 0 no man s land not part of the header not part of the data if hdr get compression io writebe number writer orig size sizeof uint32 id3d notice id3 frameimpl render frame is compressed wrote orig size orig size if hdr get encryption writer write char eid id3d notice id3 frameimpl render frame is compressed encryption id eid if hdr get grouping writer write char gid id3d notice id3 frameimpl render frame is compressed grouping id gid write the field data writer write chars flds data fld size changed false id3_frameimpl id3_writer numfields id3_frameheader size_t hdr_size stringwriter fldwriter size_t origsize getcompression renderfields fldwriter origsize id3d_notice id3_frameimpl compressedwriter fldwriter renderfields origsize getorigsize id3d_notice id3_frameimpl origsize size_t fldsize id3d_notice id3_frameimpl fldsize fldsize id3d_warning id3_frameimpl getencryptionid getgroupingid id3_frameid id3fid_noframe gettextid setunknownframe setframeid setencryption setgrouping setcompression origsize fldsize setdatasize fldsize getcompression getencryption getgrouping fldsize getcompression writebenumber origsize id3d_notice id3_frameimpl origsize origsize getencryption writechar id3d_notice id3_frameimpl getgrouping writechar id3d_notice id3_frameimpl writechars fldsize _changed bool set encryptionid uchar id bool changed id encryption id encryption id id changed changed changed hdr set encryption true return changed setencryptionid _encryption_id _encryption_id _changed _changed _hdr setencryption bool set groupingid uchar id bool changed id grouping id grouping id id changed changed changed hdr set grouping true return changed setgroupingid _grouping_id _grouping_id _changed _changed _hdr setgrouping bool id3 frameimpl parse id3 reader reader io exit trigger et reader id3d notice id3 frameimpl parse reader get beg reader get beg id3d notice id3 frameimpl parse reader get cur reader get cur id3d notice id3 frameimpl parse reader get end reader get end id3 reader pos type beg reader get cur if hdr parse reader reader get cur beg id3d warning id3 frameimpl parse no header to parse return false id3d notice id3 frameimpl parse after hdr get cur reader get cur id3d notice id3 frameimpl parse found frame id hdr get textid data is the part of the frame buffer that appears after the header const size t data size hdr get data size id3d notice id3 frameimpl parse data size data size if reader get end beg data size id3d warning id3 frameimpl parse not enough data to parse frame return false io windowed reader wr reader data size id3d notice id3 frameimpl parse window get beg wr get beg id3d notice id3 frameimpl parse window get cur wr get cur id3d notice id3 frameimpl parse window get end wr get end unsigned long orig size 0 if hdr get compression orig size io readbe number reader sizeof uint32 allocate 2mb instead 4gb max in the decompressor later on todo decompressor should actually do the sanitycheck if orig size 2 1024 1024 id3d warning id3 frameimpl parse hdr get compression exeeds sanity limit return false id3d notice id3 frameimpl parse frame is compressed orig size orig size if hdr get encryption char ch wr read char this set encryptionid ch id3d notice id3 frameimpl parse frame is encrypted encryption id int ch if hdr get grouping char ch wr read char this set groupingid ch id3d notice id3 frameimpl parse frame is encrypted grouping id int ch set the type of frame based on the parsed header this clearfields this initfields bool success false expand out the data if it s compressed if hdr get compression success parse fields wr this else io compressed reader csr wr orig size success parse fields csr this et set exit pos wr get cur changed false return true id3_frameimpl id3_reader exittrigger id3d_notice id3_frameimpl getbeg getbeg id3d_notice id3_frameimpl getcur getcur id3d_notice id3_frameimpl getend getend id3_reader pos_type getcur _hdr getcur id3d_warning id3_frameimpl id3d_notice id3_frameimpl getcur getcur id3d_notice id3_frameimpl _hdr gettextid size_t datasize _hdr getdatasize id3d_notice id3_frameimpl datasize datasize getend datasize id3d_warning id3_frameimpl windowedreader datasize id3d_notice id3_frameimpl getbeg getbeg id3d_notice id3_frameimpl getcur getcur id3d_notice id3_frameimpl getend getend origsize _hdr getcompression origsize readbenumber origsize id3d_warning id3_frameimpl _hdr getcompression id3d_notice id3_frameimpl origsize origsize _hdr getencryption readchar setencryptionid id3d_notice id3_frameimpl encryption_id _hdr getgrouping readchar setgroupingid id3d_notice id3_frameimpl grouping_id _clearfields _initfields _hdr getcompression parsefields compressedreader origsize parsefields setexitpos getcur _changed grouping id 0 this set spec id3v2 latest this setid id _grouping_id setspec id3v2_latest grouping id 0 this initfields _grouping_id _initfields grouping id 0 this frame _grouping_id id3 frameimpl id3 frameimpl clear id3_frameimpl id3_frameimpl void id3 frameimpl clear this clearfields hdr clear encryption id 0 grouping id 0 id3_frameimpl _clearfields _hdr _encryption_id _grouping_id bool id3 frameimpl setid id3 frameid id bool changed this getid id if changed this setid id changed true return changed id3_frameimpl id3_frameid _setid _changed id3 field id3 frameimpl get field id3 fieldid field name const id3 field field null if this contains field name for const iterator fi fields begin fi fields end fi if fi getid field name field fi break return field id3_field id3_frameimpl getfield id3_fieldid fieldname id3_field fieldname const_iterator _fields _fields fieldname size t id3 frameimpl num fields const return fields size size_t id3_frameimpl numfields _fields const char id3 frameimpl get description const const id3 framedef def hdr get frame def if def return def s description return null id3_frameimpl getdescription id3_framedef _hdr getframedef sdescription const char id3 frameimpl get description id3 frameid id id3 framedef my frame def id3 findframedef id if my frame def null return my frame def s description return null id3_frameimpl getdescription id3_frameid id3_framedef myframedef id3_findframedef myframedef myframedef sdescription id3 frameimpl operator const id3 frame r frame id3 frameid eid r frame getid this setid eid id3 frame const iterator ri r frame create iterator iterator li this begin while li this end id3 field this fld li const id3 field that fld ri get next if this fld null that fld null this fld that fld delete ri this set encryptionid r frame get encryptionid this set groupingid r frame get groupingid this set compression r frame get compression this set spec r frame get spec changed false return this id3_frameimpl id3_frame rframe id3_frameid rframe id3_frame constiterator rframe createiterator id3_field thisfld id3_field thatfld getnext thisfld thatfld thisfld thatfld setencryptionid rframe getencryptionid setgroupingid rframe getgroupingid setcompression rframe getcompression setspec rframe getspec _changed bool id3 frameimpl has changed const bool changed changed for const iterator fi fields begin fi fields end fi if fi fi in scope this get spec changed fi has changed return changed id3_frameimpl haschanged _changed const_iterator _fields _fields inscope getspec haschanged size t id3 frameimpl size size t bytes used hdr size if this get encryptionid bytes used if this get groupingid bytes used id3 textenc enc id3te ascii for iterator fi fields begin fi fields end fi if fi fi in scope this get spec if fi getid id3fn textenc enc id3 textenc fi get else fi set encoding enc bytes used fi bin size return bytes used size_t id3_frameimpl size_t bytesused _hdr getencryptionid bytesused getgroupingid bytesused id3_textenc id3te_ascii _fields _fields inscope getspec id3fn_textenc id3_textenc setencoding bytesused binsize bytesused bool id3 frameimpl set spec id3 v2spec spec return hdr set spec spec id3_frameimpl setspec id3_v2spec _hdr setspec id3 v2spec id3 frameimpl get spec const return hdr get spec id3_v2spec id3_frameimpl getspec _hdr getspec bool id3 frameimpl setid id3 frameid id bool changed this clearfields changed hdr set frameid id changed this initfields return changed id3_frameimpl _setid id3_frameid _clearfields _hdr setframeid _initfields bool id3 frameimpl clearfields for iterator fi fields begin fi fields end fi delete id3 fieldimpl fi fields clear bitset reset changed true return true id3_frameimpl _clearfields _fields _fields id3_fieldimpl _fields _bitset _changed void id3 frameimpl initfields const id3 framedef info hdr get frame def if null info log this id3 field fld new id3 fieldimpl id3 fielddef default 0 fields push back fld bitset set fld getid else for size t i 0 info ae field defs i id id3fn nofield i id3 field fld new id3 fieldimpl info ae field defs i fields push back fld bitset set fld getid changed true id3_frameimpl _initfields id3_framedef _hdr getframedef id3_field id3_fieldimpl id3_fielddef _fields push_back _bitset size_t aefielddefs _id id3fn_nofield id3_field id3_fieldimpl aefielddefs _fields push_back _bitset _changed cid3 tag cid3 tag m id3tag new id3 tag cid3tag cid3tag m_id3tag id3_tag cid3 tag cid3 tag if m id3tag null delete m id3tag cid3tag cid3tag m_id3tag m_id3tag begin com map cid3 tag com interface entry iid3 com tag com interface entry i dispatch com interface entry i support error info begin_com_map cid3tag com_interface_entry iid3comtag com_interface_entry idispatch com_interface_entry isupporterrorinfo stdmethodimp cid3 tag interface supports error info refiid riid static const iid arr iid iid3comtag for int i 0 i sizeof arr sizeof arr 0 i if inline is equalguid arr i riid return s ok return s false cid3tag interfacesupportserrorinfo iid_iid3comtag inlineisequalguid s_ok s_false stdmethodimp cid3 tag get haschanged variant bool p val try p val variant false if m id3tag has changed p val variant true else p val variant false return s ok catch return atl report error clsid id3comtag an unexpected error has occurred iid iid3comtag e unexpected cid3tag get_haschanged variant_bool pval pval variant_false m_id3tag haschanged pval variant_true pval variant_false s_ok atlreporterror clsid_id3comtag iid_iid3comtag e_unexpected stdmethodimp cid3 tag clear try m id3tag clear catch return atl report error clsid id3comtag an unexpected error has occurred iid iid3comtag e unexpected return s ok cid3tag m_id3tag atlreporterror clsid_id3comtag iid_iid3comtag e_unexpected s_ok stdmethodimp cid3 tag link bstr file name uses conversion if file name null return e invalidarg try m id3tag link ole2a file name catch return atl report error clsid id3comtag an unexpected error has occurred iid iid3comtag e unexpected return s ok cid3tag filename uses_conversion filename e_invalidarg m_id3tag filename atlreporterror clsid_id3comtag iid_iid3comtag e_unexpected s_ok begin com map cid3 frame com interface entry iid3 com frame com interface entry i dispatch com interface entry i support error info begin_com_map cid3frame com_interface_entry iid3comframe com_interface_entry idispatch com_interface_entry isupporterrorinfo cid3 frame cid3 frame m frame null m tagparent null cid3frame cid3frame m_frame m_tagparent cid3 frame cid3 frame if m tagparent null m tagparent release m frame null cid3frame cid3frame m_tagparent m_tagparent m_frame id3 field getid3 field return m field id3_field getid3field m_field begin com map cid3 field com interface entry iid3 com field com interface entry i dispatch com interface entry i support error info begin_com_map cid3field com_interface_entry iid3comfield com_interface_entry idispatch com_interface_entry isupporterrorinfo cid3 field cid3 field m field null m frameparent null cid3field cid3field m_field m_frameparent cid3 field cid3 field if m frameparent null m frameparent release m field null cid3field cid3field m_frameparent m_frameparent m_field begin com map c enum fields com interface entry i enumvariant begin_com_map cenumfields com_interface_entry ienumvariant c enum fields c enum fields m tag null m currentnum 0 cenumfields cenumfields m_tag m_currentnum c enum fields c enum fields if m tag null m tag release cenumfields cenumfields m_tag m_tag