<commit_before>// Screen.cc for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 <NAME> (<EMAIL>)
//
// Screen.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 <NAME> (<EMAIL>)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.	IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: Screen.cc,v 1.24 2002/02/17 18:56:14 fluxgen Exp $

// stupid macros needed to access some functions in version 2 of the GNU C
// library
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#ifdef		HAVE_CONFIG_H
#	include "../config.h"
#endif // HAVE_CONFIG_H

#include "Screen.hh"

#include "i18n.hh"
#include "fluxbox.hh"
#include "Clientmenu.hh"
#include "Icon.hh"
#include "Image.hh"
#include "StringUtil.hh"

#ifdef		SLIT
#include "Slit.hh"
#endif // SLIT

#include "Rootmenu.hh"
#include "Toolbar.hh"
#include "Window.hh"
#include "Workspace.hh"
#include "Workspacemenu.hh"

#ifdef STDC_HEADERS
#	include <sys/types.h>
#endif // STDC_HEADERS

#ifdef HAVE_CTYPE_H
#	include <ctype.h>
#endif // HAVE_CTYPE_H

#ifdef HAVE_DIRENT_H
#	include <dirent.h>
#endif // HAVE_DIRENT_H

#ifdef HAVE_LOCALE_H
#	include <locale.h>
#endif // HAVE_LOCALE_H

#ifdef HAVE_UNISTD_H
#	include <sys/types.h>
#	include <unistd.h>
#endif // HAVE_UNISTD_H

#ifdef HAVE_SYS_STAT_H
#	include <sys/stat.h>
#endif // HAVE_SYS_STAT_H

#ifdef HAVE_STDARG_H
#	include <stdarg.h>
#endif // HAVE_STDARG_H

#ifndef  MAXPATHLEN
#define	 MAXPATHLEN 255
#endif // MAXPATHLEN

#ifndef	 FONT_ELEMENT_SIZE
#define	 FONT_ELEMENT_SIZE 50
#endif // FONT_ELEMENT_SIZE

#include <X11/Xatom.h>
#include <X11/keysym.h>

#include <iostream>
#include <memory>
#include <algorithm>

using namespace std;

static Bool running = True;

static int anotherWMRunning(Display *display, XErrorEvent *) {
	fprintf(stderr,
		I18n::instance()->
		getMessage(
#ifdef		NLS
			ScreenSet, ScreenAnotherWMRunning,
#else // !NLS
			0, 0,
#endif // NLS
			"BScreen::BScreen: an error occured while querying the X server.\n"
			"	another window manager already running on display %s.\n"),
			DisplayString(display));

	running = False;

	return(-1);
}

static int dcmp(const void *one, const void *two) {
	return (strcmp((*(char **) one), (*(char **) two)));
}

//---------- resource manipulators ---------
template<>
void Resource<Tab::Alignment>::
setFromString(const char *strval) {	
	m_value = Tab::getTabAlignmentNum(strval);
}

template<>
void Resource<Tab::Placement>::
setFromString(const char *strval) {	
	m_value = Tab::getTabPlacementNum(strval);
}

template<>
void Resource<Toolbar::Placement>::
setFromString(const char *strval) {
	if (strcasecmp(strval, "TopLeft")==0)
		m_value = Toolbar::TOPLEFT;
	else if (strcasecmp(strval, "BottomLeft")==0)
		m_value = Toolbar::BOTTOMLEFT;
	else if (strcasecmp(strval, "TopCenter")==0)
		m_value = Toolbar::TOPCENTER;
	else if (strcasecmp(strval, "BottomCenter")==0)
		m_value = Toolbar::BOTTOMCENTER;
	else if (strcasecmp(strval, "TopRight")==0)
		m_value = Toolbar::TOPRIGHT;
	else if (strcasecmp(strval, "BottomRight")==0)
		m_value = Toolbar::BOTTOMRIGHT;
	else
		setDefaultValue();
}

//--------- resource accessors --------------
template<>
string Resource<Tab::Alignment>::
getString() {
	return Tab::getTabAlignmentString(m_value);
}

template<>
string Resource<Tab::Placement>::
getString() {
	return Tab::getTabPlacementString(m_value);
}

template<>
string Resource<Toolbar::Placement>::
getString() {
	switch (m_value) {
		case Toolbar::TOPLEFT:
			return string("TopLeft");
			break;
		case Toolbar::BOTTOMLEFT:
			return string("BottomLeft");
			break;
		case Toolbar::TOPCENTER:
			return string("TopCenter");
			break;			
		case Toolbar::BOTTOMCENTER:
			return string("BottomCenter");
			break;
		case Toolbar::TOPRIGHT:
			return string("TopRight");
			break;
		case Toolbar::BOTTOMRIGHT:
			return string("BottomRight");
			break;
	}
	//default string
	return string("BottomCenter");
}


BScreen::ScreenResource::ScreenResource(ResourceManager &rm, 
	const std::string &scrname, const std::string &altscrname):
toolbar_on_top(rm, false, scrname+".toolbar.onTop", altscrname+".Toolbar.OnTop"),
toolbar_auto_hide(rm, false, scrname+".toolbar.autoHide", altscrname+".Toolbar.AutoHide"),
image_dither(rm, false, scrname+".imageDither", altscrname+".ImageDither"),
opaque_move(rm, false, "session.opaqueMove", "Session.OpaqueMove"),
full_max(rm, true, scrname+".fullMaximization", altscrname+".FullMaximization"),
max_over_slit(rm, true, scrname+".maxOverSlit",altscrname+".MaxOverSlit"),
tab_rotate_vertical(rm, true, scrname+".tab.rotatevertical", altscrname+".Tab.RotateVertical"),
sloppy_window_grouping(rm, true, scrname+".sloppywindowgrouping", altscrname+".SloppyWindowGrouping"),
focus_last(rm, true, scrname+".focusLastWindow", altscrname+".FocusLastWindow"),
focus_new(rm, true, scrname+".focusNewWindows", altscrname+".FocusNewWindows"),
rootcommand(rm, "", scrname+".rootCommand", altscrname+".RootCommand"),
workspaces(rm, 1, scrname+".workspaces", altscrname+".Workspaces"),
toolbar_width_percent(rm, 65, scrname+".toolbar.widthPercent", altscrname+".Toolbar.WidthPercent"),
edge_snap_threshold(rm, 0, scrname+".edgeSnapThreshold", altscrname+".EdgeSnapThreshold"),
tab_width(rm, 64, scrname+".tab.width", altscrname+".Tab.Width"),
tab_height(rm, 16, scrname+".tab.height", altscrname+".Tab.Height"),
tab_placement(rm, Tab::PTOP, scrname+".tab.placement", altscrname+".Tab.Placement"),
tab_alignment(rm, Tab::ALEFT, scrname+".tab.alignment", altscrname+".Tab.Alignment"),
toolbar_placement(rm, Toolbar::BOTTOMCENTER, scrname+".toolbar.placement", altscrname+".Toolbar.Placement")
{

};

BScreen::BScreen(ResourceManager &rm, Fluxbox *b, 
	const string &screenname, const string &altscreenname,
	int scrn) : ScreenInfo(b, scrn),
#ifdef GNOME
gnome_win(None),
#endif
theme(0),
resource(rm, screenname, altscreenname)
{
	fluxbox = b;

	event_mask = ColormapChangeMask | EnterWindowMask | PropertyChangeMask |
		SubstructureRedirectMask | KeyPressMask | KeyReleaseMask |
		ButtonPressMask | ButtonReleaseMask| SubstructureNotifyMask;

	XErrorHandler old = XSetErrorHandler((XErrorHandler) anotherWMRunning);
	XSelectInput(getBaseDisplay()->getXDisplay(), getRootWindow(), event_mask);
	XSync(getBaseDisplay()->getXDisplay(), False);
	XSetErrorHandler((XErrorHandler) old);

	managed = running;
	if (! managed)
		return;
	
	I18n *i18n = I18n::instance();
	
	fprintf(stderr,
		i18n->
		getMessage(
		#ifdef NLS
				ScreenSet, ScreenManagingScreen,
		#else // !NLS
				0, 0,
		#endif // NLS
				"BScreen::BScreen: managing screen %d "
				"using visual 0x%lx, depth %d\n"),
		getScreenNumber(), XVisualIDFromVisual(getVisual()),
		getDepth());

	rootmenu = 0;
		
	#ifdef HAVE_STRFTIME
	resource.strftime_format = 0;
	#endif // HAVE_STRFTIME

	#ifdef HAVE_GETPID
	pid_t bpid = getpid();

	XChangeProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
		fluxbox->getFluxboxPidAtom(), XA_CARDINAL,
		sizeof(pid_t) * 8, PropModeReplace,
		(unsigned char *) &bpid, 1);
	#endif // HAVE_GETPID


	XDefineCursor(getBaseDisplay()->getXDisplay(), getRootWindow(),
		fluxbox->getSessionCursor());

	image_control =
		new BImageControl(fluxbox, this, True, fluxbox->getColorsPerChannel(),
			fluxbox->getCacheLife(), fluxbox->getCacheMax());
	image_control->installRootColormap();
	root_colormap_installed = True;

	fluxbox->load_rc(this);

	image_control->setDither(*resource.image_dither);
	theme = new Theme(getBaseDisplay()->getXDisplay(), getRootWindow(), getColormap(), getScreenNumber(), 
			image_control, fluxbox->getStyleFilename(), getRootCommand().c_str());

	#ifdef GNOME
	initGnomeAtoms();
	#endif 

	#ifdef NEWWMSPEC
	Atom netwmsupported[] = {
//		getBaseDisplay()->getNETWMStateAtom(),
		getBaseDisplay()->getNETNumberOfDesktopsAtom(),
		getBaseDisplay()->getNETCurrentDesktopAtom(),
		getBaseDisplay()->getNETSupportingWMCheckAtom(),		
	};	

	XChangeProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
		getBaseDisplay()->getNETSupportedAtom(), XA_ATOM, 32, PropModeReplace,
		(unsigned char *)netwmsupported, (sizeof netwmsupported)/sizeof netwmsupported[0]);
	#endif //!NEWWMSPEC

	const char *s =	i18n->getMessage(
	#ifdef		NLS
		ScreenSet, ScreenPositionLength,
	#else // !NLS
		0, 0,
	#endif // NLS
		"0: 0000 x 0: 0000");
	
	int l = strlen(s);

	if (i18n->multibyte()) {
		XRectangle ink, logical;
		XmbTextExtents(theme->getWindowStyle().font.set, s, l, &ink, &logical);
		geom_w = logical.width;

		geom_h = theme->getWindowStyle().font.set_extents->max_ink_extent.height;
	} else {
		geom_h = theme->getWindowStyle().font.fontstruct->ascent +
			theme->getWindowStyle().font.fontstruct->descent;

		geom_w = XTextWidth(theme->getWindowStyle().font.fontstruct, s, l);
	}

	geom_w += getBevelWidth()*2;
	geom_h += getBevelWidth()*2;

	XSetWindowAttributes attrib;
	unsigned long mask = CWBorderPixel | CWColormap | CWSaveUnder;
	attrib.border_pixel = getBorderColor()->getPixel();
	attrib.colormap = getColormap();
	attrib.save_under = True;

	geom_window =
		XCreateWindow(getBaseDisplay()->getXDisplay(), getRootWindow(),
			0, 0, geom_w, geom_h, theme->getBorderWidth(), getDepth(),
			InputOutput, getVisual(), mask, &attrib);
	geom_visible = False;

	if (theme->getWindowStyle().l_focus.getTexture() & BImage::PARENTRELATIVE) {
		if (theme->getWindowStyle().t_focus.getTexture() ==
			(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				 theme->getWindowStyle().t_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				 &theme->getWindowStyle().t_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				 geom_window, geom_pixmap);
		}
	} else {
		if (theme->getWindowStyle().l_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				 theme->getWindowStyle().l_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				 &theme->getWindowStyle().l_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				 geom_window, geom_pixmap);
		}
	}

	workspacemenu = new Workspacemenu(this);
	iconmenu = new Iconmenu(this);	
	configmenu = new Configmenu(this);

	Workspace *wkspc = (Workspace *) 0;
	if (*resource.workspaces != 0) {
		for (int i = 0; i < *resource.workspaces; ++i) {
			wkspc = new Workspace(this, workspacesList.size());
			workspacesList.push_back(wkspc);
			workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
		}
	} else {
		wkspc = new Workspace(this, workspacesList.size());
		workspacesList.push_back(wkspc);
		workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
	}

	workspacemenu->insert(i18n->
		getMessage(
		#ifdef NLS
			 IconSet, IconIcons,
		#else // !NLS
			 0, 0,
		#endif // NLS
			 "Icons"),
			iconmenu);
	workspacemenu->update();

	current_workspace = workspacesList.front();
	workspacemenu->setItemSelected(2, True);

	toolbar = new Toolbar(this);

	#ifdef SLIT
	slit = new Slit(this);
	#endif // SLIT

	InitMenu();

	raiseWindows(0, 0);
	rootmenu->update();

	changeWorkspaceID(0);
	updateNetizenWorkspaceCount();
	
	int i;
	unsigned int nchild;
	Window r, p, *children;
	XQueryTree(getBaseDisplay()->getXDisplay(), getRootWindow(), &r, &p,
			 &children, &nchild);

	// preen the window list of all icon windows... for better dockapp support
	for (i = 0; i < (int) nchild; i++) {
		
		if (children[i] == None) continue;

		XWMHints *wmhints = XGetWMHints(getBaseDisplay()->getXDisplay(),
			children[i]);

		if (wmhints) {
			if ((wmhints->flags & IconWindowHint) &&
					(wmhints->icon_window != children[i]))
				for (int j = 0; j < (int) nchild; j++) {
					if (children[j] == wmhints->icon_window) {
						children[j] = None;
						break;
					}
				}
			XFree(wmhints);
		}
	}

	// manage shown windows
	for (i = 0; i < (int) nchild; ++i) {
		if (children[i] == None || (! fluxbox->validateWindow(children[i])))
			continue;

		XWindowAttributes attrib;
		if (XGetWindowAttributes(getBaseDisplay()->getXDisplay(), children[i],
				&attrib)) {
			if (attrib.override_redirect) 
				continue;

			if (attrib.map_state != IsUnmapped) {
				
				FluxboxWindow *win = new FluxboxWindow(children[i], this);
				if (!win->isManaged()) {
					delete win;
					win = 0;
				}
				
				if (win) {
					XMapRequestEvent mre;
					mre.window = children[i];
					win->restoreAttributes();
					win->mapRequestEvent(&mre);
				}
			}
		}
	}

	if (! resource.sloppy_focus)
		XSetInputFocus(getBaseDisplay()->getXDisplay(), toolbar->getWindowID(),
			RevertToParent, CurrentTime);

	XFree(children);
	XFlush(getBaseDisplay()->getXDisplay());
	
}

namespace {
    template<typename T>
    void delete_obj(T * obj) {
        delete obj;
    }
}

BScreen::~BScreen(void) {
	#ifdef GNOME
	XDestroyWindow(getBaseDisplay()->getXDisplay(), gnome_win);
	#endif
	if (! managed) return;

	if (geom_pixmap != None)
		image_control->removeImage(geom_pixmap);

	if (geom_window != None)
		XDestroyWindow(getBaseDisplay()->getXDisplay(), geom_window);

	removeWorkspaceNames();

    std::for_each(
        workspacesList.begin(),
        workspacesList.end(),
        delete_obj<Workspace>);

    // don't delete items in the rootmenuList?

    std::for_each(
        iconList.begin(),
        iconList.end(),
        delete_obj<FluxboxWindow>);

    std::for_each(
        netizenList.begin(),
        netizenList.end(),
        delete_obj<Netizen>);

#ifdef		HAVE_STRFTIME
	if (resource.strftime_format)
		delete [] resource.strftime_format;
#endif // HAVE_STRFTIME

	delete rootmenu;
	delete workspacemenu;
	delete iconmenu;
	delete configmenu;

#ifdef		SLIT
	delete slit;
#endif // SLIT

	delete toolbar;
	delete image_control;

	delete theme;

}

void BScreen::reconfigure(void) {
	#ifdef DEBUG
	cerr<<__FILE__<<"("<<__LINE__<<"): BScreen::reconfigure"<<endl;
	#endif
	Fluxbox::instance()->loadRootCommand(this);
	theme->setRootCommand(getRootCommand());

	theme->load(fluxbox->getStyleFilename());
	theme->reconfigure();
	I18n *i18n = I18n::instance();

	const char *s = i18n->getMessage(
#ifdef		NLS
			ScreenSet, ScreenPositionLength,
#else // !NLS
			0, 0,
#endif // NLS
			"0: 0000 x 0: 0000");
	int l = strlen(s);

	if (i18n->multibyte()) {
		XRectangle ink, logical;
		XmbTextExtents(theme->getWindowStyle().font.set, s, l, &ink, &logical);
		geom_w = logical.width;

		geom_h = theme->getWindowStyle().font.set_extents->max_ink_extent.height;
	} else {
		geom_w = XTextWidth(theme->getWindowStyle().font.fontstruct, s, l);

		geom_h = theme->getWindowStyle().font.fontstruct->ascent +
			theme->getWindowStyle().font.fontstruct->descent; 
	}

	geom_w += getBevelWidth()*2;
	geom_h += getBevelWidth()*2;

	Pixmap tmp = geom_pixmap;
	if (theme->getWindowStyle().l_focus.getTexture() & BImage::PARENTRELATIVE) {
		if (theme->getWindowStyle().t_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				theme->getWindowStyle().t_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				&theme->getWindowStyle().t_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				geom_window, geom_pixmap);
		}
	} else {
		if (theme->getWindowStyle().l_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				theme->getWindowStyle().l_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				&theme->getWindowStyle().l_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				geom_window, geom_pixmap);
		}
	}
	if (tmp) image_control->removeImage(tmp);

	XSetWindowBorderWidth(getBaseDisplay()->getXDisplay(), geom_window,
												theme->getBorderWidth());
	XSetWindowBorder(getBaseDisplay()->getXDisplay(), geom_window,
									 theme->getBorderColor().getPixel());

	workspacemenu->reconfigure();
	iconmenu->reconfigure();

	{
		int remember_sub = rootmenu->getCurrentSubmenu();
		InitMenu();
		raiseWindows(0, 0);
		rootmenu->reconfigure();
		rootmenu->drawSubmenu(remember_sub);
	}

	configmenu->reconfigure();

	toolbar->reconfigure();

#ifdef		SLIT
	slit->reconfigure();
#endif // SLIT

	Workspaces::iterator wit = workspacesList.begin();
	Workspaces::iterator wit_end = workspacesList.end();
	for (; wit != wit_end; ++wit) {
		(*wit)->reconfigure();
	}

	Icons::iterator iit = iconList.begin();
	Icons::iterator iit_end = iconList.end();
	for (; iit != iit_end; ++iit) {
		if ((*iit)->validateClient())
			(*iit)->reconfigure();
	}

	image_control->timeout();
}


void BScreen::rereadMenu(void) {
	InitMenu();
	raiseWindows(0, 0);

	rootmenu->reconfigure();
}


void BScreen::removeWorkspaceNames(void) {
	workspaceNames.erase(workspaceNames.begin(), workspaceNames.end());
}

void BScreen::updateWorkspaceNamesAtom(void) {

#ifdef GNOME	
	XTextProperty	text;
	int number_of_desks = workspaceNames.size();
	
	char s[1024];
	char *names[number_of_desks];		
	
	for (int i = 0; i < number_of_desks; i++) {		
		sprintf(s, "Desktop %i", i);
		names[i] = new char[strlen(s) + 1];
		strcpy(names[i], s);
	}
	
	if (XStringListToTextProperty(names, number_of_desks, &text)) {
		XSetTextProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
			 &text, getBaseDisplay()->getGnomeWorkspaceNamesAtom());
		XFree(text.value);
	}
	
	for (int i = 0; i < number_of_desks; i++)
		delete names[i];			

#endif

}

void BScreen::addIcon(FluxboxWindow *w) {
	if (! w) return;

	w->setWorkspace(-1);
	w->setWindowNumber(iconList.size());

	iconList.push_back(w);

	iconmenu->insert((const char **) w->getIconTitle());	
	iconmenu->update();
	toolbar->addIcon(w);
}


void BScreen::removeIcon(FluxboxWindow *w) {
	if (! w) return;

    std::remove(iconList.begin(), iconList.end(), w);

	iconmenu->remove(w->getWindowNumber());
	iconmenu->update();
	toolbar->delIcon(w);
	
    Icons::iterator it = iconList.begin();
	Icons::iterator it_end = iconList.end();
	for (int i = 0; it != it_end; ++it, ++i) {
		(*it)->setWindowNumber(i);
	}
}


FluxboxWindow *BScreen::getIcon(int index) {
	if (index >= 0 && index < iconList.size())
		return iconList[index];

	return (FluxboxWindow *) 0;
}


int BScreen::addWorkspace(void) {
	Workspace *wkspc = new Workspace(this, workspacesList.size());
	workspacesList.push_back(wkspc);<commit_msg>fixed iconbar bug<commit_after>// Screen.cc for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 <NAME> (<EMAIL>)
//
// Screen.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 <NAME> (<EMAIL>)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.	IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: Screen.cc,v 1.25 2002/02/17 19:19:05 fluxgen Exp $

// stupid macros needed to access some functions in version 2 of the GNU C
// library
#ifndef	 _GNU_SOURCE
#define	 _GNU_SOURCE
#endif // _GNU_SOURCE

#ifdef		HAVE_CONFIG_H
#	include "../config.h"
#endif // HAVE_CONFIG_H

#include "Screen.hh"

#include "i18n.hh"
#include "fluxbox.hh"
#include "Clientmenu.hh"
#include "Icon.hh"
#include "Image.hh"
#include "StringUtil.hh"

#ifdef		SLIT
#include "Slit.hh"
#endif // SLIT

#include "Rootmenu.hh"
#include "Toolbar.hh"
#include "Window.hh"
#include "Workspace.hh"
#include "Workspacemenu.hh"

#ifdef STDC_HEADERS
#	include <sys/types.h>
#endif // STDC_HEADERS

#ifdef HAVE_CTYPE_H
#	include <ctype.h>
#endif // HAVE_CTYPE_H

#ifdef HAVE_DIRENT_H
#	include <dirent.h>
#endif // HAVE_DIRENT_H

#ifdef HAVE_LOCALE_H
#	include <locale.h>
#endif // HAVE_LOCALE_H

#ifdef HAVE_UNISTD_H
#	include <sys/types.h>
#	include <unistd.h>
#endif // HAVE_UNISTD_H

#ifdef HAVE_SYS_STAT_H
#	include <sys/stat.h>
#endif // HAVE_SYS_STAT_H

#ifdef HAVE_STDARG_H
#	include <stdarg.h>
#endif // HAVE_STDARG_H

#ifndef  MAXPATHLEN
#define	 MAXPATHLEN 255
#endif // MAXPATHLEN

#ifndef	 FONT_ELEMENT_SIZE
#define	 FONT_ELEMENT_SIZE 50
#endif // FONT_ELEMENT_SIZE

#include <X11/Xatom.h>
#include <X11/keysym.h>

#include <iostream>
#include <memory>
#include <algorithm>

using namespace std;

static Bool running = True;

static int anotherWMRunning(Display *display, XErrorEvent *) {
	fprintf(stderr,
		I18n::instance()->
		getMessage(
#ifdef		NLS
			ScreenSet, ScreenAnotherWMRunning,
#else // !NLS
			0, 0,
#endif // NLS
			"BScreen::BScreen: an error occured while querying the X server.\n"
			"	another window manager already running on display %s.\n"),
			DisplayString(display));

	running = False;

	return(-1);
}

static int dcmp(const void *one, const void *two) {
	return (strcmp((*(char **) one), (*(char **) two)));
}

//---------- resource manipulators ---------
template<>
void Resource<Tab::Alignment>::
setFromString(const char *strval) {	
	m_value = Tab::getTabAlignmentNum(strval);
}

template<>
void Resource<Tab::Placement>::
setFromString(const char *strval) {	
	m_value = Tab::getTabPlacementNum(strval);
}

template<>
void Resource<Toolbar::Placement>::
setFromString(const char *strval) {
	if (strcasecmp(strval, "TopLeft")==0)
		m_value = Toolbar::TOPLEFT;
	else if (strcasecmp(strval, "BottomLeft")==0)
		m_value = Toolbar::BOTTOMLEFT;
	else if (strcasecmp(strval, "TopCenter")==0)
		m_value = Toolbar::TOPCENTER;
	else if (strcasecmp(strval, "BottomCenter")==0)
		m_value = Toolbar::BOTTOMCENTER;
	else if (strcasecmp(strval, "TopRight")==0)
		m_value = Toolbar::TOPRIGHT;
	else if (strcasecmp(strval, "BottomRight")==0)
		m_value = Toolbar::BOTTOMRIGHT;
	else
		setDefaultValue();
}

//--------- resource accessors --------------
template<>
string Resource<Tab::Alignment>::
getString() {
	return Tab::getTabAlignmentString(m_value);
}

template<>
string Resource<Tab::Placement>::
getString() {
	return Tab::getTabPlacementString(m_value);
}

template<>
string Resource<Toolbar::Placement>::
getString() {
	switch (m_value) {
		case Toolbar::TOPLEFT:
			return string("TopLeft");
			break;
		case Toolbar::BOTTOMLEFT:
			return string("BottomLeft");
			break;
		case Toolbar::TOPCENTER:
			return string("TopCenter");
			break;			
		case Toolbar::BOTTOMCENTER:
			return string("BottomCenter");
			break;
		case Toolbar::TOPRIGHT:
			return string("TopRight");
			break;
		case Toolbar::BOTTOMRIGHT:
			return string("BottomRight");
			break;
	}
	//default string
	return string("BottomCenter");
}


BScreen::ScreenResource::ScreenResource(ResourceManager &rm, 
	const std::string &scrname, const std::string &altscrname):
toolbar_on_top(rm, false, scrname+".toolbar.onTop", altscrname+".Toolbar.OnTop"),
toolbar_auto_hide(rm, false, scrname+".toolbar.autoHide", altscrname+".Toolbar.AutoHide"),
image_dither(rm, false, scrname+".imageDither", altscrname+".ImageDither"),
opaque_move(rm, false, "session.opaqueMove", "Session.OpaqueMove"),
full_max(rm, true, scrname+".fullMaximization", altscrname+".FullMaximization"),
max_over_slit(rm, true, scrname+".maxOverSlit",altscrname+".MaxOverSlit"),
tab_rotate_vertical(rm, true, scrname+".tab.rotatevertical", altscrname+".Tab.RotateVertical"),
sloppy_window_grouping(rm, true, scrname+".sloppywindowgrouping", altscrname+".SloppyWindowGrouping"),
focus_last(rm, true, scrname+".focusLastWindow", altscrname+".FocusLastWindow"),
focus_new(rm, true, scrname+".focusNewWindows", altscrname+".FocusNewWindows"),
rootcommand(rm, "", scrname+".rootCommand", altscrname+".RootCommand"),
workspaces(rm, 1, scrname+".workspaces", altscrname+".Workspaces"),
toolbar_width_percent(rm, 65, scrname+".toolbar.widthPercent", altscrname+".Toolbar.WidthPercent"),
edge_snap_threshold(rm, 0, scrname+".edgeSnapThreshold", altscrname+".EdgeSnapThreshold"),
tab_width(rm, 64, scrname+".tab.width", altscrname+".Tab.Width"),
tab_height(rm, 16, scrname+".tab.height", altscrname+".Tab.Height"),
tab_placement(rm, Tab::PTOP, scrname+".tab.placement", altscrname+".Tab.Placement"),
tab_alignment(rm, Tab::ALEFT, scrname+".tab.alignment", altscrname+".Tab.Alignment"),
toolbar_placement(rm, Toolbar::BOTTOMCENTER, scrname+".toolbar.placement", altscrname+".Toolbar.Placement")
{

};

BScreen::BScreen(ResourceManager &rm, Fluxbox *b, 
	const string &screenname, const string &altscreenname,
	int scrn) : ScreenInfo(b, scrn),
#ifdef GNOME
gnome_win(None),
#endif
theme(0),
resource(rm, screenname, altscreenname)
{
	fluxbox = b;

	event_mask = ColormapChangeMask | EnterWindowMask | PropertyChangeMask |
		SubstructureRedirectMask | KeyPressMask | KeyReleaseMask |
		ButtonPressMask | ButtonReleaseMask| SubstructureNotifyMask;

	XErrorHandler old = XSetErrorHandler((XErrorHandler) anotherWMRunning);
	XSelectInput(getBaseDisplay()->getXDisplay(), getRootWindow(), event_mask);
	XSync(getBaseDisplay()->getXDisplay(), False);
	XSetErrorHandler((XErrorHandler) old);

	managed = running;
	if (! managed)
		return;
	
	I18n *i18n = I18n::instance();
	
	fprintf(stderr,
		i18n->
		getMessage(
		#ifdef NLS
				ScreenSet, ScreenManagingScreen,
		#else // !NLS
				0, 0,
		#endif // NLS
				"BScreen::BScreen: managing screen %d "
				"using visual 0x%lx, depth %d\n"),
		getScreenNumber(), XVisualIDFromVisual(getVisual()),
		getDepth());

	rootmenu = 0;
		
	#ifdef HAVE_STRFTIME
	resource.strftime_format = 0;
	#endif // HAVE_STRFTIME

	#ifdef HAVE_GETPID
	pid_t bpid = getpid();

	XChangeProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
		fluxbox->getFluxboxPidAtom(), XA_CARDINAL,
		sizeof(pid_t) * 8, PropModeReplace,
		(unsigned char *) &bpid, 1);
	#endif // HAVE_GETPID


	XDefineCursor(getBaseDisplay()->getXDisplay(), getRootWindow(),
		fluxbox->getSessionCursor());

	image_control =
		new BImageControl(fluxbox, this, True, fluxbox->getColorsPerChannel(),
			fluxbox->getCacheLife(), fluxbox->getCacheMax());
	image_control->installRootColormap();
	root_colormap_installed = True;

	fluxbox->load_rc(this);

	image_control->setDither(*resource.image_dither);
	theme = new Theme(getBaseDisplay()->getXDisplay(), getRootWindow(), getColormap(), getScreenNumber(), 
			image_control, fluxbox->getStyleFilename(), getRootCommand().c_str());

	#ifdef GNOME
	initGnomeAtoms();
	#endif 

	#ifdef NEWWMSPEC
	Atom netwmsupported[] = {
//		getBaseDisplay()->getNETWMStateAtom(),
		getBaseDisplay()->getNETNumberOfDesktopsAtom(),
		getBaseDisplay()->getNETCurrentDesktopAtom(),
		getBaseDisplay()->getNETSupportingWMCheckAtom(),		
	};	

	XChangeProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
		getBaseDisplay()->getNETSupportedAtom(), XA_ATOM, 32, PropModeReplace,
		(unsigned char *)netwmsupported, (sizeof netwmsupported)/sizeof netwmsupported[0]);
	#endif //!NEWWMSPEC

	const char *s =	i18n->getMessage(
	#ifdef		NLS
		ScreenSet, ScreenPositionLength,
	#else // !NLS
		0, 0,
	#endif // NLS
		"0: 0000 x 0: 0000");
	
	int l = strlen(s);

	if (i18n->multibyte()) {
		XRectangle ink, logical;
		XmbTextExtents(theme->getWindowStyle().font.set, s, l, &ink, &logical);
		geom_w = logical.width;

		geom_h = theme->getWindowStyle().font.set_extents->max_ink_extent.height;
	} else {
		geom_h = theme->getWindowStyle().font.fontstruct->ascent +
			theme->getWindowStyle().font.fontstruct->descent;

		geom_w = XTextWidth(theme->getWindowStyle().font.fontstruct, s, l);
	}

	geom_w += getBevelWidth()*2;
	geom_h += getBevelWidth()*2;

	XSetWindowAttributes attrib;
	unsigned long mask = CWBorderPixel | CWColormap | CWSaveUnder;
	attrib.border_pixel = getBorderColor()->getPixel();
	attrib.colormap = getColormap();
	attrib.save_under = True;

	geom_window =
		XCreateWindow(getBaseDisplay()->getXDisplay(), getRootWindow(),
			0, 0, geom_w, geom_h, theme->getBorderWidth(), getDepth(),
			InputOutput, getVisual(), mask, &attrib);
	geom_visible = False;

	if (theme->getWindowStyle().l_focus.getTexture() & BImage::PARENTRELATIVE) {
		if (theme->getWindowStyle().t_focus.getTexture() ==
			(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				 theme->getWindowStyle().t_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				 &theme->getWindowStyle().t_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				 geom_window, geom_pixmap);
		}
	} else {
		if (theme->getWindowStyle().l_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				 theme->getWindowStyle().l_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				 &theme->getWindowStyle().l_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				 geom_window, geom_pixmap);
		}
	}

	workspacemenu = new Workspacemenu(this);
	iconmenu = new Iconmenu(this);	
	configmenu = new Configmenu(this);

	Workspace *wkspc = (Workspace *) 0;
	if (*resource.workspaces != 0) {
		for (int i = 0; i < *resource.workspaces; ++i) {
			wkspc = new Workspace(this, workspacesList.size());
			workspacesList.push_back(wkspc);
			workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
		}
	} else {
		wkspc = new Workspace(this, workspacesList.size());
		workspacesList.push_back(wkspc);
		workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
	}

	workspacemenu->insert(i18n->
		getMessage(
		#ifdef NLS
			 IconSet, IconIcons,
		#else // !NLS
			 0, 0,
		#endif // NLS
			 "Icons"),
			iconmenu);
	workspacemenu->update();

	current_workspace = workspacesList.front();
	workspacemenu->setItemSelected(2, True);

	toolbar = new Toolbar(this);

	#ifdef SLIT
	slit = new Slit(this);
	#endif // SLIT

	InitMenu();

	raiseWindows(0, 0);
	rootmenu->update();

	changeWorkspaceID(0);
	updateNetizenWorkspaceCount();
	
	int i;
	unsigned int nchild;
	Window r, p, *children;
	XQueryTree(getBaseDisplay()->getXDisplay(), getRootWindow(), &r, &p,
			 &children, &nchild);

	// preen the window list of all icon windows... for better dockapp support
	for (i = 0; i < (int) nchild; i++) {
		
		if (children[i] == None) continue;

		XWMHints *wmhints = XGetWMHints(getBaseDisplay()->getXDisplay(),
			children[i]);

		if (wmhints) {
			if ((wmhints->flags & IconWindowHint) &&
					(wmhints->icon_window != children[i]))
				for (int j = 0; j < (int) nchild; j++) {
					if (children[j] == wmhints->icon_window) {
						children[j] = None;
						break;
					}
				}
			XFree(wmhints);
		}
	}

	// manage shown windows
	for (i = 0; i < (int) nchild; ++i) {
		if (children[i] == None || (! fluxbox->validateWindow(children[i])))
			continue;

		XWindowAttributes attrib;
		if (XGetWindowAttributes(getBaseDisplay()->getXDisplay(), children[i],
				&attrib)) {
			if (attrib.override_redirect) 
				continue;

			if (attrib.map_state != IsUnmapped) {
				
				FluxboxWindow *win = new FluxboxWindow(children[i], this);
				if (!win->isManaged()) {
					delete win;
					win = 0;
				}
				
				if (win) {
					XMapRequestEvent mre;
					mre.window = children[i];
					win->restoreAttributes();
					win->mapRequestEvent(&mre);
				}
			}
		}
	}

	if (! resource.sloppy_focus)
		XSetInputFocus(getBaseDisplay()->getXDisplay(), toolbar->getWindowID(),
			RevertToParent, CurrentTime);

	XFree(children);
	XFlush(getBaseDisplay()->getXDisplay());
	
}

namespace {
    template<typename T>
    void delete_obj(T * obj) {
        delete obj;
    }
}

BScreen::~BScreen(void) {
	#ifdef GNOME
	XDestroyWindow(getBaseDisplay()->getXDisplay(), gnome_win);
	#endif
	if (! managed) return;

	if (geom_pixmap != None)
		image_control->removeImage(geom_pixmap);

	if (geom_window != None)
		XDestroyWindow(getBaseDisplay()->getXDisplay(), geom_window);

	removeWorkspaceNames();

    std::for_each(
        workspacesList.begin(),
        workspacesList.end(),
        delete_obj<Workspace>);

    // don't delete items in the rootmenuList?

    std::for_each(
        iconList.begin(),
        iconList.end(),
        delete_obj<FluxboxWindow>);

    std::for_each(
        netizenList.begin(),
        netizenList.end(),
        delete_obj<Netizen>);

#ifdef		HAVE_STRFTIME
	if (resource.strftime_format)
		delete [] resource.strftime_format;
#endif // HAVE_STRFTIME

	delete rootmenu;
	delete workspacemenu;
	delete iconmenu;
	delete configmenu;

#ifdef		SLIT
	delete slit;
#endif // SLIT

	delete toolbar;
	delete image_control;

	delete theme;

}

void BScreen::reconfigure(void) {
	#ifdef DEBUG
	cerr<<__FILE__<<"("<<__LINE__<<"): BScreen::reconfigure"<<endl;
	#endif
	Fluxbox::instance()->loadRootCommand(this);
	theme->setRootCommand(getRootCommand());

	theme->load(fluxbox->getStyleFilename());
	theme->reconfigure();
	I18n *i18n = I18n::instance();

	const char *s = i18n->getMessage(
#ifdef		NLS
			ScreenSet, ScreenPositionLength,
#else // !NLS
			0, 0,
#endif // NLS
			"0: 0000 x 0: 0000");
	int l = strlen(s);

	if (i18n->multibyte()) {
		XRectangle ink, logical;
		XmbTextExtents(theme->getWindowStyle().font.set, s, l, &ink, &logical);
		geom_w = logical.width;

		geom_h = theme->getWindowStyle().font.set_extents->max_ink_extent.height;
	} else {
		geom_w = XTextWidth(theme->getWindowStyle().font.fontstruct, s, l);

		geom_h = theme->getWindowStyle().font.fontstruct->ascent +
			theme->getWindowStyle().font.fontstruct->descent; 
	}

	geom_w += getBevelWidth()*2;
	geom_h += getBevelWidth()*2;

	Pixmap tmp = geom_pixmap;
	if (theme->getWindowStyle().l_focus.getTexture() & BImage::PARENTRELATIVE) {
		if (theme->getWindowStyle().t_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				theme->getWindowStyle().t_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				&theme->getWindowStyle().t_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				geom_window, geom_pixmap);
		}
	} else {
		if (theme->getWindowStyle().l_focus.getTexture() ==
				(BImage::FLAT | BImage::SOLID)) {
			geom_pixmap = None;
			XSetWindowBackground(getBaseDisplay()->getXDisplay(), geom_window,
				theme->getWindowStyle().l_focus.getColor()->getPixel());
		} else {
			geom_pixmap = image_control->renderImage(geom_w, geom_h,
				&theme->getWindowStyle().l_focus);
			XSetWindowBackgroundPixmap(getBaseDisplay()->getXDisplay(),
				geom_window, geom_pixmap);
		}
	}
	if (tmp) image_control->removeImage(tmp);

	XSetWindowBorderWidth(getBaseDisplay()->getXDisplay(), geom_window,
												theme->getBorderWidth());
	XSetWindowBorder(getBaseDisplay()->getXDisplay(), geom_window,
									 theme->getBorderColor().getPixel());

	workspacemenu->reconfigure();
	iconmenu->reconfigure();

	{
		int remember_sub = rootmenu->getCurrentSubmenu();
		InitMenu();
		raiseWindows(0, 0);
		rootmenu->reconfigure();
		rootmenu->drawSubmenu(remember_sub);
	}

	configmenu->reconfigure();

	toolbar->reconfigure();

#ifdef		SLIT
	slit->reconfigure();
#endif // SLIT

	Workspaces::iterator wit = workspacesList.begin();
	Workspaces::iterator wit_end = workspacesList.end();
	for (; wit != wit_end; ++wit) {
		(*wit)->reconfigure();
	}

	Icons::iterator iit = iconList.begin();
	Icons::iterator iit_end = iconList.end();
	for (; iit != iit_end; ++iit) {
		if ((*iit)->validateClient())
			(*iit)->reconfigure();
	}

	image_control->timeout();
}


void BScreen::rereadMenu(void) {
	InitMenu();
	raiseWindows(0, 0);

	rootmenu->reconfigure();
}


void BScreen::removeWorkspaceNames(void) {
	workspaceNames.erase(workspaceNames.begin(), workspaceNames.end());
}

void BScreen::updateWorkspaceNamesAtom(void) {

#ifdef GNOME	
	XTextProperty	text;
	int number_of_desks = workspaceNames.size();
	
	char s[1024];
	char *names[number_of_desks];		
	
	for (int i = 0; i < number_of_desks; i++) {		
		sprintf(s, "Desktop %i", i);
		names[i] = new char[strlen(s) + 1];
		strcpy(names[i], s);
	}
	
	if (XStringListToTextProperty(names, number_of_desks, &text)) {
		XSetTextProperty(getBaseDisplay()->getXDisplay(), getRootWindow(),
			 &text, getBaseDisplay()->getGnomeWorkspaceNamesAtom());
		XFree(text.value);
	}
	
	for (int i = 0; i < number_of_desks; i++)
		delete names[i];			

#endif

}

void BScreen::addIcon(FluxboxWindow *w) {
	if (! w) return;

	w->setWorkspace(-1);
	w->setWindowNumber(iconList.size());

	iconList.push_back(w);

	iconmenu->insert((const char **) w->getIconTitle());	
	iconmenu->update();
	toolbar->addIcon(w);
}


void BScreen::removeIcon(FluxboxWindow *w) {
	if (! w) return;
	{
    Icons::iterator it = iconList.begin();
	Icons::iterator it_end = iconList.end();
	for (; it != it_end; ++it) {
		if (*it == w) {
			iconList.erase(it);
			break;
		}
	}
	}
	//std::remove(iconList.begin(), iconList.end(), w);
	
	iconmenu->remove(w->getWindowNumber());
	iconmenu->update();
	toolbar->delIcon(w);
	
    Icons::iterator it = iconList.begin();
	Icons::iterator it_end = iconList.end();
	for (int i = 0; it != it_end; ++it, ++i) {
		(*it)->setWindowNumber(i);
	}
}


FluxboxWindow *BScreen::getIcon(int index) {
	if (index >= 0 && index < iconList.size())
		return iconList[index];

	return (FluxboxWindow *) 0;
}


int BScreen::addWorkspace(void) {
	Workspace *wkspc = new Workspace(this, workspacesList.size());
	workspacesList.push_back(wkspc);
{'fraction_non_alphanumeric': 0.1538971300402712, 'fraction_numerical': 0.008105214864658204, 'mean_word_length': 4.857718722006569, 'pattern_counts': {'":': 0, '<': 103, '<?xml version=': 0, '>': 347, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1145296', 'n_tokens_mistral': 15094, 'n_tokens_neox': 13627, 'n_words': 2784}