]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/texwindow.cpp
Merge branch 'master' into divVerent/farplanedist-sky-fix
[xonotic/netradiant.git] / radiant / texwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Texture Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "texwindow.h"
29
30 #include "debugging/debugging.h"
31 #include "warnings.h"
32
33 #include "ifilesystem.h"
34 #include "iundo.h"
35 #include "igl.h"
36 #include "iarchive.h"
37 #include "moduleobserver.h"
38
39 #include <set>
40 #include <string>
41 #include <vector>
42
43 #include <gtk/gtk.h>
44 #include <gtk/gtkrange.h>
45 #include <gtk/gtkframe.h>
46 #include <gtk/gtkhbox.h>
47 #include <gtk/gtkvbox.h>
48 #include <gtk/gtkvscrollbar.h>
49
50 #include "signal/signal.h"
51 #include "math/vector.h"
52 #include "texturelib.h"
53 #include "string/string.h"
54 #include "shaderlib.h"
55 #include "os/file.h"
56 #include "os/path.h"
57 #include "stream/memstream.h"
58 #include "stream/textfilestream.h"
59 #include "stream/stringstream.h"
60 #include "cmdlib.h"
61 #include "texmanip.h"
62 #include "textures.h"
63 #include "convert.h"
64
65 #include "gtkutil/menu.h"
66 #include "gtkutil/nonmodal.h"
67 #include "gtkutil/cursor.h"
68 #include "gtkutil/widget.h"
69 #include "gtkutil/glwidget.h"
70 #include "gtkutil/messagebox.h"
71
72 #include "error.h"
73 #include "map.h"
74 #include "qgl.h"
75 #include "select.h"
76 #include "brush_primit.h"
77 #include "brushmanip.h"
78 #include "patchmanip.h"
79 #include "plugin.h"
80 #include "qe3.h"
81 #include "gtkdlgs.h"
82 #include "gtkmisc.h"
83 #include "mainframe.h"
84 #include "findtexturedialog.h"
85 #include "surfacedialog.h"
86 #include "patchdialog.h"
87 #include "groupdialog.h"
88 #include "preferences.h"
89 #include "shaders.h"
90 #include "commands.h"
91
92 bool TextureBrowser_showWads(){
93         return !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) );
94 }
95
96 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser );
97
98 bool string_equal_start( const char* string, StringRange start ){
99         return string_equal_n( string, start.first, start.last - start.first );
100 }
101
102 typedef std::set<CopiedString> TextureGroups;
103
104 void TextureGroups_addWad( TextureGroups& groups, const char* archive ){
105         if ( extension_equal( path_get_extension( archive ), "wad" ) ) {
106 #if 1
107                 groups.insert( archive );
108 #else
109                 CopiedString archiveBaseName( path_get_filename_start( archive ), path_get_filename_base_end( archive ) );
110                 groups.insert( archiveBaseName );
111 #endif
112         }
113 }
114 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addWad> TextureGroupsAddWadCaller;
115
116 void TextureGroups_addShader( TextureGroups& groups, const char* shaderName ){
117         const char* texture = path_make_relative( shaderName, "textures/" );
118         if ( texture != shaderName ) {
119                 const char* last = path_remove_directory( texture );
120                 if ( !string_empty( last ) ) {
121                         groups.insert( CopiedString( StringRange( texture, --last ) ) );
122                 }
123         }
124 }
125 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addShader> TextureGroupsAddShaderCaller;
126
127 void TextureGroups_addDirectory( TextureGroups& groups, const char* directory ){
128         groups.insert( directory );
129 }
130 typedef ReferenceCaller1<TextureGroups, const char*, TextureGroups_addDirectory> TextureGroupsAddDirectoryCaller;
131
132 namespace
133 {
134 bool g_TextureBrowser_shaderlistOnly = false;
135 bool g_TextureBrowser_fixedSize = false;
136 bool g_TextureBrowser_filterNotex = false;
137 }
138
139 class DeferredAdjustment
140 {
141 gdouble m_value;
142 guint m_handler;
143 typedef void ( *ValueChangedFunction )( void* data, gdouble value );
144 ValueChangedFunction m_function;
145 void* m_data;
146
147 static gboolean deferred_value_changed( gpointer data ){
148         reinterpret_cast<DeferredAdjustment*>( data )->m_function(
149                 reinterpret_cast<DeferredAdjustment*>( data )->m_data,
150                 reinterpret_cast<DeferredAdjustment*>( data )->m_value
151                 );
152         reinterpret_cast<DeferredAdjustment*>( data )->m_handler = 0;
153         reinterpret_cast<DeferredAdjustment*>( data )->m_value = 0;
154         return FALSE;
155 }
156 public:
157 DeferredAdjustment( ValueChangedFunction function, void* data ) : m_value( 0 ), m_handler( 0 ), m_function( function ), m_data( data ){
158 }
159 void flush(){
160         if ( m_handler != 0 ) {
161                 g_source_remove( m_handler );
162                 deferred_value_changed( this );
163         }
164 }
165 void value_changed( gdouble value ){
166         m_value = value;
167         if ( m_handler == 0 ) {
168                 m_handler = g_idle_add( deferred_value_changed, this );
169         }
170 }
171 static void adjustment_value_changed( GtkAdjustment *adjustment, DeferredAdjustment* self ){
172         self->value_changed( adjustment->value );
173 }
174 };
175
176
177
178 class TextureBrowser;
179
180 typedef ReferenceCaller<TextureBrowser, TextureBrowser_queueDraw> TextureBrowserQueueDrawCaller;
181
182 void TextureBrowser_scrollChanged( void* data, gdouble value );
183
184
185 enum StartupShaders
186 {
187         STARTUPSHADERS_NONE = 0,
188         STARTUPSHADERS_COMMON,
189 };
190
191 void TextureBrowser_hideUnusedExport( const BoolImportCallback& importer );
192 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
193
194 void TextureBrowser_showShadersExport( const BoolImportCallback& importer );
195 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
196
197 void TextureBrowser_showShaderlistOnly( const BoolImportCallback& importer );
198 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
199
200 void TextureBrowser_fixedSize( const BoolImportCallback& importer );
201 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_fixedSize> TextureBrowserFixedSizeExport;
202
203 void TextureBrowser_filterNotex( const BoolImportCallback& importer );
204 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterNotex> TextureBrowserFilterNotexExport;
205
206 class TextureBrowser
207 {
208 public:
209 int width, height;
210 int originy;
211 int m_nTotalHeight;
212
213 CopiedString shader;
214
215 GtkWindow* m_parent;
216 GtkWidget* m_gl_widget;
217 GtkWidget* m_texture_scroll;
218 GtkWidget* m_treeViewTree;
219 GtkWidget* m_treeViewTags;
220 GtkWidget* m_tag_frame;
221 GtkListStore* m_assigned_store;
222 GtkListStore* m_available_store;
223 GtkWidget* m_assigned_tree;
224 GtkWidget* m_available_tree;
225 GtkWidget* m_scr_win_tree;
226 GtkWidget* m_scr_win_tags;
227 GtkWidget* m_tag_notebook;
228 GtkWidget* m_search_button;
229 GtkWidget* m_shader_info_item;
230
231 std::set<CopiedString> m_all_tags;
232 GtkListStore* m_all_tags_list;
233 std::vector<CopiedString> m_copied_tags;
234 std::set<CopiedString> m_found_shaders;
235
236 ToggleItem m_hideunused_item;
237 ToggleItem m_showshaders_item;
238 ToggleItem m_showshaderlistonly_item;
239 ToggleItem m_fixedsize_item;
240 ToggleItem m_filternotex_item;
241
242 guint m_sizeHandler;
243 guint m_exposeHandler;
244
245 bool m_heightChanged;
246 bool m_originInvalid;
247
248 DeferredAdjustment m_scrollAdjustment;
249 FreezePointer m_freezePointer;
250
251 Vector3 color_textureback;
252 // the increment step we use against the wheel mouse
253 std::size_t m_mouseWheelScrollIncrement;
254 std::size_t m_textureScale;
255 // make the texture increments match the grid changes
256 bool m_showShaders;
257 bool m_showTextureScrollbar;
258 StartupShaders m_startupShaders;
259 // if true, the texture window will only display in-use shaders
260 // if false, all the shaders in memory are displayed
261 bool m_hideUnused;
262 bool m_rmbSelected;
263 bool m_searchedTags;
264 bool m_tags;
265 // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true.
266 int m_uniformTextureSize;
267 // Return the display width of a texture in the texture browser
268 int getTextureWidth( qtexture_t* tex ){
269         int width;
270         if ( !g_TextureBrowser_fixedSize ) {
271                 // Don't use uniform size
272                 width = (int)( tex->width * ( (float)m_textureScale / 100 ) );
273         }
274         else if
275         ( tex->width >= tex->height ) {
276                 // Texture is square, or wider than it is tall
277                 width = m_uniformTextureSize;
278         }
279         else {
280                 // Otherwise, preserve the texture's aspect ratio
281                 width = (int)( m_uniformTextureSize * ( (float)tex->width / tex->height ) );
282         }
283         return width;
284 }
285 // Return the display height of a texture in the texture browser
286 int getTextureHeight( qtexture_t* tex ){
287         int height;
288         if ( !g_TextureBrowser_fixedSize ) {
289                 // Don't use uniform size
290                 height = (int)( tex->height * ( (float)m_textureScale / 100 ) );
291         }
292         else if ( tex->height >= tex->width ) {
293                 // Texture is square, or taller than it is wide
294                 height = m_uniformTextureSize;
295         }
296         else {
297                 // Otherwise, preserve the texture's aspect ratio
298                 height = (int)( m_uniformTextureSize * ( (float)tex->height / tex->width ) );
299         }
300         return height;
301 }
302
303 TextureBrowser() :
304         m_texture_scroll( 0 ),
305         m_hideunused_item( TextureBrowserHideUnusedExport() ),
306         m_showshaders_item( TextureBrowserShowShadersExport() ),
307         m_showshaderlistonly_item( TextureBrowserShowShaderlistOnlyExport() ),
308         m_fixedsize_item( TextureBrowserFixedSizeExport() ),
309         m_filternotex_item( TextureBrowserFilterNotexExport() ),
310         m_heightChanged( true ),
311         m_originInvalid( true ),
312         m_scrollAdjustment( TextureBrowser_scrollChanged, this ),
313         color_textureback( 0.25f, 0.25f, 0.25f ),
314         m_mouseWheelScrollIncrement( 64 ),
315         m_textureScale( 50 ),
316         m_showShaders( true ),
317         m_showTextureScrollbar( true ),
318         m_startupShaders( STARTUPSHADERS_NONE ),
319         m_hideUnused( false ),
320         m_rmbSelected( false ),
321         m_searchedTags( false ),
322         m_tags( false ),
323         m_uniformTextureSize( 128 ){
324 }
325 };
326
327 void ( *TextureBrowser_textureSelected )( const char* shader );
328
329
330 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser );
331
332
333 const char* TextureBrowser_getComonShadersName(){
334         const char* value = g_pGameDescription->getKeyValue( "common_shaders_name" );
335         if ( !string_empty( value ) ) {
336                 return value;
337         }
338         return "Common";
339 }
340
341 const char* TextureBrowser_getComonShadersDir(){
342         const char* value = g_pGameDescription->getKeyValue( "common_shaders_dir" );
343         if ( !string_empty( value ) ) {
344                 return value;
345         }
346         return "common/";
347 }
348
349 inline int TextureBrowser_fontHeight( TextureBrowser& textureBrowser ){
350         return GlobalOpenGL().m_font->getPixelHeight();
351 }
352
353 const char* TextureBrowser_GetSelectedShader( TextureBrowser& textureBrowser ){
354         return textureBrowser.shader.c_str();
355 }
356
357 void TextureBrowser_SetStatus( TextureBrowser& textureBrowser, const char* name ){
358         IShader* shader = QERApp_Shader_ForName( name );
359         qtexture_t* q = shader->getTexture();
360         StringOutputStream strTex( 256 );
361         strTex << name << " W: " << Unsigned( q->width ) << " H: " << Unsigned( q->height );
362         shader->DecRef();
363         g_pParentWnd->SetStatusText( g_pParentWnd->m_texture_status, strTex.c_str() );
364 }
365
366 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name );
367
368 void TextureBrowser_SetSelectedShader( TextureBrowser& textureBrowser, const char* shader ){
369         textureBrowser.shader = shader;
370         TextureBrowser_SetStatus( textureBrowser, shader );
371         TextureBrowser_Focus( textureBrowser, shader );
372
373         if ( FindTextureDialog_isOpen() ) {
374                 FindTextureDialog_selectTexture( shader );
375         }
376
377         // disable the menu item "shader info" if no shader was selected
378         IShader* ishader = QERApp_Shader_ForName( shader );
379         CopiedString filename = ishader->getShaderFileName();
380
381         if ( filename.empty() ) {
382                 if ( textureBrowser.m_shader_info_item != NULL ) {
383                         gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, FALSE );
384                 }
385         }
386         else {
387                 gtk_widget_set_sensitive( textureBrowser.m_shader_info_item, TRUE );
388         }
389
390         ishader->DecRef();
391 }
392
393
394 CopiedString g_TextureBrowser_currentDirectory;
395
396 /*
397    ============================================================================
398
399    TEXTURE LAYOUT
400
401    TTimo: now based on a rundown through all the shaders
402    NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle
403    otherwise we may need to rely on a list instead of an array storage
404    ============================================================================
405  */
406
407 class TextureLayout
408 {
409 public:
410 // texture layout functions
411 // TTimo: now based on shaders
412 int current_x, current_y, current_row;
413 };
414
415 void Texture_StartPos( TextureLayout& layout ){
416         layout.current_x = 8;
417         layout.current_y = -8;
418         layout.current_row = 0;
419 }
420
421 void Texture_NextPos( TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y ){
422         qtexture_t* q = current_texture;
423
424         int nWidth = textureBrowser.getTextureWidth( q );
425         int nHeight = textureBrowser.getTextureHeight( q );
426         if ( layout.current_x + nWidth > textureBrowser.width - 8 && layout.current_row ) { // go to the next row unless the texture is the first on the row
427                 layout.current_x = 8;
428                 layout.current_y -= layout.current_row + TextureBrowser_fontHeight( textureBrowser ) + 4;
429                 layout.current_row = 0;
430         }
431
432         *x = layout.current_x;
433         *y = layout.current_y;
434
435         // Is our texture larger than the row? If so, grow the
436         // row height to match it
437
438         if ( layout.current_row < nHeight ) {
439                 layout.current_row = nHeight;
440         }
441
442         // never go less than 96, or the names get all crunched up
443         layout.current_x += nWidth < 96 ? 96 : nWidth;
444         layout.current_x += 8;
445 }
446
447 bool TextureSearch_IsShown( const char* name ){
448         std::set<CopiedString>::iterator iter;
449
450         iter = GlobalTextureBrowser().m_found_shaders.find( name );
451
452         if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
453                 return false;
454         }
455         else {
456                 return true;
457         }
458 }
459
460 CopiedString g_notex;
461 CopiedString g_shadernotex;
462
463 // if texture_showinuse jump over non in-use textures
464 bool Texture_IsShown( IShader* shader, bool show_shaders, bool hideUnused ){
465         // filter notex / shadernotex images
466         if ( g_TextureBrowser_filterNotex && ( string_equal( g_notex.c_str(), shader->getTexture()->name ) || string_equal( g_shadernotex.c_str(), shader->getTexture()->name ) ) ) {
467                 return false;
468         }
469
470         if ( g_TextureBrowser_currentDirectory == "Untagged" ) {
471                 std::set<CopiedString>::iterator iter;
472
473                 iter = GlobalTextureBrowser().m_found_shaders.find( shader->getName() );
474
475                 if ( iter == GlobalTextureBrowser().m_found_shaders.end() ) {
476                         return false;
477                 }
478                 else {
479                         return true;
480                 }
481         }
482
483         if ( !shader_equal_prefix( shader->getName(), "textures/" ) ) {
484                 return false;
485         }
486
487         if ( !show_shaders && !shader->IsDefault() ) {
488                 return false;
489         }
490
491         if ( hideUnused && !shader->IsInUse() ) {
492                 return false;
493         }
494
495         if ( GlobalTextureBrowser().m_searchedTags ) {
496                 if ( !TextureSearch_IsShown( shader->getName() ) ) {
497                         return false;
498                 }
499                 else {
500                         return true;
501                 }
502         }
503         else {
504                 if ( !shader_equal_prefix( shader_get_textureName( shader->getName() ), g_TextureBrowser_currentDirectory.c_str() ) ) {
505                         return false;
506                 }
507         }
508
509         return true;
510 }
511
512 void TextureBrowser_heightChanged( TextureBrowser& textureBrowser ){
513         textureBrowser.m_heightChanged = true;
514
515         TextureBrowser_updateScroll( textureBrowser );
516         TextureBrowser_queueDraw( textureBrowser );
517 }
518
519 void TextureBrowser_evaluateHeight( TextureBrowser& textureBrowser ){
520         if ( textureBrowser.m_heightChanged ) {
521                 textureBrowser.m_heightChanged = false;
522
523                 textureBrowser.m_nTotalHeight = 0;
524
525                 TextureLayout layout;
526                 Texture_StartPos( layout );
527                 for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
528                 {
529                         IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
530
531                         if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
532                                 continue;
533                         }
534
535                         int x, y;
536                         Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
537                         textureBrowser.m_nTotalHeight = std::max( textureBrowser.m_nTotalHeight, abs( layout.current_y ) + TextureBrowser_fontHeight( textureBrowser ) + textureBrowser.getTextureHeight( shader->getTexture() ) + 4 );
538                 }
539         }
540 }
541
542 int TextureBrowser_TotalHeight( TextureBrowser& textureBrowser ){
543         TextureBrowser_evaluateHeight( textureBrowser );
544         return textureBrowser.m_nTotalHeight;
545 }
546
547 inline const int& min_int( const int& left, const int& right ){
548         return std::min( left, right );
549 }
550
551 void TextureBrowser_clampOriginY( TextureBrowser& textureBrowser ){
552         if ( textureBrowser.originy > 0 ) {
553                 textureBrowser.originy = 0;
554         }
555         int lower = min_int( textureBrowser.height - TextureBrowser_TotalHeight( textureBrowser ), 0 );
556         if ( textureBrowser.originy < lower ) {
557                 textureBrowser.originy = lower;
558         }
559 }
560
561 int TextureBrowser_getOriginY( TextureBrowser& textureBrowser ){
562         if ( textureBrowser.m_originInvalid ) {
563                 textureBrowser.m_originInvalid = false;
564                 TextureBrowser_clampOriginY( textureBrowser );
565                 TextureBrowser_updateScroll( textureBrowser );
566         }
567         return textureBrowser.originy;
568 }
569
570 void TextureBrowser_setOriginY( TextureBrowser& textureBrowser, int originy ){
571         textureBrowser.originy = originy;
572         TextureBrowser_clampOriginY( textureBrowser );
573         TextureBrowser_updateScroll( textureBrowser );
574         TextureBrowser_queueDraw( textureBrowser );
575 }
576
577
578 Signal0 g_activeShadersChangedCallbacks;
579
580 void TextureBrowser_addActiveShadersChangedCallback( const SignalHandler& handler ){
581         g_activeShadersChangedCallbacks.connectLast( handler );
582 }
583
584 class ShadersObserver : public ModuleObserver
585 {
586 Signal0 m_realiseCallbacks;
587 public:
588 void realise(){
589         m_realiseCallbacks();
590 }
591 void unrealise(){
592 }
593 void insert( const SignalHandler& handler ){
594         m_realiseCallbacks.connectLast( handler );
595 }
596 };
597
598 namespace
599 {
600 ShadersObserver g_ShadersObserver;
601 }
602
603 void TextureBrowser_addShadersRealiseCallback( const SignalHandler& handler ){
604         g_ShadersObserver.insert( handler );
605 }
606
607 void TextureBrowser_activeShadersChanged( TextureBrowser& textureBrowser ){
608         TextureBrowser_heightChanged( textureBrowser );
609         textureBrowser.m_originInvalid = true;
610
611         g_activeShadersChangedCallbacks();
612 }
613
614 void TextureBrowser_importShowScrollbar( TextureBrowser& textureBrowser, bool value ){
615         textureBrowser.m_showTextureScrollbar = value;
616         if ( textureBrowser.m_texture_scroll != 0 ) {
617                 widget_set_visible( textureBrowser.m_texture_scroll, textureBrowser.m_showTextureScrollbar );
618                 TextureBrowser_updateScroll( textureBrowser );
619         }
620 }
621 typedef ReferenceCaller1<TextureBrowser, bool, TextureBrowser_importShowScrollbar> TextureBrowserImportShowScrollbarCaller;
622
623
624 /*
625    ==============
626    TextureBrowser_ShowDirectory
627    relies on texture_directory global for the directory to use
628    1) Load the shaders for the given directory
629    2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader)
630    NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made
631    available through the IShaders interface
632    NOTE: for texture window layout:
633    all shaders are stored with alphabetical order after load
634    previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown
635    ( the GL textures are not flushed though)
636    ==============
637  */
638
639 bool endswith( const char *haystack, const char *needle ){
640         size_t lh = strlen( haystack );
641         size_t ln = strlen( needle );
642         if ( lh < ln ) {
643                 return false;
644         }
645         return !memcmp( haystack + ( lh - ln ), needle, ln );
646 }
647
648 bool texture_name_ignore( const char* name ){
649         StringOutputStream strTemp( string_length( name ) );
650         strTemp << LowerCase( name );
651
652         return
653                 endswith( strTemp.c_str(), ".specular" ) ||
654                 endswith( strTemp.c_str(), ".glow" ) ||
655                 endswith( strTemp.c_str(), ".bump" ) ||
656                 endswith( strTemp.c_str(), ".diffuse" ) ||
657                 endswith( strTemp.c_str(), ".blend" ) ||
658                 endswith( strTemp.c_str(), ".alpha" ) ||
659                 endswith( strTemp.c_str(), "_norm" ) ||
660                 endswith( strTemp.c_str(), "_bump" ) ||
661                 endswith( strTemp.c_str(), "_glow" ) ||
662                 endswith( strTemp.c_str(), "_gloss" ) ||
663                 endswith( strTemp.c_str(), "_pants" ) ||
664                 endswith( strTemp.c_str(), "_shirt" ) ||
665                 endswith( strTemp.c_str(), "_reflect" ) ||
666                 endswith( strTemp.c_str(), "_alpha" ) ||
667                 0;
668 }
669
670 class LoadShaderVisitor : public Archive::Visitor
671 {
672 public:
673 void visit( const char* name ){
674         IShader* shader = QERApp_Shader_ForName( CopiedString( StringRange( name, path_get_filename_base_end( name ) ) ).c_str() );
675         shader->DecRef();
676 }
677 };
678
679 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused );
680
681 GtkWidget* g_page_textures;
682
683 void TextureBrowser_toggleShow(){
684         GroupDialog_showPage( g_page_textures );
685 }
686
687
688 void TextureBrowser_updateTitle(){
689         GroupDialog_updatePageTitle( g_page_textures );
690 }
691
692
693
694 class TextureCategoryLoadShader
695 {
696 const char* m_directory;
697 std::size_t& m_count;
698 public:
699 typedef const char* first_argument_type;
700
701 TextureCategoryLoadShader( const char* directory, std::size_t& count )
702         : m_directory( directory ), m_count( count ){
703         m_count = 0;
704 }
705 void operator()( const char* name ) const {
706         if ( shader_equal_prefix( name, "textures/" )
707                  && shader_equal_prefix( name + string_length( "textures/" ), m_directory ) ) {
708                 ++m_count;
709                 // request the shader, this will load the texture if needed
710                 // this Shader_ForName call is a kind of hack
711                 IShader *pFoo = QERApp_Shader_ForName( name );
712                 pFoo->DecRef();
713         }
714 }
715 };
716
717 void TextureDirectory_loadTexture( const char* directory, const char* texture ){
718         StringOutputStream name( 256 );
719         name << directory << StringRange( texture, path_get_filename_base_end( texture ) );
720
721         if ( texture_name_ignore( name.c_str() ) ) {
722                 return;
723         }
724
725         if ( !shader_valid( name.c_str() ) ) {
726                 globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n";
727                 return;
728         }
729
730         // if a texture is already in use to represent a shader, ignore it
731         IShader* shader = QERApp_Shader_ForName( name.c_str() );
732         shader->DecRef();
733 }
734 typedef ConstPointerCaller1<char, const char*, TextureDirectory_loadTexture> TextureDirectoryLoadTextureCaller;
735
736 class LoadTexturesByTypeVisitor : public ImageModules::Visitor
737 {
738 const char* m_dirstring;
739 public:
740 LoadTexturesByTypeVisitor( const char* dirstring )
741         : m_dirstring( dirstring ){
742 }
743 void visit( const char* minor, const _QERPlugImageTable& table ) const {
744         GlobalFileSystem().forEachFile( m_dirstring, minor, TextureDirectoryLoadTextureCaller( m_dirstring ) );
745 }
746 };
747
748 void TextureBrowser_ShowDirectory( TextureBrowser& textureBrowser, const char* directory ){
749         if ( TextureBrowser_showWads() ) {
750                 Archive* archive = GlobalFileSystem().getArchive( directory );
751                 ASSERT_NOTNULL( archive );
752                 LoadShaderVisitor visitor;
753                 archive->forEachFile( Archive::VisitorFunc( visitor, Archive::eFiles, 0 ), "textures/" );
754         }
755         else
756         {
757                 g_TextureBrowser_currentDirectory = directory;
758                 TextureBrowser_heightChanged( textureBrowser );
759
760                 std::size_t shaders_count;
761                 GlobalShaderSystem().foreachShaderName( makeCallback1( TextureCategoryLoadShader( directory, shaders_count ) ) );
762                 globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
763
764                 if ( g_pGameDescription->mGameType != "doom3" ) {
765                         // load remaining texture files
766
767                         StringOutputStream dirstring( 64 );
768                         dirstring << "textures/" << directory;
769
770                         Radiant_getImageModules().foreachModule( LoadTexturesByTypeVisitor( dirstring.c_str() ) );
771                 }
772         }
773
774         // we'll display the newly loaded textures + all the ones already in use
775         TextureBrowser_SetHideUnused( textureBrowser, false );
776
777         TextureBrowser_updateTitle();
778 }
779
780 void TextureBrowser_ShowTagSearchResult( TextureBrowser& textureBrowser, const char* directory ){
781         g_TextureBrowser_currentDirectory = directory;
782         TextureBrowser_heightChanged( textureBrowser );
783
784         std::size_t shaders_count;
785         GlobalShaderSystem().foreachShaderName( makeCallback1( TextureCategoryLoadShader( directory, shaders_count ) ) );
786         globalOutputStream() << "Showing " << Unsigned( shaders_count ) << " shaders.\n";
787
788         if ( g_pGameDescription->mGameType != "doom3" ) {
789                 // load remaining texture files
790                 StringOutputStream dirstring( 64 );
791                 dirstring << "textures/" << directory;
792
793                 {
794                         LoadTexturesByTypeVisitor visitor( dirstring.c_str() );
795                         Radiant_getImageModules().foreachModule( visitor );
796                 }
797         }
798
799         // we'll display the newly loaded textures + all the ones already in use
800         TextureBrowser_SetHideUnused( textureBrowser, false );
801 }
802
803
804 bool TextureBrowser_hideUnused();
805
806 void TextureBrowser_hideUnusedExport( const BoolImportCallback& importer ){
807         importer( TextureBrowser_hideUnused() );
808 }
809 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_hideUnusedExport> TextureBrowserHideUnusedExport;
810
811 void TextureBrowser_showShadersExport( const BoolImportCallback& importer ){
812         importer( GlobalTextureBrowser().m_showShaders );
813 }
814 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShadersExport> TextureBrowserShowShadersExport;
815
816 void TextureBrowser_showShaderlistOnly( const BoolImportCallback& importer ){
817         importer( g_TextureBrowser_shaderlistOnly );
818 }
819 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_showShaderlistOnly> TextureBrowserShowShaderlistOnlyExport;
820
821 void TextureBrowser_fixedSize( const BoolImportCallback& importer ){
822         importer( g_TextureBrowser_fixedSize );
823 }
824 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_fixedSize> TextureBrowser_FixedSizeExport;
825
826 void TextureBrowser_filterNotex( const BoolImportCallback& importer ){
827         importer( g_TextureBrowser_filterNotex );
828 }
829 typedef FreeCaller1<const BoolImportCallback&, TextureBrowser_filterNotex> TextureBrowser_filterNotexExport;
830
831 void TextureBrowser_SetHideUnused( TextureBrowser& textureBrowser, bool hideUnused ){
832         if ( hideUnused ) {
833                 textureBrowser.m_hideUnused = true;
834         }
835         else
836         {
837                 textureBrowser.m_hideUnused = false;
838         }
839
840         textureBrowser.m_hideunused_item.update();
841
842         TextureBrowser_heightChanged( textureBrowser );
843         textureBrowser.m_originInvalid = true;
844 }
845
846 void TextureBrowser_ShowStartupShaders( TextureBrowser& textureBrowser ){
847         if ( textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON ) {
848                 TextureBrowser_ShowDirectory( textureBrowser, TextureBrowser_getComonShadersDir() );
849         }
850 }
851
852
853 //++timo NOTE: this is a mix of Shader module stuff and texture explorer
854 // it might need to be split in parts or moved out .. dunno
855 // scroll origin so the specified texture is completely on screen
856 // if current texture is not displayed, nothing is changed
857 void TextureBrowser_Focus( TextureBrowser& textureBrowser, const char* name ){
858         TextureLayout layout;
859         // scroll origin so the texture is completely on screen
860         Texture_StartPos( layout );
861
862         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
863         {
864                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
865
866                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
867                         continue;
868                 }
869
870                 int x, y;
871                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
872                 qtexture_t* q = shader->getTexture();
873                 if ( !q ) {
874                         break;
875                 }
876
877                 // we have found when texdef->name and the shader name match
878                 // NOTE: as everywhere else for our comparisons, we are not case sensitive
879                 if ( shader_equal( name, shader->getName() ) ) {
880                         int textureHeight = (int)( q->height * ( (float)textureBrowser.m_textureScale / 100 ) )
881                                                                 + 2 * TextureBrowser_fontHeight( textureBrowser );
882
883                         int originy = TextureBrowser_getOriginY( textureBrowser );
884                         if ( y > originy ) {
885                                 originy = y;
886                         }
887
888                         if ( y - textureHeight < originy - textureBrowser.height ) {
889                                 originy = ( y - textureHeight ) + textureBrowser.height;
890                         }
891
892                         TextureBrowser_setOriginY( textureBrowser, originy );
893                         return;
894                 }
895         }
896 }
897
898 IShader* Texture_At( TextureBrowser& textureBrowser, int mx, int my ){
899         my += TextureBrowser_getOriginY( textureBrowser ) - textureBrowser.height;
900
901         TextureLayout layout;
902         Texture_StartPos( layout );
903         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
904         {
905                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
906
907                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
908                         continue;
909                 }
910
911                 int x, y;
912                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
913                 qtexture_t  *q = shader->getTexture();
914                 if ( !q ) {
915                         break;
916                 }
917
918                 int nWidth = textureBrowser.getTextureWidth( q );
919                 int nHeight = textureBrowser.getTextureHeight( q );
920                 if ( mx > x && mx - x < nWidth
921                          && my < y && y - my < nHeight + TextureBrowser_fontHeight( textureBrowser ) ) {
922                         return shader;
923                 }
924         }
925
926         return 0;
927 }
928
929 /*
930    ==============
931    SelectTexture
932
933    By mouse click
934    ==============
935  */
936 void SelectTexture( TextureBrowser& textureBrowser, int mx, int my, bool bShift ){
937         IShader* shader = Texture_At( textureBrowser, mx, my );
938         if ( shader != 0 ) {
939                 if ( bShift ) {
940                         if ( shader->IsDefault() ) {
941                                 globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n";
942                         }
943                         else{
944                                 ViewShader( shader->getShaderFileName(), shader->getName() );
945                         }
946                 }
947                 else
948                 {
949                         TextureBrowser_SetSelectedShader( textureBrowser, shader->getName() );
950                         TextureBrowser_textureSelected( shader->getName() );
951
952                         if ( !FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected ) {
953                                 UndoableCommand undo( "textureNameSetSelected" );
954                                 Select_SetShader( shader->getName() );
955                         }
956                 }
957         }
958 }
959
960 /*
961    ============================================================================
962
963    MOUSE ACTIONS
964
965    ============================================================================
966  */
967
968 void TextureBrowser_trackingDelta( int x, int y, unsigned int state, void* data ){
969         TextureBrowser& textureBrowser = *reinterpret_cast<TextureBrowser*>( data );
970         if ( y != 0 ) {
971                 int scale = 1;
972
973                 if ( state & GDK_SHIFT_MASK ) {
974                         scale = 4;
975                 }
976
977                 int originy = TextureBrowser_getOriginY( textureBrowser );
978                 originy += y * scale;
979                 TextureBrowser_setOriginY( textureBrowser, originy );
980         }
981 }
982
983 void TextureBrowser_Tracking_MouseDown( TextureBrowser& textureBrowser ){
984         textureBrowser.m_freezePointer.freeze_pointer( textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser );
985 }
986
987 void TextureBrowser_Tracking_MouseUp( TextureBrowser& textureBrowser ){
988         textureBrowser.m_freezePointer.unfreeze_pointer( textureBrowser.m_parent );
989 }
990
991 void TextureBrowser_Selection_MouseDown( TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy ){
992         SelectTexture( textureBrowser, pointx, textureBrowser.height - 1 - pointy, ( flags & GDK_SHIFT_MASK ) != 0 );
993 }
994
995 /*
996    ============================================================================
997
998    DRAWING
999
1000    ============================================================================
1001  */
1002
1003 /*
1004    ============
1005    Texture_Draw
1006    TTimo: relying on the shaders list to display the textures
1007    we must query all qtexture_t* to manage and display through the IShaders interface
1008    this allows a plugin to completely override the texture system
1009    ============
1010  */
1011 void Texture_Draw( TextureBrowser& textureBrowser ){
1012         int originy = TextureBrowser_getOriginY( textureBrowser );
1013
1014         glClearColor( textureBrowser.color_textureback[0],
1015                                   textureBrowser.color_textureback[1],
1016                                   textureBrowser.color_textureback[2],
1017                                   0 );
1018         glViewport( 0, 0, textureBrowser.width, textureBrowser.height );
1019         glMatrixMode( GL_PROJECTION );
1020         glLoadIdentity();
1021
1022         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1023         glDisable( GL_DEPTH_TEST );
1024         glDisable( GL_BLEND );
1025         glOrtho( 0, textureBrowser.width, originy - textureBrowser.height, originy, -100, 100 );
1026         glEnable( GL_TEXTURE_2D );
1027
1028         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1029
1030         int last_y = 0, last_height = 0;
1031
1032         TextureLayout layout;
1033         Texture_StartPos( layout );
1034         for ( QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement() )
1035         {
1036                 IShader* shader = QERApp_ActiveShaders_IteratorCurrent();
1037
1038                 if ( !Texture_IsShown( shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused ) ) {
1039                         continue;
1040                 }
1041
1042                 int x, y;
1043                 Texture_NextPos( textureBrowser, layout, shader->getTexture(), &x, &y );
1044                 qtexture_t *q = shader->getTexture();
1045                 if ( !q ) {
1046                         break;
1047                 }
1048
1049                 int nWidth = textureBrowser.getTextureWidth( q );
1050                 int nHeight = textureBrowser.getTextureHeight( q );
1051
1052                 if ( y != last_y ) {
1053                         last_y = y;
1054                         last_height = 0;
1055                 }
1056                 last_height = std::max( nHeight, last_height );
1057
1058                 // Is this texture visible?
1059                 if ( ( y - nHeight - TextureBrowser_fontHeight( textureBrowser ) < originy )
1060                          && ( y > originy - textureBrowser.height ) ) {
1061                         // borders rules:
1062                         // if it's the current texture, draw a thick red line, else:
1063                         // shaders have a white border, simple textures don't
1064                         // if !texture_showinuse: (some textures displayed may not be in use)
1065                         // draw an additional square around with 0.5 1 0.5 color
1066                         if ( shader_equal( TextureBrowser_GetSelectedShader( textureBrowser ), shader->getName() ) ) {
1067                                 glLineWidth( 3 );
1068                                 if ( textureBrowser.m_rmbSelected ) {
1069                                         glColor3f( 0,0,1 );
1070                                 }
1071                                 else {
1072                                         glColor3f( 1,0,0 );
1073                                 }
1074                                 glDisable( GL_TEXTURE_2D );
1075
1076                                 glBegin( GL_LINE_LOOP );
1077                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1078                                 glVertex2i( x - 4,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1079                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight - 4 );
1080                                 glVertex2i( x + 4 + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) + 4 );
1081                                 glEnd();
1082
1083                                 glEnable( GL_TEXTURE_2D );
1084                                 glLineWidth( 1 );
1085                         }
1086                         else
1087                         {
1088                                 glLineWidth( 1 );
1089                                 // shader border:
1090                                 if ( !shader->IsDefault() ) {
1091                                         glColor3f( 1,1,1 );
1092                                         glDisable( GL_TEXTURE_2D );
1093
1094                                         glBegin( GL_LINE_LOOP );
1095                                         glVertex2i( x - 1,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1096                                         glVertex2i( x - 1,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1097                                         glVertex2i( x + 1 + nWidth,y - nHeight - 1 - TextureBrowser_fontHeight( textureBrowser ) );
1098                                         glVertex2i( x + 1 + nWidth,y + 1 - TextureBrowser_fontHeight( textureBrowser ) );
1099                                         glEnd();
1100                                         glEnable( GL_TEXTURE_2D );
1101                                 }
1102
1103                                 // highlight in-use textures
1104                                 if ( !textureBrowser.m_hideUnused && shader->IsInUse() ) {
1105                                         glColor3f( 0.5,1,0.5 );
1106                                         glDisable( GL_TEXTURE_2D );
1107                                         glBegin( GL_LINE_LOOP );
1108                                         glVertex2i( x - 3,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1109                                         glVertex2i( x - 3,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1110                                         glVertex2i( x + 3 + nWidth,y - nHeight - 3 - TextureBrowser_fontHeight( textureBrowser ) );
1111                                         glVertex2i( x + 3 + nWidth,y + 3 - TextureBrowser_fontHeight( textureBrowser ) );
1112                                         glEnd();
1113                                         glEnable( GL_TEXTURE_2D );
1114                                 }
1115                         }
1116
1117                         // Draw the texture
1118                         glBindTexture( GL_TEXTURE_2D, q->texture_number );
1119                         GlobalOpenGL_debugAssertNoErrors();
1120                         glColor3f( 1,1,1 );
1121                         glBegin( GL_QUADS );
1122                         glTexCoord2i( 0,0 );
1123                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) );
1124                         glTexCoord2i( 1,0 );
1125                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) );
1126                         glTexCoord2i( 1,1 );
1127                         glVertex2i( x + nWidth,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1128                         glTexCoord2i( 0,1 );
1129                         glVertex2i( x,y - TextureBrowser_fontHeight( textureBrowser ) - nHeight );
1130                         glEnd();
1131
1132                         // draw the texture name
1133                         glDisable( GL_TEXTURE_2D );
1134                         glColor3f( 1,1,1 );
1135
1136                         glRasterPos2i( x, y - TextureBrowser_fontHeight( textureBrowser ) + 5 );
1137
1138                         // don't draw the directory name
1139                         const char* name = shader->getName();
1140                         name += strlen( name );
1141                         while ( name != shader->getName() && *( name - 1 ) != '/' && *( name - 1 ) != '\\' )
1142                                 name--;
1143
1144                         GlobalOpenGL().drawString( name );
1145                         glEnable( GL_TEXTURE_2D );
1146                 }
1147
1148                 //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4;
1149         }
1150
1151
1152         // reset the current texture
1153         glBindTexture( GL_TEXTURE_2D, 0 );
1154         //qglFinish();
1155 }
1156
1157 void TextureBrowser_queueDraw( TextureBrowser& textureBrowser ){
1158         if ( textureBrowser.m_gl_widget != 0 ) {
1159                 gtk_widget_queue_draw( textureBrowser.m_gl_widget );
1160         }
1161 }
1162
1163
1164 void TextureBrowser_setScale( TextureBrowser& textureBrowser, std::size_t scale ){
1165         textureBrowser.m_textureScale = scale;
1166
1167         TextureBrowser_queueDraw( textureBrowser );
1168 }
1169
1170
1171 void TextureBrowser_MouseWheel( TextureBrowser& textureBrowser, bool bUp ){
1172         int originy = TextureBrowser_getOriginY( textureBrowser );
1173
1174         if ( bUp ) {
1175                 originy += int(textureBrowser.m_mouseWheelScrollIncrement);
1176         }
1177         else
1178         {
1179                 originy -= int(textureBrowser.m_mouseWheelScrollIncrement);
1180         }
1181
1182         TextureBrowser_setOriginY( textureBrowser, originy );
1183 }
1184
1185 XmlTagBuilder TagBuilder;
1186
1187 enum
1188 {
1189         TAG_COLUMN,
1190         N_COLUMNS
1191 };
1192
1193 void BuildStoreAssignedTags( GtkListStore* store, const char* shader, TextureBrowser* textureBrowser ){
1194         GtkTreeIter iter;
1195
1196         gtk_list_store_clear( store );
1197
1198         std::vector<CopiedString> assigned_tags;
1199         TagBuilder.GetShaderTags( shader, assigned_tags );
1200
1201         for ( size_t i = 0; i < assigned_tags.size(); i++ )
1202         {
1203                 gtk_list_store_append( store, &iter );
1204                 gtk_list_store_set( store, &iter, TAG_COLUMN, assigned_tags[i].c_str(), -1 );
1205         }
1206 }
1207
1208 void BuildStoreAvailableTags(   GtkListStore* storeAvailable,
1209                                                                 GtkListStore* storeAssigned,
1210                                                                 const std::set<CopiedString>& allTags,
1211                                                                 TextureBrowser* textureBrowser ){
1212         GtkTreeIter iterAssigned;
1213         GtkTreeIter iterAvailable;
1214         std::set<CopiedString>::const_iterator iterAll;
1215         gchar* tag_assigned;
1216
1217         gtk_list_store_clear( storeAvailable );
1218
1219         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( storeAssigned ), &iterAssigned ) != 0;
1220
1221         if ( !row ) { // does the shader have tags assigned?
1222                 for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1223                 {
1224                         gtk_list_store_append( storeAvailable, &iterAvailable );
1225                         gtk_list_store_set( storeAvailable, &iterAvailable, TAG_COLUMN, ( *iterAll ).c_str(), -1 );
1226                 }
1227         }
1228         else
1229         {
1230                 while ( row ) // available tags = all tags - assigned tags
1231                 {
1232                         gtk_tree_model_get( GTK_TREE_MODEL( storeAssigned ), &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1233
1234                         for ( iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll )
1235                         {
1236                                 if ( strcmp( (char*)tag_assigned, ( *iterAll ).c_str() ) != 0 ) {
1237                                         gtk_list_store_append( storeAvailable, &iterAvailable );
1238                                         gtk_list_store_set( storeAvailable, &iterAvailable, TAG_COLUMN, ( *iterAll ).c_str(), -1 );
1239                                 }
1240                                 else
1241                                 {
1242                                         row = gtk_tree_model_iter_next( GTK_TREE_MODEL( storeAssigned ), &iterAssigned ) != 0;
1243
1244                                         if ( row ) {
1245                                                 gtk_tree_model_get( GTK_TREE_MODEL( storeAssigned ), &iterAssigned, TAG_COLUMN, &tag_assigned, -1 );
1246                                         }
1247                                 }
1248                         }
1249                 }
1250         }
1251 }
1252
1253 gboolean TextureBrowser_button_press( GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1254         if ( event->type == GDK_BUTTON_PRESS ) {
1255                 if ( event->button == 3 ) {
1256                         if ( GlobalTextureBrowser().m_tags ) {
1257                                 textureBrowser->m_rmbSelected = true;
1258                                 TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1259
1260                                 BuildStoreAssignedTags( textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser );
1261                                 BuildStoreAvailableTags( textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser );
1262                                 textureBrowser->m_heightChanged = true;
1263                                 gtk_widget_show( textureBrowser->m_tag_frame );
1264
1265                                 process_gui();
1266
1267                                 TextureBrowser_Focus( *textureBrowser, textureBrowser->shader.c_str() );
1268                         }
1269                         else
1270                         {
1271                                 TextureBrowser_Tracking_MouseDown( *textureBrowser );
1272                         }
1273                 }
1274                 else if ( event->button == 1 ) {
1275                         TextureBrowser_Selection_MouseDown( *textureBrowser, event->state, static_cast<int>( event->x ), static_cast<int>( event->y ) );
1276
1277                         if ( GlobalTextureBrowser().m_tags ) {
1278                                 textureBrowser->m_rmbSelected = false;
1279                                 gtk_widget_hide( textureBrowser->m_tag_frame );
1280                         }
1281                 }
1282         }
1283         return FALSE;
1284 }
1285
1286 gboolean TextureBrowser_button_release( GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser ){
1287         if ( event->type == GDK_BUTTON_RELEASE ) {
1288                 if ( event->button == 3 ) {
1289                         if ( !GlobalTextureBrowser().m_tags ) {
1290                                 TextureBrowser_Tracking_MouseUp( *textureBrowser );
1291                         }
1292                 }
1293         }
1294         return FALSE;
1295 }
1296
1297 gboolean TextureBrowser_motion( GtkWidget *widget, GdkEventMotion *event, TextureBrowser* textureBrowser ){
1298         return FALSE;
1299 }
1300
1301 gboolean TextureBrowser_scroll( GtkWidget* widget, GdkEventScroll* event, TextureBrowser* textureBrowser ){
1302         if ( event->direction == GDK_SCROLL_UP ) {
1303                 TextureBrowser_MouseWheel( *textureBrowser, true );
1304         }
1305         else if ( event->direction == GDK_SCROLL_DOWN ) {
1306                 TextureBrowser_MouseWheel( *textureBrowser, false );
1307         }
1308         return FALSE;
1309 }
1310
1311 void TextureBrowser_scrollChanged( void* data, gdouble value ){
1312         //globalOutputStream() << "vertical scroll\n";
1313         TextureBrowser_setOriginY( *reinterpret_cast<TextureBrowser*>( data ), -(int)value );
1314 }
1315
1316 static void TextureBrowser_verticalScroll( GtkAdjustment *adjustment, TextureBrowser* textureBrowser ){
1317         textureBrowser->m_scrollAdjustment.value_changed( adjustment->value );
1318 }
1319
1320 void TextureBrowser_updateScroll( TextureBrowser& textureBrowser ){
1321         if ( textureBrowser.m_showTextureScrollbar ) {
1322                 int totalHeight = TextureBrowser_TotalHeight( textureBrowser );
1323
1324                 totalHeight = std::max( totalHeight, textureBrowser.height );
1325
1326                 GtkAdjustment *vadjustment = gtk_range_get_adjustment( GTK_RANGE( textureBrowser.m_texture_scroll ) );
1327
1328                 vadjustment->value = -TextureBrowser_getOriginY( textureBrowser );
1329                 vadjustment->page_size = textureBrowser.height;
1330                 vadjustment->page_increment = textureBrowser.height / 2;
1331                 vadjustment->step_increment = 20;
1332                 vadjustment->lower = 0;
1333                 vadjustment->upper = totalHeight;
1334
1335                 g_signal_emit_by_name( G_OBJECT( vadjustment ), "changed" );
1336         }
1337 }
1338
1339 gboolean TextureBrowser_size_allocate( GtkWidget* widget, GtkAllocation* allocation, TextureBrowser* textureBrowser ){
1340         textureBrowser->width = allocation->width;
1341         textureBrowser->height = allocation->height;
1342         TextureBrowser_heightChanged( *textureBrowser );
1343         textureBrowser->m_originInvalid = true;
1344         TextureBrowser_queueDraw( *textureBrowser );
1345         return FALSE;
1346 }
1347
1348 gboolean TextureBrowser_expose( GtkWidget* widget, GdkEventExpose* event, TextureBrowser* textureBrowser ){
1349         if ( glwidget_make_current( textureBrowser->m_gl_widget ) != FALSE ) {
1350                 GlobalOpenGL_debugAssertNoErrors();
1351                 TextureBrowser_evaluateHeight( *textureBrowser );
1352                 Texture_Draw( *textureBrowser );
1353                 GlobalOpenGL_debugAssertNoErrors();
1354                 glwidget_swap_buffers( textureBrowser->m_gl_widget );
1355         }
1356         return FALSE;
1357 }
1358
1359
1360 TextureBrowser g_TextureBrowser;
1361
1362 TextureBrowser& GlobalTextureBrowser(){
1363         return g_TextureBrowser;
1364 }
1365
1366 bool TextureBrowser_hideUnused(){
1367         return g_TextureBrowser.m_hideUnused;
1368 }
1369
1370 void TextureBrowser_ToggleHideUnused(){
1371         if ( g_TextureBrowser.m_hideUnused ) {
1372                 TextureBrowser_SetHideUnused( g_TextureBrowser, false );
1373         }
1374         else
1375         {
1376                 TextureBrowser_SetHideUnused( g_TextureBrowser, true );
1377         }
1378 }
1379
1380 void TextureGroups_constructTreeModel( TextureGroups groups, GtkTreeStore* store ){
1381         // put the information from the old textures menu into a treeview
1382         GtkTreeIter iter, child;
1383
1384         TextureGroups::const_iterator i = groups.begin();
1385         while ( i != groups.end() )
1386         {
1387                 const char* dirName = ( *i ).c_str();
1388                 const char* firstUnderscore = strchr( dirName, '_' );
1389                 StringRange dirRoot( dirName, ( firstUnderscore == 0 ) ? dirName : firstUnderscore + 1 );
1390
1391                 TextureGroups::const_iterator next = i;
1392                 ++next;
1393                 if ( firstUnderscore != 0
1394                          && next != groups.end()
1395                          && string_equal_start( ( *next ).c_str(), dirRoot ) ) {
1396                         gtk_tree_store_append( store, &iter, NULL );
1397                         gtk_tree_store_set( store, &iter, 0, CopiedString( StringRange( dirName, firstUnderscore ) ).c_str(), -1 );
1398
1399                         // keep going...
1400                         while ( i != groups.end() && string_equal_start( ( *i ).c_str(), dirRoot ) )
1401                         {
1402                                 gtk_tree_store_append( store, &child, &iter );
1403                                 gtk_tree_store_set( store, &child, 0, ( *i ).c_str(), -1 );
1404                                 ++i;
1405                         }
1406                 }
1407                 else
1408                 {
1409                         gtk_tree_store_append( store, &iter, NULL );
1410                         gtk_tree_store_set( store, &iter, 0, dirName, -1 );
1411                         ++i;
1412                 }
1413         }
1414 }
1415
1416 TextureGroups TextureGroups_constructTreeView(){
1417         TextureGroups groups;
1418
1419         if ( TextureBrowser_showWads() ) {
1420                 GlobalFileSystem().forEachArchive( TextureGroupsAddWadCaller( groups ) );
1421         }
1422         else
1423         {
1424                 // scan texture dirs and pak files only if not restricting to shaderlist
1425                 if ( g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly ) {
1426                         GlobalFileSystem().forEachDirectory( "textures/", TextureGroupsAddDirectoryCaller( groups ) );
1427                 }
1428
1429                 GlobalShaderSystem().foreachShaderName( TextureGroupsAddShaderCaller( groups ) );
1430         }
1431
1432         return groups;
1433 }
1434
1435 void TextureBrowser_constructTreeStore(){
1436         TextureGroups groups = TextureGroups_constructTreeView();
1437         GtkTreeStore* store = gtk_tree_store_new( 1, G_TYPE_STRING );
1438         TextureGroups_constructTreeModel( groups, store );
1439         std::set<CopiedString>::iterator iter;
1440
1441         GtkTreeModel* model = GTK_TREE_MODEL( store );
1442
1443         gtk_tree_view_set_model( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), model );
1444
1445         g_object_unref( G_OBJECT( store ) );
1446 }
1447
1448 void TextureBrowser_constructTreeStoreTags(){
1449         TextureGroups groups;
1450         GtkTreeStore* store = gtk_tree_store_new( 1, G_TYPE_STRING );
1451         GtkTreeModel* model = GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list );
1452
1453         gtk_tree_view_set_model( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), model );
1454
1455         g_object_unref( G_OBJECT( store ) );
1456 }
1457
1458 void TreeView_onRowActivated( GtkTreeView* treeview, GtkTreePath* path, GtkTreeViewColumn* col, gpointer userdata ){
1459         GtkTreeIter iter;
1460
1461         GtkTreeModel* model = gtk_tree_view_get_model( GTK_TREE_VIEW( treeview ) );
1462
1463         if ( gtk_tree_model_get_iter( model, &iter, path ) ) {
1464                 gchar dirName[1024];
1465
1466                 gchar* buffer;
1467                 gtk_tree_model_get( model, &iter, 0, &buffer, -1 );
1468                 strcpy( dirName, buffer );
1469                 g_free( buffer );
1470
1471                 g_TextureBrowser.m_searchedTags = false;
1472
1473                 if ( !TextureBrowser_showWads() ) {
1474                         strcat( dirName, "/" );
1475                 }
1476
1477                 ScopeDisableScreenUpdates disableScreenUpdates( dirName, "Loading Textures" );
1478                 TextureBrowser_ShowDirectory( GlobalTextureBrowser(), dirName );
1479                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
1480         }
1481 }
1482
1483 void TextureBrowser_createTreeViewTree(){
1484         GtkCellRenderer* renderer;
1485         g_TextureBrowser.m_treeViewTree = GTK_WIDGET( gtk_tree_view_new() );
1486         gtk_tree_view_set_enable_search( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), FALSE );
1487
1488         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), FALSE );
1489         g_signal_connect( g_TextureBrowser.m_treeViewTree, "row-activated", (GCallback) TreeView_onRowActivated, NULL );
1490
1491         renderer = gtk_cell_renderer_text_new();
1492         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTree ), -1, "", renderer, "text", 0, NULL );
1493
1494         TextureBrowser_constructTreeStore();
1495 }
1496
1497 void TextureBrowser_addTag();
1498 void TextureBrowser_renameTag();
1499 void TextureBrowser_deleteTag();
1500
1501 void TextureBrowser_createContextMenu( GtkWidget *treeview, GdkEventButton *event ){
1502         GtkWidget* menu = gtk_menu_new();
1503
1504         GtkWidget* menuitem = gtk_menu_item_new_with_label( "Add tag" );
1505         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_addTag, treeview );
1506         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1507
1508         menuitem = gtk_menu_item_new_with_label( "Rename tag" );
1509         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_renameTag, treeview );
1510         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1511
1512         menuitem = gtk_menu_item_new_with_label( "Delete tag" );
1513         g_signal_connect( menuitem, "activate", (GCallback)TextureBrowser_deleteTag, treeview );
1514         gtk_menu_shell_append( GTK_MENU_SHELL( menu ), menuitem );
1515
1516         gtk_widget_show_all( menu );
1517
1518         gtk_menu_popup( GTK_MENU( menu ), NULL, NULL, NULL, NULL,
1519                                         ( event != NULL ) ? event->button : 0,
1520                                         gdk_event_get_time( (GdkEvent*)event ) );
1521 }
1522
1523 gboolean TreeViewTags_onButtonPressed( GtkWidget *treeview, GdkEventButton *event ){
1524         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
1525                 GtkTreePath *path;
1526                 GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( treeview ) );
1527
1528                 if ( gtk_tree_view_get_path_at_pos( GTK_TREE_VIEW( treeview ), event->x, event->y, &path, NULL, NULL, NULL ) ) {
1529                         gtk_tree_selection_unselect_all( selection );
1530                         gtk_tree_selection_select_path( selection, path );
1531                         gtk_tree_path_free( path );
1532                 }
1533
1534                 TextureBrowser_createContextMenu( treeview, event );
1535                 return TRUE;
1536         }
1537         return FALSE;
1538 }
1539
1540 void TextureBrowser_createTreeViewTags(){
1541         GtkCellRenderer* renderer;
1542         g_TextureBrowser.m_treeViewTags = GTK_WIDGET( gtk_tree_view_new() );
1543         gtk_tree_view_set_enable_search( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), FALSE );
1544
1545         g_signal_connect( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL );
1546
1547         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), FALSE );
1548
1549         renderer = gtk_cell_renderer_text_new();
1550         gtk_tree_view_insert_column_with_attributes( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ), -1, "", renderer, "text", 0, NULL );
1551
1552         TextureBrowser_constructTreeStoreTags();
1553 }
1554
1555 GtkMenuItem* TextureBrowser_constructViewMenu( GtkMenu* menu ){
1556         GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic( "_View" );
1557
1558         if ( g_Layout_enableDetachableMenus.m_value ) {
1559                 menu_tearoff( menu );
1560         }
1561
1562         create_check_menu_item_with_mnemonic( menu, "Hide _Unused", "ShowInUse" );
1563         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1564                 create_check_menu_item_with_mnemonic( menu, "Hide Image Missing", "FilterNotex" );
1565         }
1566         menu_separator( menu );
1567
1568         create_menu_item_with_mnemonic( menu, "Show All", "ShowAllTextures" );
1569
1570         // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games
1571         if ( g_pGameDescription->mGameType == "doom3" || !string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1572                 g_TextureBrowser.m_showShaders = true;
1573         }
1574         else
1575         {
1576                 create_check_menu_item_with_mnemonic( menu, "Show shaders", "ToggleShowShaders" );
1577         }
1578
1579         if ( g_pGameDescription->mGameType != "doom3" && string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1580                 create_check_menu_item_with_mnemonic( menu, "Shaders Only", "ToggleShowShaderlistOnly" );
1581         }
1582         if ( g_TextureBrowser.m_tags ) {
1583                 create_menu_item_with_mnemonic( menu, "Show Untagged", "ShowUntagged" );
1584         }
1585
1586         create_check_menu_item_with_mnemonic( menu, "Fixed Size", "FixedSize" );
1587
1588         if ( string_empty( g_pGameDescription->getKeyValue( "show_wads" ) ) ) {
1589                 menu_separator( menu );
1590                 g_TextureBrowser.m_shader_info_item = GTK_WIDGET( create_menu_item_with_mnemonic( menu, "Shader Info", "ShaderInfo" ) );
1591                 gtk_widget_set_sensitive( g_TextureBrowser.m_shader_info_item, FALSE );
1592         }
1593
1594         return textures_menu_item;
1595 }
1596
1597 GtkMenuItem* TextureBrowser_constructToolsMenu( GtkMenu* menu ){
1598         GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic( "_Tools" );
1599
1600         if ( g_Layout_enableDetachableMenus.m_value ) {
1601                 menu_tearoff( menu );
1602         }
1603
1604         create_menu_item_with_mnemonic( menu, "Flush & Reload Shaders", "RefreshShaders" );
1605         create_menu_item_with_mnemonic( menu, "Find / Replace...", "FindReplaceTextures" );
1606
1607         return textures_menu_item;
1608 }
1609
1610 GtkMenuItem* TextureBrowser_constructTagsMenu( GtkMenu* menu ){
1611         GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic( "T_ags" );
1612
1613         if ( g_Layout_enableDetachableMenus.m_value ) {
1614                 menu_tearoff( menu );
1615         }
1616
1617         create_menu_item_with_mnemonic( menu, "Add tag", "AddTag" );
1618         create_menu_item_with_mnemonic( menu, "Rename tag", "RenameTag" );
1619         create_menu_item_with_mnemonic( menu, "Delete tag", "DeleteTag" );
1620         menu_separator( menu );
1621         create_menu_item_with_mnemonic( menu, "Copy tags from selected", "CopyTag" );
1622         create_menu_item_with_mnemonic( menu, "Paste tags to selected", "PasteTag" );
1623
1624         return textures_menu_item;
1625 }
1626
1627 gboolean TextureBrowser_tagMoveHelper( GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected ){
1628         g_assert( selected != NULL );
1629
1630         GtkTreeRowReference* rowref = gtk_tree_row_reference_new( model, path );
1631         *selected = g_slist_append( *selected, rowref );
1632
1633         return FALSE;
1634 }
1635
1636 void TextureBrowser_assignTags(){
1637         GSList* selected = NULL;
1638         GSList* node;
1639         gchar* tag_assigned;
1640
1641         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
1642
1643         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1644
1645         if ( selected != NULL ) {
1646                 for ( node = selected; node != NULL; node = node->next )
1647                 {
1648                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1649
1650                         if ( path ) {
1651                                 GtkTreeIter iter;
1652
1653                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ), &iter, path ) ) {
1654                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ), &iter, TAG_COLUMN, &tag_assigned, -1 );
1655                                         if ( !TagBuilder.CheckShaderTag( g_TextureBrowser.shader.c_str() ) ) {
1656                                                 // create a custom shader/texture entry
1657                                                 IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
1658                                                 CopiedString filename = ishader->getShaderFileName();
1659
1660                                                 if ( filename.empty() ) {
1661                                                         // it's a texture
1662                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE );
1663                                                 }
1664                                                 else {
1665                                                         // it's a shader
1666                                                         TagBuilder.AddShaderNode( g_TextureBrowser.shader.c_str(), CUSTOM, SHADER );
1667                                                 }
1668                                                 ishader->DecRef();
1669                                         }
1670                                         TagBuilder.AddShaderTag( g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG );
1671
1672                                         gtk_list_store_remove( g_TextureBrowser.m_available_store, &iter );
1673                                         gtk_list_store_append( g_TextureBrowser.m_assigned_store, &iter );
1674                                         gtk_list_store_set( g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, (char*)tag_assigned, -1 );
1675                                 }
1676                         }
1677                 }
1678
1679                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1680
1681                 // Save changes
1682                 TagBuilder.SaveXmlDoc();
1683         }
1684         g_slist_free( selected );
1685 }
1686
1687 void TextureBrowser_removeTags(){
1688         GSList* selected = NULL;
1689         GSList* node;
1690         gchar* tag;
1691
1692         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ) );
1693
1694         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1695
1696         if ( selected != NULL ) {
1697                 for ( node = selected; node != NULL; node = node->next )
1698                 {
1699                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1700
1701                         if ( path ) {
1702                                 GtkTreeIter iter;
1703
1704                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ), &iter, path ) ) {
1705                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ), &iter, TAG_COLUMN, &tag, -1 );
1706                                         TagBuilder.DeleteShaderTag( g_TextureBrowser.shader.c_str(), tag );
1707                                         gtk_list_store_remove( g_TextureBrowser.m_assigned_store, &iter );
1708                                 }
1709                         }
1710                 }
1711
1712                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1713
1714                 // Update the "available tags list"
1715                 BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
1716
1717                 // Save changes
1718                 TagBuilder.SaveXmlDoc();
1719         }
1720         g_slist_free( selected );
1721 }
1722
1723 void TextureBrowser_buildTagList(){
1724         GtkTreeIter treeIter;
1725         gtk_list_store_clear( g_TextureBrowser.m_all_tags_list );
1726
1727         std::set<CopiedString>::iterator iter;
1728
1729         for ( iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter )
1730         {
1731                 gtk_list_store_append( g_TextureBrowser.m_all_tags_list, &treeIter );
1732                 gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &treeIter, TAG_COLUMN, ( *iter ).c_str(), -1 );
1733         }
1734 }
1735
1736 void TextureBrowser_searchTags(){
1737         GSList* selected = NULL;
1738         GSList* node;
1739         gchar* tag;
1740         char buffer[256];
1741         char tags_searched[256];
1742
1743         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
1744
1745         gtk_tree_selection_selected_foreach( selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected );
1746
1747         if ( selected != NULL ) {
1748                 strcpy( buffer, "/root/*/*[tag='" );
1749                 strcpy( tags_searched, "[TAGS] " );
1750
1751                 for ( node = selected; node != NULL; node = node->next )
1752                 {
1753                         GtkTreePath* path = gtk_tree_row_reference_get_path( (GtkTreeRowReference*)node->data );
1754
1755                         if ( path ) {
1756                                 GtkTreeIter iter;
1757
1758                                 if ( gtk_tree_model_get_iter( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iter, path ) ) {
1759                                         gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iter, TAG_COLUMN, &tag, -1 );
1760
1761                                         strcat( buffer, tag );
1762                                         strcat( tags_searched, tag );
1763                                         if ( node != g_slist_last( node ) ) {
1764                                                 strcat( buffer, "' and tag='" );
1765                                                 strcat( tags_searched, ", " );
1766                                         }
1767                                 }
1768                         }
1769                 }
1770
1771                 strcat( buffer, "']" );
1772
1773                 g_slist_foreach( selected, (GFunc)gtk_tree_row_reference_free, NULL );
1774
1775                 g_TextureBrowser.m_found_shaders.clear(); // delete old list
1776                 TagBuilder.TagSearch( buffer, g_TextureBrowser.m_found_shaders );
1777
1778                 if ( !g_TextureBrowser.m_found_shaders.empty() ) { // found something
1779                         size_t shaders_found = g_TextureBrowser.m_found_shaders.size();
1780
1781                         globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n";
1782                         ScopeDisableScreenUpdates disableScreenUpdates( "Searching...", "Loading Textures" );
1783
1784                         std::set<CopiedString>::iterator iter;
1785
1786                         for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
1787                         {
1788                                 std::string path = ( *iter ).c_str();
1789                                 size_t pos = path.find_last_of( "/", path.size() );
1790                                 std::string name = path.substr( pos + 1, path.size() );
1791                                 path = path.substr( 0, pos + 1 );
1792                                 TextureDirectory_loadTexture( path.c_str(), name.c_str() );
1793                         }
1794                 }
1795                 g_TextureBrowser.m_searchedTags = true;
1796                 g_TextureBrowser_currentDirectory = tags_searched;
1797
1798                 g_TextureBrowser.m_nTotalHeight = 0;
1799                 TextureBrowser_setOriginY( g_TextureBrowser, 0 );
1800                 TextureBrowser_heightChanged( g_TextureBrowser );
1801                 TextureBrowser_updateTitle();
1802         }
1803         g_slist_free( selected );
1804 }
1805
1806 void TextureBrowser_toggleSearchButton(){
1807         gint page = gtk_notebook_get_current_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ) );
1808
1809         if ( page == 0 ) { // tag page
1810                 gtk_widget_show_all( g_TextureBrowser.m_search_button );
1811         }
1812         else {
1813                 gtk_widget_hide_all( g_TextureBrowser.m_search_button );
1814         }
1815 }
1816
1817 void TextureBrowser_constructTagNotebook(){
1818         g_TextureBrowser.m_tag_notebook = gtk_notebook_new();
1819         GtkWidget* labelTags = gtk_label_new( "Tags" );
1820         GtkWidget* labelTextures = gtk_label_new( "Textures" );
1821
1822         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tree, labelTextures );
1823         gtk_notebook_append_page( GTK_NOTEBOOK( g_TextureBrowser.m_tag_notebook ), g_TextureBrowser.m_scr_win_tags, labelTags );
1824
1825         g_signal_connect( G_OBJECT( g_TextureBrowser.m_tag_notebook ), "switch-page", G_CALLBACK( TextureBrowser_toggleSearchButton ), NULL );
1826
1827         gtk_widget_show_all( g_TextureBrowser.m_tag_notebook );
1828 }
1829
1830 void TextureBrowser_constructSearchButton(){
1831         GtkTooltips* tooltips = gtk_tooltips_new();
1832
1833         GtkWidget* image = gtk_image_new_from_stock( GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR );
1834         g_TextureBrowser.m_search_button = gtk_button_new();
1835         g_signal_connect( G_OBJECT( g_TextureBrowser.m_search_button ), "clicked", G_CALLBACK( TextureBrowser_searchTags ), NULL );
1836         gtk_tooltips_set_tip( GTK_TOOLTIPS( tooltips ), g_TextureBrowser.m_search_button, "Search with selected tags", "Search with selected tags" );
1837         gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_search_button ), image );
1838 }
1839
1840 void TextureBrowser_checkTagFile(){
1841         const char SHADERTAG_FILE[] = "shadertags.xml";
1842         CopiedString default_filename, rc_filename;
1843         StringOutputStream stream( 256 );
1844
1845         stream << LocalRcPath_get();
1846         stream << SHADERTAG_FILE;
1847         rc_filename = stream.c_str();
1848
1849         if ( file_exists( rc_filename.c_str() ) ) {
1850                 g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( rc_filename.c_str() );
1851
1852                 if ( g_TextureBrowser.m_tags ) {
1853                         globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n";
1854                 }
1855         }
1856         else
1857         {
1858                 // load default tagfile
1859                 stream.clear();
1860                 stream << g_pGameDescription->mGameToolsPath.c_str();
1861                 stream << SHADERTAG_FILE;
1862                 default_filename = stream.c_str();
1863
1864                 if ( file_exists( default_filename.c_str() ) ) {
1865                         g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc( default_filename.c_str(), rc_filename.c_str() );
1866
1867                         if ( g_TextureBrowser.m_tags ) {
1868                                 globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n";
1869                         }
1870                 }
1871                 else
1872                 {
1873                         globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n";
1874                 }
1875         }
1876 }
1877
1878 void TextureBrowser_SetNotex(){
1879         StringOutputStream name( 256 );
1880         name << GlobalRadiant().getAppPath() << "bitmaps/notex.bmp";
1881         g_notex = name.c_str();
1882
1883         name = NULL;
1884         name << GlobalRadiant().getAppPath() << "bitmaps/shadernotex.bmp";
1885         g_shadernotex = name.c_str();
1886 }
1887
1888 GtkWidget* TextureBrowser_constructWindow( GtkWindow* toplevel ){
1889         // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider
1890         // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't
1891         // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing
1892         // for the "once-the-gtk-libs-are-updated-TODO-list" :x
1893
1894         TextureBrowser_checkTagFile();
1895         TextureBrowser_SetNotex();
1896
1897         GlobalShaderSystem().setActiveShadersChangedNotify( ReferenceCaller<TextureBrowser, TextureBrowser_activeShadersChanged>( g_TextureBrowser ) );
1898
1899         g_TextureBrowser.m_parent = toplevel;
1900
1901         GtkWidget* table = gtk_table_new( 3, 3, FALSE );
1902         GtkWidget* frame_table = NULL;
1903         GtkWidget* vbox = gtk_vbox_new( FALSE, 0 );
1904         gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
1905         gtk_widget_show( vbox );
1906
1907         GtkWidget* menu_bar;
1908
1909         { // menu bar
1910                 menu_bar = gtk_menu_bar_new();
1911                 GtkWidget* menu_view = gtk_menu_new();
1912                 GtkWidget* view_item = (GtkWidget*)TextureBrowser_constructViewMenu( GTK_MENU( menu_view ) );
1913                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( view_item ), menu_view );
1914                 gtk_menu_bar_append( GTK_MENU_BAR( menu_bar ), view_item );
1915
1916                 GtkWidget* menu_tools = gtk_menu_new();
1917                 GtkWidget* tools_item = (GtkWidget*)TextureBrowser_constructToolsMenu( GTK_MENU( menu_tools ) );
1918                 gtk_menu_item_set_submenu( GTK_MENU_ITEM( tools_item ), menu_tools );
1919                 gtk_menu_bar_append( GTK_MENU_BAR( menu_bar ), tools_item );
1920
1921                 gtk_table_attach( GTK_TABLE( table ), menu_bar, 0, 3, 0, 1, GTK_FILL, GTK_SHRINK, 0, 0 );
1922                 gtk_widget_show( menu_bar );
1923         }
1924         { // Texture TreeView
1925                 g_TextureBrowser.m_scr_win_tree = gtk_scrolled_window_new( NULL, NULL );
1926                 gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tree ), 0 );
1927
1928                 // vertical only scrolling for treeview
1929                 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
1930
1931                 gtk_widget_show( g_TextureBrowser.m_scr_win_tree );
1932
1933                 TextureBrowser_createTreeViewTree();
1934
1935                 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tree ), GTK_WIDGET( g_TextureBrowser.m_treeViewTree ) );
1936                 gtk_widget_show( GTK_WIDGET( g_TextureBrowser.m_treeViewTree ) );
1937         }
1938         { // gl_widget scrollbar
1939                 GtkWidget* w = gtk_vscrollbar_new( GTK_ADJUSTMENT( gtk_adjustment_new( 0,0,0,1,1,0 ) ) );
1940                 gtk_table_attach( GTK_TABLE( table ), w, 2, 3, 1, 2, GTK_SHRINK, GTK_FILL, 0, 0 );
1941                 gtk_widget_show( w );
1942                 g_TextureBrowser.m_texture_scroll = w;
1943
1944                 GtkAdjustment *vadjustment = gtk_range_get_adjustment( GTK_RANGE( g_TextureBrowser.m_texture_scroll ) );
1945                 g_signal_connect( G_OBJECT( vadjustment ), "value_changed", G_CALLBACK( TextureBrowser_verticalScroll ), &g_TextureBrowser );
1946
1947                 widget_set_visible( g_TextureBrowser.m_texture_scroll, g_TextureBrowser.m_showTextureScrollbar );
1948         }
1949         { // gl_widget
1950                 g_TextureBrowser.m_gl_widget = glwidget_new( FALSE );
1951                 gtk_widget_ref( g_TextureBrowser.m_gl_widget );
1952
1953                 gtk_widget_set_events( g_TextureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
1954                 GTK_WIDGET_SET_FLAGS( g_TextureBrowser.m_gl_widget, GTK_CAN_FOCUS );
1955
1956                 gtk_table_attach_defaults( GTK_TABLE( table ), g_TextureBrowser.m_gl_widget, 1, 2, 1, 2 );
1957                 gtk_widget_show( g_TextureBrowser.m_gl_widget );
1958
1959                 g_TextureBrowser.m_sizeHandler = g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "size_allocate", G_CALLBACK( TextureBrowser_size_allocate ), &g_TextureBrowser );
1960                 g_TextureBrowser.m_exposeHandler = g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "expose_event", G_CALLBACK( TextureBrowser_expose ), &g_TextureBrowser );
1961
1962                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "button_press_event", G_CALLBACK( TextureBrowser_button_press ), &g_TextureBrowser );
1963                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "button_release_event", G_CALLBACK( TextureBrowser_button_release ), &g_TextureBrowser );
1964                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "motion_notify_event", G_CALLBACK( TextureBrowser_motion ), &g_TextureBrowser );
1965                 g_signal_connect( G_OBJECT( g_TextureBrowser.m_gl_widget ), "scroll_event", G_CALLBACK( TextureBrowser_scroll ), &g_TextureBrowser );
1966         }
1967
1968         // tag stuff
1969         if ( g_TextureBrowser.m_tags ) {
1970                 { // fill tag GtkListStore
1971                         g_TextureBrowser.m_all_tags_list = gtk_list_store_new( N_COLUMNS, G_TYPE_STRING );
1972                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_all_tags_list );
1973                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
1974
1975                         TagBuilder.GetAllTags( g_TextureBrowser.m_all_tags );
1976                         TextureBrowser_buildTagList();
1977                 }
1978                 { // tag menu bar
1979                         GtkWidget* menu_tags = gtk_menu_new();
1980                         GtkWidget* tags_item = (GtkWidget*)TextureBrowser_constructTagsMenu( GTK_MENU( menu_tags ) );
1981                         gtk_menu_item_set_submenu( GTK_MENU_ITEM( tags_item ), menu_tags );
1982                         gtk_menu_bar_append( GTK_MENU_BAR( menu_bar ), tags_item );
1983                 }
1984                 { // Tag TreeView
1985                         g_TextureBrowser.m_scr_win_tags = gtk_scrolled_window_new( NULL, NULL );
1986                         gtk_container_set_border_width( GTK_CONTAINER( g_TextureBrowser.m_scr_win_tags ), 0 );
1987
1988                         // vertical only scrolling for treeview
1989                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
1990
1991                         TextureBrowser_createTreeViewTags();
1992
1993                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
1994                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
1995
1996                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( g_TextureBrowser.m_scr_win_tags ), GTK_WIDGET( g_TextureBrowser.m_treeViewTags ) );
1997                         gtk_widget_show( GTK_WIDGET( g_TextureBrowser.m_treeViewTags ) );
1998                 }
1999                 { // Texture/Tag notebook
2000                         TextureBrowser_constructTagNotebook();
2001                         gtk_box_pack_start( GTK_BOX( vbox ), g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0 );
2002                 }
2003                 { // Tag search button
2004                         TextureBrowser_constructSearchButton();
2005                         gtk_box_pack_end( GTK_BOX( vbox ), g_TextureBrowser.m_search_button, FALSE, FALSE, 0 );
2006                 }
2007                 { // Tag frame
2008                         frame_table = gtk_table_new( 3, 3, FALSE );
2009
2010                         g_TextureBrowser.m_tag_frame = gtk_frame_new( "Tag assignment" );
2011                         gtk_frame_set_label_align( GTK_FRAME( g_TextureBrowser.m_tag_frame ), 0.5, 0.5 );
2012                         gtk_frame_set_shadow_type( GTK_FRAME( g_TextureBrowser.m_tag_frame ), GTK_SHADOW_NONE );
2013
2014                         gtk_table_attach( GTK_TABLE( table ), g_TextureBrowser.m_tag_frame, 1, 3, 2, 3, GTK_FILL, GTK_SHRINK, 0, 0 );
2015
2016                         gtk_widget_show( frame_table );
2017
2018                         gtk_container_add( GTK_CONTAINER( g_TextureBrowser.m_tag_frame ), frame_table );
2019                 }
2020                 { // assigned tag list
2021                         GtkWidget* scrolled_win = gtk_scrolled_window_new( NULL, NULL );
2022                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2023                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2024
2025                         g_TextureBrowser.m_assigned_store = gtk_list_store_new( N_COLUMNS, G_TYPE_STRING );
2026
2027                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_assigned_store );
2028                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2029
2030                         GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
2031
2032                         g_TextureBrowser.m_assigned_tree = gtk_tree_view_new_with_model( GTK_TREE_MODEL( g_TextureBrowser.m_assigned_store ) );
2033                         g_object_unref( G_OBJECT( g_TextureBrowser.m_assigned_store ) );
2034                         g_signal_connect( g_TextureBrowser.m_assigned_tree, "row-activated", (GCallback) TextureBrowser_removeTags, NULL );
2035                         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ), FALSE );
2036
2037                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ) );
2038                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2039
2040                         GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "", renderer, "text", TAG_COLUMN, NULL );
2041                         gtk_tree_view_append_column( GTK_TREE_VIEW( g_TextureBrowser.m_assigned_tree ), column );
2042                         gtk_widget_show( g_TextureBrowser.m_assigned_tree );
2043
2044                         gtk_widget_show( scrolled_win );
2045                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_WIDGET( g_TextureBrowser.m_assigned_tree ) );
2046
2047                         gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
2048                 }
2049                 { // available tag list
2050                         GtkWidget* scrolled_win = gtk_scrolled_window_new( NULL, NULL );
2051                         gtk_container_set_border_width( GTK_CONTAINER( scrolled_win ), 0 );
2052                         gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS );
2053
2054                         g_TextureBrowser.m_available_store = gtk_list_store_new( N_COLUMNS, G_TYPE_STRING );
2055                         GtkTreeSortable* sortable = GTK_TREE_SORTABLE( g_TextureBrowser.m_available_store );
2056                         gtk_tree_sortable_set_sort_column_id( sortable, TAG_COLUMN, GTK_SORT_ASCENDING );
2057
2058                         GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
2059
2060                         g_TextureBrowser.m_available_tree = gtk_tree_view_new_with_model( GTK_TREE_MODEL( g_TextureBrowser.m_available_store ) );
2061                         g_object_unref( G_OBJECT( g_TextureBrowser.m_available_store ) );
2062                         g_signal_connect( g_TextureBrowser.m_available_tree, "row-activated", (GCallback) TextureBrowser_assignTags, NULL );
2063                         gtk_tree_view_set_headers_visible( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ), FALSE );
2064
2065                         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
2066                         gtk_tree_selection_set_mode( selection, GTK_SELECTION_MULTIPLE );
2067
2068                         GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes( "", renderer, "text", TAG_COLUMN, NULL );
2069                         gtk_tree_view_append_column( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ), column );
2070                         gtk_widget_show( g_TextureBrowser.m_available_tree );
2071
2072                         gtk_widget_show( scrolled_win );
2073                         gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW( scrolled_win ), GTK_WIDGET( g_TextureBrowser.m_available_tree ) );
2074
2075                         gtk_table_attach( GTK_TABLE( frame_table ), scrolled_win, 2, 3, 1, 3, GTK_FILL, GTK_FILL, 0, 0 );
2076                 }
2077                 { // tag arrow buttons
2078                         GtkWidget* m_btn_left = gtk_button_new();
2079                         GtkWidget* m_btn_right = gtk_button_new();
2080                         GtkWidget* m_arrow_left = gtk_arrow_new( GTK_ARROW_LEFT, GTK_SHADOW_OUT );
2081                         GtkWidget* m_arrow_right = gtk_arrow_new( GTK_ARROW_RIGHT, GTK_SHADOW_OUT );
2082                         gtk_container_add( GTK_CONTAINER( m_btn_left ), m_arrow_left );
2083                         gtk_container_add( GTK_CONTAINER( m_btn_right ), m_arrow_right );
2084
2085                         // workaround. the size of the tag frame depends of the requested size of the arrow buttons.
2086                         gtk_widget_set_size_request( m_arrow_left, -1, 68 );
2087                         gtk_widget_set_size_request( m_arrow_right, -1, 68 );
2088
2089                         gtk_table_attach( GTK_TABLE( frame_table ), m_btn_left, 1, 2, 1, 2, GTK_SHRINK, GTK_EXPAND, 0, 0 );
2090                         gtk_table_attach( GTK_TABLE( frame_table ), m_btn_right, 1, 2, 2, 3, GTK_SHRINK, GTK_EXPAND, 0, 0 );
2091
2092                         g_signal_connect( G_OBJECT( m_btn_left ), "clicked", G_CALLBACK( TextureBrowser_assignTags ), NULL );
2093                         g_signal_connect( G_OBJECT( m_btn_right ), "clicked", G_CALLBACK( TextureBrowser_removeTags ), NULL );
2094
2095                         gtk_widget_show( m_btn_left );
2096                         gtk_widget_show( m_btn_right );
2097                         gtk_widget_show( m_arrow_left );
2098                         gtk_widget_show( m_arrow_right );
2099                 }
2100                 { // tag fram labels
2101                         GtkWidget* m_lbl_assigned = gtk_label_new( "Assigned" );
2102                         GtkWidget* m_lbl_unassigned = gtk_label_new( "Available" );
2103
2104                         gtk_table_attach( GTK_TABLE( frame_table ), m_lbl_assigned, 0, 1, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0 );
2105                         gtk_table_attach( GTK_TABLE( frame_table ), m_lbl_unassigned, 2, 3, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0 );
2106
2107                         gtk_widget_show( m_lbl_assigned );
2108                         gtk_widget_show( m_lbl_unassigned );
2109                 }
2110         }
2111         else { // no tag support, show the texture tree only
2112                 gtk_box_pack_start( GTK_BOX( vbox ), g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0 );
2113         }
2114
2115         // TODO do we need this?
2116         //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL);
2117
2118         return table;
2119 }
2120
2121 void TextureBrowser_destroyWindow(){
2122         GlobalShaderSystem().setActiveShadersChangedNotify( Callback() );
2123
2124         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_sizeHandler );
2125         g_signal_handler_disconnect( G_OBJECT( g_TextureBrowser.m_gl_widget ), g_TextureBrowser.m_exposeHandler );
2126
2127         gtk_widget_unref( g_TextureBrowser.m_gl_widget );
2128 }
2129
2130 const Vector3& TextureBrowser_getBackgroundColour( TextureBrowser& textureBrowser ){
2131         return textureBrowser.color_textureback;
2132 }
2133
2134 void TextureBrowser_setBackgroundColour( TextureBrowser& textureBrowser, const Vector3& colour ){
2135         textureBrowser.color_textureback = colour;
2136         TextureBrowser_queueDraw( textureBrowser );
2137 }
2138
2139 void TextureBrowser_selectionHelper( GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected ){
2140         g_assert( selected != NULL );
2141
2142         gchar* name;
2143         gtk_tree_model_get( model, iter, TAG_COLUMN, &name, -1 );
2144         *selected = g_slist_append( *selected, name );
2145 }
2146
2147 void TextureBrowser_shaderInfo(){
2148         const char* name = TextureBrowser_GetSelectedShader( g_TextureBrowser );
2149         IShader* shader = QERApp_Shader_ForName( name );
2150
2151         DoShaderInfoDlg( name, shader->getShaderFileName(), "Shader Info" );
2152
2153         shader->DecRef();
2154 }
2155
2156 void TextureBrowser_addTag(){
2157         CopiedString tag;
2158
2159         EMessageBoxReturn result = DoShaderTagDlg( &tag, "Add shader tag" );
2160
2161         if ( result == eIDOK && !tag.empty() ) {
2162                 GtkTreeIter iter, iter2;
2163                 g_TextureBrowser.m_all_tags.insert( tag.c_str() );
2164                 gtk_list_store_append( g_TextureBrowser.m_available_store, &iter );
2165                 gtk_list_store_set( g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1 );
2166
2167                 // Select the currently added tag in the available list
2168                 GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_available_tree ) );
2169                 gtk_tree_selection_select_iter( selection, &iter );
2170
2171                 gtk_list_store_append( g_TextureBrowser.m_all_tags_list, &iter2 );
2172                 gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iter2, TAG_COLUMN, tag.c_str(), -1 );
2173         }
2174 }
2175
2176 void TextureBrowser_renameTag(){
2177         /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because
2178            gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE,
2179            we need to count the number of selected rows first and use
2180            gtk_tree_selection_selected_foreach() then to go through the list of selected
2181            rows (which always containins a single row).
2182          */
2183
2184         GSList* selected = NULL;
2185
2186         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
2187         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2188
2189         if ( g_slist_length( selected ) == 1 ) { // we only rename a single tag
2190                 CopiedString newTag;
2191                 EMessageBoxReturn result = DoShaderTagDlg( &newTag, "Rename shader tag" );
2192
2193                 if ( result == eIDOK && !newTag.empty() ) {
2194                         GtkTreeIter iterList;
2195                         gchar* rowTag;
2196                         gchar* oldTag = (char*)selected->data;
2197
2198                         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList ) != 0;
2199
2200                         while ( row )
2201                         {
2202                                 gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList, TAG_COLUMN, &rowTag, -1 );
2203
2204                                 if ( strcmp( rowTag, oldTag ) == 0 ) {
2205                                         gtk_list_store_set( g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1 );
2206                                 }
2207                                 row = gtk_tree_model_iter_next( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterList ) != 0;
2208                         }
2209
2210                         TagBuilder.RenameShaderTag( oldTag, newTag.c_str() );
2211
2212                         g_TextureBrowser.m_all_tags.erase( (CopiedString)oldTag );
2213                         g_TextureBrowser.m_all_tags.insert( newTag );
2214
2215                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2216                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2217                 }
2218         }
2219         else
2220         {
2221                 gtk_MessageBox( GTK_WIDGET( g_TextureBrowser.m_parent ), "Select a single tag for renaming." );
2222         }
2223 }
2224
2225 void TextureBrowser_deleteTag(){
2226         GSList* selected = NULL;
2227
2228         GtkTreeSelection* selection = gtk_tree_view_get_selection( GTK_TREE_VIEW( g_TextureBrowser.m_treeViewTags ) );
2229         gtk_tree_selection_selected_foreach( selection, GtkTreeSelectionForeachFunc( TextureBrowser_selectionHelper ), &selected );
2230
2231         if ( g_slist_length( selected ) == 1 ) { // we only delete a single tag
2232                 EMessageBoxReturn result = gtk_MessageBox( GTK_WIDGET( g_TextureBrowser.m_parent ), "Are you sure you want to delete the selected tag?", "Delete Tag", eMB_YESNO, eMB_ICONQUESTION );
2233
2234                 if ( result == eIDYES ) {
2235                         GtkTreeIter iterSelected;
2236                         gchar *rowTag;
2237
2238                         gchar* tagSelected = (char*)selected->data;
2239
2240                         bool row = gtk_tree_model_get_iter_first( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected ) != 0;
2241
2242                         while ( row )
2243                         {
2244                                 gtk_tree_model_get( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected, TAG_COLUMN, &rowTag, -1 );
2245
2246                                 if ( strcmp( rowTag, tagSelected ) == 0 ) {
2247                                         gtk_list_store_remove( g_TextureBrowser.m_all_tags_list, &iterSelected );
2248                                         break;
2249                                 }
2250                                 row = gtk_tree_model_iter_next( GTK_TREE_MODEL( g_TextureBrowser.m_all_tags_list ), &iterSelected ) != 0;
2251                         }
2252
2253                         TagBuilder.DeleteTag( tagSelected );
2254                         g_TextureBrowser.m_all_tags.erase( (CopiedString)tagSelected );
2255
2256                         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser );
2257                         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2258                 }
2259         }
2260         else {
2261                 gtk_MessageBox( GTK_WIDGET( g_TextureBrowser.m_parent ), "Select a single tag for deletion." );
2262         }
2263 }
2264
2265 void TextureBrowser_copyTag(){
2266         g_TextureBrowser.m_copied_tags.clear();
2267         TagBuilder.GetShaderTags( g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags );
2268 }
2269
2270 void TextureBrowser_pasteTag(){
2271         IShader* ishader = QERApp_Shader_ForName( g_TextureBrowser.shader.c_str() );
2272         CopiedString shader = g_TextureBrowser.shader.c_str();
2273
2274         if ( !TagBuilder.CheckShaderTag( shader.c_str() ) ) {
2275                 CopiedString shaderFile = ishader->getShaderFileName();
2276                 if ( shaderFile.empty() ) {
2277                         // it's a texture
2278                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, TEXTURE );
2279                 }
2280                 else
2281                 {
2282                         // it's a shader
2283                         TagBuilder.AddShaderNode( shader.c_str(), CUSTOM, SHADER );
2284                 }
2285
2286                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2287                 {
2288                         TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2289                 }
2290         }
2291         else
2292         {
2293                 for ( size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i )
2294                 {
2295                         if ( !TagBuilder.CheckShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str() ) ) {
2296                                 // the tag doesn't exist - let's add it
2297                                 TagBuilder.AddShaderTag( shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG );
2298                         }
2299                 }
2300         }
2301
2302         ishader->DecRef();
2303
2304         TagBuilder.SaveXmlDoc();
2305         BuildStoreAssignedTags( g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser );
2306         BuildStoreAvailableTags( g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser );
2307 }
2308
2309 void RefreshShaders(){
2310         ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Loading Shaders" );
2311         GlobalShaderSystem().refresh();
2312         UpdateAllWindows();
2313 }
2314
2315 void TextureBrowser_ToggleShowShaders(){
2316         g_TextureBrowser.m_showShaders ^= 1;
2317         g_TextureBrowser.m_showshaders_item.update();
2318         TextureBrowser_queueDraw( g_TextureBrowser );
2319 }
2320
2321 void TextureBrowser_ToggleShowShaderListOnly(){
2322         g_TextureBrowser_shaderlistOnly ^= 1;
2323         g_TextureBrowser.m_showshaderlistonly_item.update();
2324
2325         TextureBrowser_constructTreeStore();
2326 }
2327
2328 void TextureBrowser_showAll(){
2329         g_TextureBrowser_currentDirectory = "";
2330         g_TextureBrowser.m_searchedTags = false;
2331         TextureBrowser_heightChanged( g_TextureBrowser );
2332         TextureBrowser_updateTitle();
2333 }
2334
2335 void TextureBrowser_showUntagged(){
2336         EMessageBoxReturn result = gtk_MessageBox( GTK_WIDGET( g_TextureBrowser.m_parent ), "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", eMB_YESNO, eMB_ICONWARNING );
2337
2338         if ( result == eIDYES ) {
2339                 g_TextureBrowser.m_found_shaders.clear();
2340                 TagBuilder.GetUntagged( g_TextureBrowser.m_found_shaders );
2341                 std::set<CopiedString>::iterator iter;
2342
2343                 ScopeDisableScreenUpdates disableScreenUpdates( "Searching untagged textures...", "Loading Textures" );
2344
2345                 for ( iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++ )
2346                 {
2347                         std::string path = ( *iter ).c_str();
2348                         size_t pos = path.find_last_of( "/", path.size() );
2349                         std::string name = path.substr( pos + 1, path.size() );
2350                         path = path.substr( 0, pos + 1 );
2351                         TextureDirectory_loadTexture( path.c_str(), name.c_str() );
2352                         globalErrorStream() << path.c_str() << name.c_str() << "\n";
2353                 }
2354
2355                 g_TextureBrowser_currentDirectory = "Untagged";
2356                 TextureBrowser_queueDraw( GlobalTextureBrowser() );
2357                 TextureBrowser_heightChanged( g_TextureBrowser );
2358                 TextureBrowser_updateTitle();
2359         }
2360 }
2361
2362 void TextureBrowser_FixedSize(){
2363         g_TextureBrowser_fixedSize ^= 1;
2364         GlobalTextureBrowser().m_fixedsize_item.update();
2365         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2366 }
2367
2368 void TextureBrowser_FilterNotex(){
2369         g_TextureBrowser_filterNotex ^= 1;
2370         GlobalTextureBrowser().m_filternotex_item.update();
2371         TextureBrowser_activeShadersChanged( GlobalTextureBrowser() );
2372 }
2373
2374 void TextureBrowser_exportTitle( const StringImportCallback& importer ){
2375         StringOutputStream buffer( 64 );
2376         buffer << "Textures: ";
2377         if ( !string_empty( g_TextureBrowser_currentDirectory.c_str() ) ) {
2378                 buffer << g_TextureBrowser_currentDirectory.c_str();
2379         }
2380         else
2381         {
2382                 buffer << "all";
2383         }
2384         importer( buffer.c_str() );
2385 }
2386
2387
2388 void TextureScaleImport( TextureBrowser& textureBrowser, int value ){
2389         switch ( value )
2390         {
2391         case 0:
2392                 TextureBrowser_setScale( textureBrowser, 10 );
2393                 break;
2394         case 1:
2395                 TextureBrowser_setScale( textureBrowser, 25 );
2396                 break;
2397         case 2:
2398                 TextureBrowser_setScale( textureBrowser, 50 );
2399                 break;
2400         case 3:
2401                 TextureBrowser_setScale( textureBrowser, 100 );
2402                 break;
2403         case 4:
2404                 TextureBrowser_setScale( textureBrowser, 200 );
2405                 break;
2406         }
2407 }
2408 typedef ReferenceCaller1<TextureBrowser, int, TextureScaleImport> TextureScaleImportCaller;
2409
2410 void TextureScaleExport( TextureBrowser& textureBrowser, const IntImportCallback& importer ){
2411         switch ( textureBrowser.m_textureScale )
2412         {
2413         case 10:
2414                 importer( 0 );
2415                 break;
2416         case 25:
2417                 importer( 1 );
2418                 break;
2419         case 50:
2420                 importer( 2 );
2421                 break;
2422         case 100:
2423                 importer( 3 );
2424                 break;
2425         case 200:
2426                 importer( 4 );
2427                 break;
2428         }
2429 }
2430 typedef ReferenceCaller1<TextureBrowser, const IntImportCallback&, TextureScaleExport> TextureScaleExportCaller;
2431
2432 void TextureBrowser_constructPreferences( PreferencesPage& page ){
2433         page.appendCheckBox(
2434                 "", "Texture scrollbar",
2435                 TextureBrowserImportShowScrollbarCaller( GlobalTextureBrowser() ),
2436                 BoolExportCaller( GlobalTextureBrowser().m_showTextureScrollbar )
2437                 );
2438         {
2439                 const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" };
2440                 page.appendCombo(
2441                         "Texture Thumbnail Scale",
2442                         STRING_ARRAY_RANGE( texture_scale ),
2443                         IntImportCallback( TextureScaleImportCaller( GlobalTextureBrowser() ) ),
2444                         IntExportCallback( TextureScaleExportCaller( GlobalTextureBrowser() ) )
2445                         );
2446         }
2447         page.appendEntry( "Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement );
2448         {
2449                 const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() };
2450                 page.appendCombo( "Load Shaders at Startup", reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ), STRING_ARRAY_RANGE( startup_shaders ) );
2451         }
2452 }
2453 void TextureBrowser_constructPage( PreferenceGroup& group ){
2454         PreferencesPage page( group.createPage( "Texture Browser", "Texture Browser Preferences" ) );
2455         TextureBrowser_constructPreferences( page );
2456 }
2457 void TextureBrowser_registerPreferencesPage(){
2458         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, TextureBrowser_constructPage>() );
2459 }
2460
2461
2462 #include "preferencesystem.h"
2463 #include "stringio.h"
2464
2465 typedef ReferenceCaller1<TextureBrowser, std::size_t, TextureBrowser_setScale> TextureBrowserSetScaleCaller;
2466
2467
2468
2469 void TextureClipboard_textureSelected( const char* shader );
2470
2471 void TextureBrowser_Construct(){
2472         GlobalCommands_insert( "ShaderInfo", FreeCaller<TextureBrowser_shaderInfo>() );
2473         GlobalCommands_insert( "ShowUntagged", FreeCaller<TextureBrowser_showUntagged>() );
2474         GlobalCommands_insert( "AddTag", FreeCaller<TextureBrowser_addTag>() );
2475         GlobalCommands_insert( "RenameTag", FreeCaller<TextureBrowser_renameTag>() );
2476         GlobalCommands_insert( "DeleteTag", FreeCaller<TextureBrowser_deleteTag>() );
2477         GlobalCommands_insert( "CopyTag", FreeCaller<TextureBrowser_copyTag>() );
2478         GlobalCommands_insert( "PasteTag", FreeCaller<TextureBrowser_pasteTag>() );
2479         GlobalCommands_insert( "RefreshShaders", FreeCaller<RefreshShaders>() );
2480         GlobalToggles_insert( "ShowInUse", FreeCaller<TextureBrowser_ToggleHideUnused>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_hideunused_item ), Accelerator( 'U' ) );
2481         GlobalCommands_insert( "ShowAllTextures", FreeCaller<TextureBrowser_showAll>(), Accelerator( 'A', (GdkModifierType)GDK_CONTROL_MASK ) );
2482         GlobalCommands_insert( "ToggleTextures", FreeCaller<TextureBrowser_toggleShow>(), Accelerator( 'T' ) );
2483         GlobalToggles_insert( "ToggleShowShaders", FreeCaller<TextureBrowser_ToggleShowShaders>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaders_item ) );
2484         GlobalToggles_insert( "ToggleShowShaderlistOnly", FreeCaller<TextureBrowser_ToggleShowShaderListOnly>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_showshaderlistonly_item ) );
2485         GlobalToggles_insert( "FixedSize", FreeCaller<TextureBrowser_FixedSize>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_fixedsize_item ) );
2486         GlobalToggles_insert( "FilterNotex", FreeCaller<TextureBrowser_FilterNotex>(), ToggleItem::AddCallbackCaller( g_TextureBrowser.m_filternotex_item ) );
2487
2488         GlobalPreferenceSystem().registerPreference( "TextureScale",
2489                                                                                                  makeSizeStringImportCallback( TextureBrowserSetScaleCaller( g_TextureBrowser ) ),
2490                                                                                                  SizeExportStringCaller( g_TextureBrowser.m_textureScale )
2491                                                                                                  );
2492         GlobalPreferenceSystem().registerPreference( "TextureScrollbar",
2493                                                                                                  makeBoolStringImportCallback( TextureBrowserImportShowScrollbarCaller( g_TextureBrowser ) ),
2494                                                                                                  BoolExportStringCaller( GlobalTextureBrowser().m_showTextureScrollbar )
2495                                                                                                  );
2496         GlobalPreferenceSystem().registerPreference( "ShowShaders", BoolImportStringCaller( GlobalTextureBrowser().m_showShaders ), BoolExportStringCaller( GlobalTextureBrowser().m_showShaders ) );
2497         GlobalPreferenceSystem().registerPreference( "ShowShaderlistOnly", BoolImportStringCaller( g_TextureBrowser_shaderlistOnly ), BoolExportStringCaller( g_TextureBrowser_shaderlistOnly ) );
2498         GlobalPreferenceSystem().registerPreference( "FixedSize", BoolImportStringCaller( g_TextureBrowser_fixedSize ), BoolExportStringCaller( g_TextureBrowser_fixedSize ) );
2499         GlobalPreferenceSystem().registerPreference( "FilterNotex", BoolImportStringCaller( g_TextureBrowser_filterNotex ), BoolExportStringCaller( g_TextureBrowser_filterNotex ) );
2500         GlobalPreferenceSystem().registerPreference( "LoadShaders", IntImportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ), IntExportStringCaller( reinterpret_cast<int&>( GlobalTextureBrowser().m_startupShaders ) ) );
2501         GlobalPreferenceSystem().registerPreference( "WheelMouseInc", SizeImportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ), SizeExportStringCaller( GlobalTextureBrowser().m_mouseWheelScrollIncrement ) );
2502         GlobalPreferenceSystem().registerPreference( "SI_Colors0", Vector3ImportStringCaller( GlobalTextureBrowser().color_textureback ), Vector3ExportStringCaller( GlobalTextureBrowser().color_textureback ) );
2503
2504         g_TextureBrowser.shader = texdef_name_default();
2505
2506         Textures_setModeChangedNotify( ReferenceCaller<TextureBrowser, TextureBrowser_queueDraw>( g_TextureBrowser ) );
2507
2508         TextureBrowser_registerPreferencesPage();
2509
2510         GlobalShaderSystem().attach( g_ShadersObserver );
2511
2512         TextureBrowser_textureSelected = TextureClipboard_textureSelected;
2513 }
2514 void TextureBrowser_Destroy(){
2515         GlobalShaderSystem().detach( g_ShadersObserver );
2516
2517         Textures_setModeChangedNotify( Callback() );
2518 }