code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/***************************************************************************** * Web3d.org Copyright (c) 2001 * Java Source * * This source is licensed under the GNU LGPL v2.1 * Please read http://www.gnu.org/copyleft/lgpl.html for more information * * This software comes with the standard NO WARRANTY disclaimer for any * purpose. Use it at your own risk. If there's a problem you get to fix it. * ****************************************************************************/ package org.web3d.vrml.renderer.ogl.nodes; // External imports import javax.vecmath.*; // Local imports import org.web3d.vrml.renderer.common.nodes.AreaListener; /** * The listener interface for receiving notice of the viewpoint on entry or * exit from an area. * <p> * Each method receives both the user's current position and orientation in * V-world coordinates but also the transform of the object that was picked * and representing this interface. The idea of this is to save internal calls * to getLocalToVWorld() and the extra capability bits required for this. The * transform is available from the initial pick SceneGraphPath anyway, so this * comes for free and leads to better performance. In addition, it saves * needing to pass in a scene graph path for dealing with the * getLocalToVWorld() case when we are under a SharedGroup. * * @author Alan Hudson, Justin Couch * @version $Revision: 1.3 $ */ public interface OGLAreaListener extends AreaListener { /** * Invoked when the user enters an area. * * @param position The new position of the user * @param orientation The orientation of the user there * @param localPosition The vworld transform object for the class * that implemented this listener */ public void areaEntry(Point3f position, Vector3f orientation, Matrix4f vpMatrix, Matrix4f localPosition); /** * Notification that the user is still in the area, but that the * viewer reference point has changed. * * @param position The new position of the user * @param orientation The orientation of the user there * @param localPosition The vworld transform object for the class * that implemented this listener */ public void userPositionChanged(Point3f position, Vector3f orientation, Matrix4f vpMatrix, Matrix4f localPosition); /** * Invoked when the tracked object exits on area. */ public void areaExit(); }
Norkart/NK-VirtualGlobe
Xj3D/src/java/org/web3d/vrml/renderer/ogl/nodes/OGLAreaListener.java
Java
gpl-2.0
2,694
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file departures_gui.cpp Scheduled departures from a station. */ #include "stdafx.h" #include "debug.h" #include "gui.h" #include "textbuf_gui.h" #include "strings_func.h" #include "window_func.h" #include "vehicle_func.h" #include "string_func.h" #include "window_gui.h" #include "timetable.h" #include "vehiclelist.h" #include "company_base.h" #include "date_func.h" #include "departures_gui.h" #include "station_base.h" #include "vehicle_gui_base.h" #include "vehicle_base.h" #include "vehicle_gui.h" #include "order_base.h" #include "settings_type.h" #include "core/smallvec_type.hpp" #include "date_type.h" #include "company_type.h" #include "departures_func.h" #include "cargotype.h" #include "table/sprites.h" #include "table/strings.h" static const NWidgetPart _nested_departures_list[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_CLOSEBOX, COLOUR_GREY), NWidget(WWT_CAPTION, COLOUR_GREY, WID_DB_CAPTION), SetDataTip(STR_DEPARTURES_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), NWidget(WWT_SHADEBOX, COLOUR_GREY), NWidget(WWT_STICKYBOX, COLOUR_GREY), EndContainer(), NWidget(NWID_HORIZONTAL), NWidget(WWT_MATRIX, COLOUR_GREY, WID_DB_LIST), SetMinimalSize(0, 0), SetFill(1, 0), SetResize(1, 1), NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_DB_SCROLLBAR), EndContainer(), NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_GREY), SetMinimalSize(0, 12), SetResize(1, 0), SetFill(1, 1), EndContainer(), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_DEPS), SetMinimalSize(6, 12), SetFill(0, 1), SetDataTip(STR_DEPARTURES_DEPARTURES, STR_DEPARTURES_DEPARTURES_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_ARRS), SetMinimalSize(6, 12), SetFill(0, 1), SetDataTip(STR_DEPARTURES_ARRIVALS, STR_DEPARTURES_ARRIVALS_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_VIA), SetMinimalSize(11, 12), SetFill(0, 1), SetDataTip(STR_DEPARTURES_VIA_BUTTON, STR_DEPARTURES_VIA_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_TRAINS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_TRAIN, STR_STATION_VIEW_SCHEDULED_TRAINS_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_ROADVEHS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_LORRY, STR_STATION_VIEW_SCHEDULED_ROAD_VEHICLES_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_SHIPS), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_SHIP, STR_STATION_VIEW_SCHEDULED_SHIPS_TOOLTIP), NWidget(WWT_TEXTBTN, COLOUR_GREY, WID_DB_SHOW_PLANES), SetMinimalSize(14, 12), SetFill(0, 1), SetDataTip(STR_PLANE, STR_STATION_VIEW_SCHEDULED_AIRCRAFT_TOOLTIP), NWidget(WWT_RESIZEBOX, COLOUR_GREY), EndContainer(), }; static WindowDesc _departures_desc( WDP_AUTO, 260, 246, WC_DEPARTURES_BOARD, WC_NONE, 0, _nested_departures_list, lengthof(_nested_departures_list) ); static uint cached_date_width = 0; ///< The cached maximum width required to display a date. static uint cached_status_width = 0; ///< The cached maximum width required to show the status field. static uint cached_date_arrow_width = 0; ///< The cached width of the red/green arrows that may be displayed alongside times. static bool cached_date_display_method; ///< Whether the above cached values refers to original (d,m,y) dates or the 24h clock. static bool cached_arr_dep_display_method; ///< Whether to show departures and arrivals on a single line. template<bool Twaypoint = false> struct DeparturesWindow : public Window { protected: StationID station; ///< The station whose departures we're showing. DepartureList *departures; ///< The current list of departures from this station. DepartureList *arrivals; ///< The current list of arrivals from this station. uint entry_height; ///< The height of an entry in the departures list. uint tick_count; ///< The number of ticks that have elapsed since the window was created. Used for scrolling text. int calc_tick_countdown; ///< The number of ticks to wait until recomputing the departure list. Signed in case it goes below zero. bool show_types[4]; ///< The vehicle types to show in the departure list. bool departure_types[3]; ///< The types of departure to show in the departure list. uint min_width; ///< The minimum width of this window. Scrollbar *vscroll; virtual uint GetMinWidth() const; static void RecomputeDateWidth(); virtual void DrawDeparturesListItems(const Rect &r) const; void DeleteDeparturesList(DepartureList* list); public: DeparturesWindow(const WindowDesc *desc, WindowNumber window_number) : Window(), station(window_number), departures(new DepartureList()), arrivals(new DepartureList()), entry_height(1 + FONT_HEIGHT_NORMAL + 1 + (_settings_client.gui.departure_larger_font ? FONT_HEIGHT_NORMAL : FONT_HEIGHT_SMALL) + 1 + 1), tick_count(0), calc_tick_countdown(0), min_width(400) { this->CreateNestedTree(desc); this->vscroll = this->GetScrollbar(WID_DB_SCROLLBAR); this->FinishInitNested(desc, window_number); /* By default, only show departures. */ departure_types[0] = true; departure_types[1] = false; departure_types[2] = false; this->LowerWidget(WID_DB_SHOW_DEPS); this->RaiseWidget(WID_DB_SHOW_ARRS); this->RaiseWidget(WID_DB_SHOW_VIA); for (uint i = 0; i < 4; ++i) { show_types[i] = true; this->LowerWidget(WID_DB_SHOW_TRAINS + i); } if (Twaypoint) { this->GetWidget<NWidgetCore>(WID_DB_CAPTION)->SetDataTip(STR_DEPARTURES_CAPTION_WAYPOINT, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS); for (uint i = 0; i < 4; ++i) { this->DisableWidget(WID_DB_SHOW_TRAINS + i); } this->DisableWidget(WID_DB_SHOW_ARRS); this->DisableWidget(WID_DB_SHOW_DEPS); this->DisableWidget(WID_DB_SHOW_VIA); departure_types[2] = true; this->LowerWidget(WID_DB_SHOW_VIA); } } virtual ~DeparturesWindow() { this->DeleteDeparturesList(departures); this->DeleteDeparturesList(this->arrivals); } virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) { switch (widget) { case WID_DB_LIST: resize->height = DeparturesWindow::entry_height; size->height = 2 * resize->height; break; } } virtual void SetStringParameters(int widget) const { if (widget == WID_DB_CAPTION) { const Station *st = Station::Get(this->station); SetDParam(0, st->index); } } virtual void OnClick(Point pt, int widget, int click_count) { switch (widget) { case WID_DB_SHOW_TRAINS: // Show trains to this station case WID_DB_SHOW_ROADVEHS: // Show road vehicles to this station case WID_DB_SHOW_SHIPS: // Show ships to this station case WID_DB_SHOW_PLANES: // Show aircraft to this station this->show_types[widget - WID_DB_SHOW_TRAINS] = !this->show_types[widget - WID_DB_SHOW_TRAINS]; if (this->show_types[widget - WID_DB_SHOW_TRAINS]) { this->LowerWidget(widget); } else { this->RaiseWidget(widget); } /* We need to recompute the departures list. */ this->calc_tick_countdown = 0; /* We need to redraw the button that was pressed. */ this->SetWidgetDirty(widget); break; case WID_DB_SHOW_DEPS: case WID_DB_SHOW_ARRS: if (_settings_client.gui.departure_show_both) break; /* FALL THROUGH */ case WID_DB_SHOW_VIA: this->departure_types[widget - WID_DB_SHOW_DEPS] = !this->departure_types[widget - WID_DB_SHOW_DEPS]; if (this->departure_types[widget - WID_DB_SHOW_DEPS]) { this->LowerWidget(widget); } else { this->RaiseWidget(widget); } if (!this->departure_types[0]) { this->RaiseWidget(WID_DB_SHOW_VIA); this->DisableWidget(WID_DB_SHOW_VIA); } else { this->EnableWidget(WID_DB_SHOW_VIA); if (this->departure_types[2]) { this->LowerWidget(WID_DB_SHOW_VIA); } } /* We need to recompute the departures list. */ this->calc_tick_countdown = 0; /* We need to redraw the button that was pressed. */ this->SetWidgetDirty(widget); break; case WID_DB_LIST: // Matrix to show departures /* We need to find the departure corresponding to where the user clicked. */ uint32 id_v = (pt.y - this->GetWidget<NWidgetBase>(WID_DB_LIST)->pos_y) / this->entry_height; if (id_v >= this->vscroll->GetCapacity()) return; // click out of bounds id_v += this->vscroll->GetPosition(); if (id_v >= (this->departures->Length() + this->arrivals->Length())) return; // click out of list bound uint departure = 0; uint arrival = 0; /* Draw each departure. */ for (uint i = 0; i <= id_v; ++i) { const Departure *d; if (arrival == this->arrivals->Length()) { d = (*(this->departures))[departure++]; } else if (departure == this->departures->Length()) { d = (*(this->arrivals))[arrival++]; } else { d = (*(this->departures))[departure]; const Departure *a = (*(this->arrivals))[arrival]; if (a->scheduled_date < d->scheduled_date) { d = a; arrival++; } else { departure++; } } if (i == id_v) { ShowVehicleViewWindow(d->vehicle); break; } } break; } } virtual void OnTick() { if (_pause_mode == PM_UNPAUSED) { this->tick_count += 1; this->calc_tick_countdown -= 1; } /* Recompute the minimum date display width if the cached one is no longer valid. */ if (cached_date_width == 0 || _settings_client.gui.time_in_minutes != cached_date_display_method || _settings_client.gui.departure_show_both != cached_arr_dep_display_method) { this->RecomputeDateWidth(); } /* We need to redraw the scrolling text in its new position. */ this->SetWidgetDirty(WID_DB_LIST); /* Recompute the list of departures if we're due to. */ if (this->calc_tick_countdown <= 0) { this->calc_tick_countdown = _settings_client.gui.departure_calc_frequency; this->DeleteDeparturesList(this->departures); this->DeleteDeparturesList(this->arrivals); //arr/dep csere // this->departures = (this->departure_types[0] ? MakeDepartureList(this->station, this->show_types, D_DEPARTURE, Twaypoint || this->departure_types[2]) : new DepartureList()); // this->arrivals = (this->departure_types[1] && !_settings_client.gui.departure_show_both ? MakeDepartureList(this->station, this->show_types, D_ARRIVAL ) : new DepartureList()); this->departures = (this->departure_types[0] ? MakeDepartureList(this->station, this->show_types, D_ARRIVAL, Twaypoint || this->departure_types[2]) : new DepartureList()); this->arrivals = (this->departure_types[1] && !_settings_client.gui.departure_show_both ? MakeDepartureList(this->station, this->show_types, D_DEPARTURE ) : new DepartureList()); this->SetWidgetDirty(WID_DB_LIST); } uint new_width = this->GetMinWidth(); if (new_width != this->min_width) { NWidgetCore *n = this->GetWidget<NWidgetCore>(WID_DB_LIST); n->SetMinimalSize(new_width, 0); this->ReInit(); this->min_width = new_width; } uint new_height = 1 + FONT_HEIGHT_NORMAL + 1 + (_settings_client.gui.departure_larger_font ? FONT_HEIGHT_NORMAL : FONT_HEIGHT_SMALL) + 1 + 1; if (new_height != this->entry_height) { this->entry_height = new_height; this->SetWidgetDirty(WID_DB_LIST); this->ReInit(); } } virtual void OnPaint() { if (Twaypoint || _settings_client.gui.departure_show_both) { this->DisableWidget(WID_DB_SHOW_ARRS); this->DisableWidget(WID_DB_SHOW_DEPS); } else { this->EnableWidget(WID_DB_SHOW_ARRS); this->EnableWidget(WID_DB_SHOW_DEPS); } this->vscroll->SetCount(min(_settings_client.gui.max_departures, this->departures->Length() + this->arrivals->Length())); this->DrawWidgets(); } virtual void DrawWidget(const Rect &r, int widget) const { switch (widget) { case WID_DB_LIST: this->DrawDeparturesListItems(r); break; } } virtual void OnResize() { this->vscroll->SetCapacityFromWidget(this, WID_DB_LIST); this->GetWidget<NWidgetCore>(WID_DB_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START); } }; /** * Shows a window of scheduled departures for a station. * @param station the station to show a departures window for */ void ShowStationDepartures(StationID station) { AllocateWindowDescFront<DeparturesWindow<> >(&_departures_desc, station); } /** * Shows a window of scheduled departures for a station. * @param station the station to show a departures window for */ void ShowWaypointDepartures(StationID waypoint) { AllocateWindowDescFront<DeparturesWindow<true> >(&_departures_desc, waypoint); } template<bool Twaypoint> void DeparturesWindow<Twaypoint>::RecomputeDateWidth() { cached_date_width = 0; cached_status_width = 0; cached_date_display_method = _settings_client.gui.time_in_minutes; cached_arr_dep_display_method = _settings_client.gui.departure_show_both; cached_status_width = max((GetStringBoundingBox(STR_DEPARTURES_ON_TIME)).width, cached_status_width); cached_status_width = max((GetStringBoundingBox(STR_DEPARTURES_DELAYED)).width, cached_status_width); cached_status_width = max((GetStringBoundingBox(STR_DEPARTURES_CANCELLED)).width, cached_status_width); uint interval = cached_date_display_method ? _settings_client.gui.ticks_per_minute : DAY_TICKS; uint count = cached_date_display_method ? 24*60 : 365; for (uint i = 0; i < count; ++i) { SetDParam(0, INT_MAX - (i*interval)); SetDParam(1, INT_MAX - (i*interval)); cached_date_width = max(GetStringBoundingBox(cached_arr_dep_display_method ? STR_DEPARTURES_TIME_BOTH : STR_DEPARTURES_TIME_DEP).width, cached_date_width); cached_status_width = max((GetStringBoundingBox(STR_DEPARTURES_EXPECTED)).width, cached_status_width); } SetDParam(0, 0); cached_date_arrow_width = GetStringBoundingBox(STR_DEPARTURES_TIME_DEP).width - GetStringBoundingBox(STR_DEPARTURES_TIME).width; if (!_settings_client.gui.departure_show_both) { cached_date_width -= cached_date_arrow_width; } } template<bool Twaypoint> uint DeparturesWindow<Twaypoint>::GetMinWidth() const { uint result = 0; /* Time */ result = cached_date_width; /* Vehicle type icon */ result += _settings_client.gui.departure_show_vehicle_type ? (GetStringBoundingBox(STR_DEPARTURES_TYPE_PLANE)).width : 0; /* Status */ result += cached_status_width; /* Find the maximum company name width. */ int toc_width = 0; /* Find the maximum company name width. */ int group_width = 0; /* Find the maximum vehicle name width. */ int veh_width = 0; if (_settings_client.gui.departure_show_vehicle || _settings_client.gui.departure_show_company || _settings_client.gui.departure_show_group) { for (uint i = 0; i < 4; ++i) { VehicleList vehicles; /* MAX_COMPANIES is probably the wrong thing to put here, but it works. GenerateVehicleSortList doesn't check the company when the type of list is VL_STATION_LIST (r20801). */ if (!GenerateVehicleSortList(&vehicles, VehicleListIdentifier(VL_STATION_LIST, (VehicleType)(VEH_TRAIN + i), MAX_COMPANIES, station).Pack())) { /* Something went wrong: panic! */ continue; } for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) { SetDParam(0, (uint64)((*v)->index)); int width = (GetStringBoundingBox(STR_DEPARTURES_VEH)).width; if (_settings_client.gui.departure_show_vehicle && width > veh_width) veh_width = width; if ((*v)->group_id != INVALID_GROUP && (*v)->group_id != DEFAULT_GROUP) { SetDParam(0, (uint64)((*v)->group_id)); width = (GetStringBoundingBox(STR_DEPARTURES_GROUP)).width; if (_settings_client.gui.departure_show_group && width > group_width) group_width = width; } SetDParam(0, (uint64)((*v)->owner)); width = (GetStringBoundingBox(STR_DEPARTURES_TOC)).width; if (_settings_client.gui.departure_show_company && width > toc_width) toc_width = width; } } } result += toc_width + veh_width + group_width; return result + 140; } /** * Deletes this window's departure list. */ template<bool Twaypoint> void DeparturesWindow<Twaypoint>::DeleteDeparturesList(DepartureList *list) { /* SmallVector uses free rather than delete on its contents (which doesn't invoke the destructor), so we need to delete each departure manually. */ for (uint i = 0; i < list->Length(); ++i) { Departure **d = list->Get(i); delete *d; /* Make sure a double free doesn't happen. */ *d = NULL; } list->Reset(); delete list; list = NULL; } /** * Draws a list of departures. */ template<bool Twaypoint> void DeparturesWindow<Twaypoint>::DrawDeparturesListItems(const Rect &r) const { int left = r.left + WD_MATRIX_LEFT; int right = r.right - WD_MATRIX_RIGHT; bool rtl = _current_text_dir == TD_RTL; bool ltr = !rtl; int text_offset = WD_FRAMERECT_RIGHT; int text_left = left + (rtl ? 0 : text_offset); int text_right = right - (rtl ? text_offset : 0); int y = r.top + 1; uint max_departures = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->departures->Length() + this->arrivals->Length()); if (max_departures > _settings_client.gui.max_departures) { max_departures = _settings_client.gui.max_departures; } byte small_font_size = _settings_client.gui.departure_larger_font ? FONT_HEIGHT_NORMAL : FONT_HEIGHT_SMALL; /* Draw the black background. */ GfxFillRect(r.left + 1, r.top, r.right - 1, r.bottom, PC_BLACK); /* Nothing selected? Then display the information text. */ bool none_selected[2] = {true, true}; for (uint i = 0; i < 4; ++i) { if (this->show_types[i]) { none_selected[0] = false; break; } } for (uint i = 0; i < 2; ++i) { if (this->departure_types[i]) { none_selected[1] = false; break; } } if (none_selected[0] || none_selected[1]) { DrawString(text_left, text_right, y + 1, STR_DEPARTURES_NONE_SELECTED); return; } /* No scheduled departures? Then display the information text. */ if (max_departures == 0) { DrawString(text_left, text_right, y + 1, STR_DEPARTURES_EMPTY); return; } /* Find the maximum possible width of the departure time and "Expt <time>" fields. */ int time_width = cached_date_width; if (!_settings_client.gui.departure_show_both) { time_width += (departure_types[0] && departure_types[1] ? cached_date_arrow_width : 0); } /* Vehicle type icon */ int type_width = _settings_client.gui.departure_show_vehicle_type ? (GetStringBoundingBox(STR_DEPARTURES_TYPE_PLANE)).width : 0; /* Find the maximum width of the status field */ int status_width = cached_status_width; /* Find the width of the "Calling at:" field. */ int calling_at_width = (GetStringBoundingBox(_settings_client.gui.departure_larger_font ? STR_DEPARTURES_CALLING_AT_LARGE : STR_DEPARTURES_CALLING_AT)).width; /* Find the maximum company name width. */ int toc_width = 0; /* Find the maximum group name width. */ int group_width = 0; /* Find the maximum vehicle name width. */ int veh_width = 0; if (_settings_client.gui.departure_show_vehicle || _settings_client.gui.departure_show_company || _settings_client.gui.departure_show_group) { for (uint i = 0; i < 4; ++i) { VehicleList vehicles; /* MAX_COMPANIES is probably the wrong thing to put here, but it works. GenerateVehicleSortList doesn't check the company when the type of list is VL_STATION_LIST (r20801). */ if (!GenerateVehicleSortList(&vehicles, VehicleListIdentifier(VL_STATION_LIST, (VehicleType)(VEH_TRAIN + i), MAX_COMPANIES, station).Pack())) { /* Something went wrong: panic! */ continue; } for (const Vehicle **v = vehicles.Begin(); v != vehicles.End(); v++) { SetDParam(0, (uint64)((*v)->index)); int width = (GetStringBoundingBox(STR_DEPARTURES_VEH)).width; if (_settings_client.gui.departure_show_vehicle && width > veh_width) veh_width = width; if ((*v)->group_id != INVALID_GROUP && (*v)->group_id != DEFAULT_GROUP) { SetDParam(0, (uint64)((*v)->group_id)); width = (GetStringBoundingBox(STR_DEPARTURES_GROUP)).width; if (_settings_client.gui.departure_show_group && width > group_width) group_width = width; } SetDParam(0, (uint64)((*v)->owner)); width = (GetStringBoundingBox(STR_DEPARTURES_TOC)).width; if (_settings_client.gui.departure_show_company && width > toc_width) toc_width = width; } } } uint departure = 0; uint arrival = 0; /* Draw each departure. */ for (uint i = 0; i < max_departures; ++i) { const Departure *d; if (arrival == this->arrivals->Length()) { d = (*(this->departures))[departure++]; } else if (departure == this->departures->Length()) { d = (*(this->arrivals))[arrival++]; } else { d = (*(this->departures))[departure]; const Departure *a = (*(this->arrivals))[arrival]; if (a->scheduled_date < d->scheduled_date) { d = a; arrival++; } else { departure++; } } if (i < this->vscroll->GetPosition()) { continue; } /* If for some reason the departure is too far in the future or is at a negative time, skip it. */ if ((d->scheduled_date / DAY_TICKS) > (_date + _settings_client.gui.max_departure_time) || d->scheduled_date < 0) { continue; } if (d->terminus == INVALID_STATION) continue; StringID time_str = (departure_types[0] && departure_types[1]) ? (d->type == D_DEPARTURE ? STR_DEPARTURES_TIME_DEP : STR_DEPARTURES_TIME_ARR) : STR_DEPARTURES_TIME; if (_settings_client.gui.departure_show_both) time_str = STR_DEPARTURES_TIME_BOTH; /* Time */ SetDParam(0, d->scheduled_date); SetDParam(1, d->scheduled_date - d->order->wait_time); ltr ? DrawString( text_left, text_left + time_width, y + 1, time_str) : DrawString(text_right - time_width, text_right, y + 1, time_str); /* Vehicle type icon, with thanks to sph */ if (_settings_client.gui.departure_show_vehicle_type) { StringID type = STR_DEPARTURES_TYPE_TRAIN; int offset = (_settings_client.gui.departure_show_vehicle_color ? 1 : 0); switch (d->vehicle->type) { case VEH_TRAIN: type = STR_DEPARTURES_TYPE_TRAIN; break; case VEH_ROAD: type = IsCargoInClass(d->vehicle->cargo_type, CC_PASSENGERS) ? STR_DEPARTURES_TYPE_BUS : STR_DEPARTURES_TYPE_LORRY; break; case VEH_SHIP: type = STR_DEPARTURES_TYPE_SHIP; break; case VEH_AIRCRAFT: type = STR_DEPARTURES_TYPE_PLANE; break; default: break; } type += offset; DrawString(text_left + time_width + 3, text_left + time_width + type_width + 3, y, type); } /* The icons to show with the destination and via stations. */ StringID icon = STR_DEPARTURES_STATION_NONE; StringID icon_via = STR_DEPARTURES_STATION_NONE; if (_settings_client.gui.departure_destination_type) { Station *t = Station::Get(d->terminus.station); if (t->facilities & FACIL_DOCK && t->facilities & FACIL_AIRPORT && d->vehicle->type != VEH_SHIP && d->vehicle->type != VEH_AIRCRAFT) { icon = STR_DEPARTURES_STATION_PORTAIRPORT; } else if (t->facilities & FACIL_DOCK && d->vehicle->type != VEH_SHIP) { icon = STR_DEPARTURES_STATION_PORT; } else if (t->facilities & FACIL_AIRPORT && d->vehicle->type != VEH_AIRCRAFT) { icon = STR_DEPARTURES_STATION_AIRPORT; } } if (_settings_client.gui.departure_destination_type && d->via != INVALID_STATION) { Station *t = Station::Get(d->via); if (t->facilities & FACIL_DOCK && t->facilities & FACIL_AIRPORT && d->vehicle->type != VEH_SHIP && d->vehicle->type != VEH_AIRCRAFT) { icon_via = STR_DEPARTURES_STATION_PORTAIRPORT; } else if (t->facilities & FACIL_DOCK && d->vehicle->type != VEH_SHIP) { icon_via = STR_DEPARTURES_STATION_PORT; } else if (t->facilities & FACIL_AIRPORT && d->vehicle->type != VEH_AIRCRAFT) { icon_via = STR_DEPARTURES_STATION_AIRPORT; } } /* Destination */ if (d->via == INVALID_STATION) { /* Only show the terminus. */ SetDParam(0, d->terminus.station); SetDParam(1, icon); ltr ? DrawString( text_left + time_width + type_width + 6, text_right - status_width - (toc_width + veh_width + group_width + 2) - 2, y + 1, STR_DEPARTURES_TERMINUS) : DrawString(text_left + status_width + (toc_width + veh_width + group_width + 2) + 2, text_right - time_width - type_width - 6, y + 1, STR_DEPARTURES_TERMINUS); } else { /* Show the terminus and the via station. */ SetDParam(0, d->terminus.station); SetDParam(1, icon); SetDParam(2, d->via); SetDParam(3, icon_via); int text_width = (GetStringBoundingBox(STR_DEPARTURES_TERMINUS_VIA_STATION)).width; if (text_width < text_right - status_width - (toc_width + veh_width + group_width + 2) - 2 - (text_left + time_width + type_width + 6)) { /* They will both fit, so show them both. */ SetDParam(0, d->terminus.station); SetDParam(1, icon); SetDParam(2, d->via); SetDParam(3, icon_via); ltr ? DrawString( text_left + time_width + type_width + 6, text_right - status_width - (toc_width + veh_width + group_width + 2) - 2, y + 1, STR_DEPARTURES_TERMINUS_VIA_STATION) : DrawString(text_left + status_width + (toc_width + veh_width + group_width + 2) + 2, text_right - time_width - type_width - 6, y + 1, STR_DEPARTURES_TERMINUS_VIA_STATION); } else { /* They won't both fit, so switch between showing the terminus and the via station approximately every 4 seconds. */ if (this->tick_count & (1 << 7)) { SetDParam(0, d->via); SetDParam(1, icon_via); ltr ? DrawString( text_left + time_width + type_width + 6, text_right - status_width - (toc_width + veh_width + group_width + 2) - 2, y + 1, STR_DEPARTURES_VIA) : DrawString(text_left + status_width + (toc_width + veh_width + group_width + 2) + 2, text_right - time_width - type_width - 6, y + 1, STR_DEPARTURES_VIA); } else { SetDParam(0, d->terminus.station); SetDParam(1, icon); ltr ? DrawString( text_left + time_width + type_width + 6, text_right - status_width - (toc_width + veh_width + group_width + 2) - 2, y + 1, STR_DEPARTURES_TERMINUS_VIA) : DrawString(text_left + status_width + (toc_width + veh_width + group_width + 2) + 2, text_right - time_width - type_width - 6, y + 1, STR_DEPARTURES_TERMINUS_VIA); } } } /* Status */ { int status_left = ltr ? text_right - status_width - 2 - (toc_width + veh_width + group_width + 2) : text_left + (toc_width + veh_width + group_width + 2) + 7; int status_right = ltr ? text_right - (toc_width + veh_width + group_width + 2) + 2 : text_left + status_width + 2 + (toc_width + veh_width + group_width + 7); if (d->status == D_ARRIVED) { /* The vehicle has arrived. */ DrawString(status_left, status_right, y + 1, STR_DEPARTURES_ARRIVED); } else if(d->status == D_CANCELLED) { /* The vehicle has been cancelled. */ DrawString(status_left, status_right, y + 1, STR_DEPARTURES_CANCELLED); } else{ if (d->lateness <= DAY_TICKS && d->scheduled_date > ((_date * DAY_TICKS) + _date_fract)) { /* We have no evidence that the vehicle is late, so assume it is on time. */ DrawString(status_left, status_right, y + 1, STR_DEPARTURES_ON_TIME); } else { if ((d->scheduled_date + d->lateness) < ((_date * DAY_TICKS) + _date_fract)) { /* The vehicle was expected to have arrived by now, even if we knew it was going to be late. */ /* We assume that the train stays at least a day at a station so it won't accidentally be marked as delayed for a fraction of a day. */ DrawString(status_left, status_right, y + 1, STR_DEPARTURES_DELAYED); } else { /* The vehicle is expected to be late and is not yet due to arrive. */ SetDParam(0, d->scheduled_date + d->lateness); DrawString(status_left, status_right, y + 1, STR_DEPARTURES_EXPECTED); } } } } /* Vehicle name */ if (_settings_client.gui.departure_show_vehicle) { SetDParam(0, (uint64)(d->vehicle->index)); ltr ? DrawString(text_right - (toc_width + veh_width + group_width + 2), text_right - toc_width - group_width - 2, y + 1, STR_DEPARTURES_VEH) : DrawString( text_left + toc_width + group_width + 2, text_left + (toc_width + veh_width + group_width + 2), y + 1, STR_DEPARTURES_VEH); } /* Group name */ if (_settings_client.gui.departure_show_group && d->vehicle->group_id != INVALID_GROUP && d->vehicle->group_id != DEFAULT_GROUP) { SetDParam(0, (uint64)(d->vehicle->group_id)); ltr ? DrawString(text_right - (toc_width + group_width + 2), text_right - toc_width - 2, y + 1, STR_DEPARTURES_GROUP) : DrawString( text_left + toc_width + 2, text_left + (toc_width + group_width + 2), y + 1, STR_DEPARTURES_GROUP); } /* Operating company */ if (_settings_client.gui.departure_show_company) { SetDParam(0, (uint64)(d->vehicle->owner)); ltr ? DrawString(text_right - toc_width, text_right, y + 1, STR_DEPARTURES_TOC, TC_FROMSTRING, SA_RIGHT) : DrawString( text_left, text_left + toc_width, y + 1, STR_DEPARTURES_TOC, TC_FROMSTRING, SA_LEFT); } int bottom_y = y + this->entry_height - small_font_size - (_settings_client.gui.departure_larger_font ? 1 : 3); /* Calling at */ ltr ? DrawString( text_left, text_left + calling_at_width, bottom_y, _settings_client.gui.departure_larger_font ? STR_DEPARTURES_CALLING_AT_LARGE : STR_DEPARTURES_CALLING_AT) : DrawString(text_right - calling_at_width, text_right, bottom_y, _settings_client.gui.departure_larger_font ? STR_DEPARTURES_CALLING_AT_LARGE : STR_DEPARTURES_CALLING_AT); /* List of stations */ /* RTL languages can be handled in the language file, e.g. by having the following: */ /* STR_DEPARTURES_CALLING_AT_STATION :{STATION}, {RAW_STRING} */ /* STR_DEPARTURES_CALLING_AT_LAST_STATION :{STATION} & {RAW_STRING}*/ char buffer[512], scratch[512]; if (d->calling_at.Length() != 0) { SetDParam(0, (uint64)(*d->calling_at.Get(0)).station); GetString(scratch, STR_DEPARTURES_CALLING_AT_FIRST_STATION, lastof(scratch)); StationID continuesTo = INVALID_STATION; if (d->calling_at.Get(0)->station == d->terminus.station && d->calling_at.Length() > 1) { continuesTo = d->calling_at.Get(d->calling_at.Length() - 1)->station; } else if (d->calling_at.Length() > 1) { /* There's more than one stop. */ uint i; /* For all but the last station, write out ", <station>". */ for (i = 1; i < d->calling_at.Length() - 1; ++i) { StationID s = d->calling_at.Get(i)->station; if (s == d->terminus.station) { continuesTo = d->calling_at.Get(d->calling_at.Length() - 1)->station; break; } SetDParam(0, (uint64)scratch); SetDParam(1, (uint64)s); GetString(buffer, STR_DEPARTURES_CALLING_AT_STATION, lastof(buffer)); strncpy(scratch, buffer, sizeof(scratch)); } /* Finally, finish off with " and <station>". */ SetDParam(0, (uint64)scratch); SetDParam(1, (uint64)d->calling_at.Get(i)->station); GetString(buffer, STR_DEPARTURES_CALLING_AT_LAST_STATION, lastof(buffer)); strncpy(scratch, buffer, sizeof(scratch)); } SetDParam(0, (uint64)scratch); StringID string; if (continuesTo == INVALID_STATION) { string = _settings_client.gui.departure_larger_font ? STR_DEPARTURES_CALLING_AT_LIST_LARGE : STR_DEPARTURES_CALLING_AT_LIST; } else { SetDParam(1, continuesTo); string = _settings_client.gui.departure_larger_font ? STR_DEPARTURES_CALLING_AT_LIST_SMART_TERMINUS_LARGE : STR_DEPARTURES_CALLING_AT_LIST_SMART_TERMINUS; } GetString(buffer, string, lastof(buffer)); } else { buffer[0] = 0; //SetDParam(0, d->terminus); //GetString(scratch, STR_DEPARTURES_CALLING_AT_FIRST_STATION, lastof(scratch)); } int list_width = (GetStringBoundingBox(buffer, _settings_client.gui.departure_larger_font ? FS_NORMAL : FS_SMALL)).width; /* Draw the whole list if it will fit. Otherwise scroll it. */ if (list_width < text_right - (text_left + calling_at_width + 2)) { ltr ? DrawString(text_left + calling_at_width + 2, text_right, bottom_y, buffer) : DrawString( text_left, text_right - calling_at_width - 2, bottom_y, buffer); } else { DrawPixelInfo tmp_dpi; if (ltr ? !FillDrawPixelInfo(&tmp_dpi, text_left + calling_at_width + 2, bottom_y, text_right - (text_left + calling_at_width + 2), small_font_size + 3) : !FillDrawPixelInfo(&tmp_dpi, text_left , bottom_y, text_right - (text_left + calling_at_width + 2), small_font_size + 3)) { y += this->entry_height; continue; } DrawPixelInfo *old_dpi = _cur_dpi; _cur_dpi = &tmp_dpi; /* The scrolling text starts out of view at the right of the screen and finishes when it is out of view at the left of the screen. */ int pos = ltr ? text_right - (this->tick_count % (list_width + text_right - text_left)) : text_left + (this->tick_count % (list_width + text_right - text_left)); ltr ? DrawString( pos, INT16_MAX, 0, buffer, TC_FROMSTRING, SA_LEFT | SA_FORCE) : DrawString(-INT16_MAX, pos, 0, buffer, TC_FROMSTRING, SA_RIGHT | SA_FORCE); _cur_dpi = old_dpi; } y += this->entry_height; } }
koreapyj/openttd-yapp
src/departures_gui.cpp
C++
gpl-2.0
33,995
/** A data model representing a list of Invites @class InviteList @extends Discourse.Model @namespace Discourse @module Discourse **/ Discourse.InviteList = Discourse.Model.extend({ empty: (function() { return this.blank('pending') && this.blank('redeemed'); }).property('pending.@each', 'redeemed.@each') }); Discourse.InviteList.reopenClass({ findInvitedBy: function(user) { var promise; promise = new RSVP.Promise(); $.ajax({ url: "/users/" + (user.get('username_lower')) + "/invited.json", success: function(result) { var invitedList; invitedList = result.invited_list; if (invitedList.pending) { invitedList.pending = invitedList.pending.map(function(i) { return Discourse.Invite.create(i); }); } if (invitedList.redeemed) { invitedList.redeemed = invitedList.redeemed.map(function(i) { return Discourse.Invite.create(i); }); } invitedList.user = user; return promise.resolve(Discourse.InviteList.create(invitedList)); } }); return promise; } });
SuperSonicDesignINC/FXDD
app/assets/javascripts/discourse/models/invite_list.js
JavaScript
gpl-2.0
1,146
<?php /** * Coupon Data * * Functions for displaying the coupon data meta box * * @author WooThemes * @category Admin Write Panels * @package WooCommerce */ /** * Coupon data meta box * * Displays the meta box */ function woocommerce_coupon_data_meta_box($post) { global $woocommerce; wp_nonce_field( 'woocommerce_save_data', 'woocommerce_meta_nonce' ); ?> <style type="text/css"> #edit-slug-box { display:none } </style> <div id="coupon_options" class="panel woocommerce_options_panel"> <?php // Type woocommerce_wp_select( array( 'id' => 'discount_type', 'label' => __('Discount type', 'woothemes'), 'options' => $woocommerce->get_coupon_discount_types() ) ); // Amount woocommerce_wp_text_input( array( 'id' => 'coupon_amount', 'label' => __('Coupon amount', 'woothemes'), 'placeholder' => __('0.00', 'woothemes'), 'description' => __('Enter an amount e.g. 2.99', 'woothemes') ) ); // Individual use woocommerce_wp_checkbox( array( 'id' => 'individual_use', 'label' => __('Individual use', 'woothemes'), 'description' => __('Check this box if the coupon cannot be used in conjunction with other coupons', 'woothemes') ) ); // Apply before tax woocommerce_wp_checkbox( array( 'id' => 'apply_before_tax', 'label' => __('Apply before tax', 'woothemes'), 'description' => __('Check this box if the coupon should be applied before calculating cart tax', 'woothemes') ) ); // Free Shipping woocommerce_wp_checkbox( array( 'id' => 'free_shipping', 'label' => __('Enable free shipping', 'woothemes'), 'description' => sprintf(__('Check this box if the coupon enables free shipping (see <a href="%s">Free Shipping</a>)', 'woothemes'), admin_url('admin.php?page=woocommerce&tab=shipping_methods&subtab=shipping-free_shipping')) ) ); // Product ids woocommerce_wp_text_input( array( 'id' => 'product_ids', 'label' => __('Product IDs', 'woothemes'), 'placeholder' => __('N/A', 'woothemes'), 'description' => __('(optional) Comma separate IDs which need to be in the cart to use this coupon or, for "Product Discounts", which products are discounted.', 'woothemes') ) ); // Exclude Product ids woocommerce_wp_text_input( array( 'id' => 'exclude_product_ids', 'label' => __('Exclude Product IDs', 'woothemes'), 'placeholder' => __('N/A', 'woothemes'), 'description' => __('(optional) Comma separate IDs which must not be in the cart to use this coupon or, for "Product Discounts", which products are not discounted.', 'woothemes') ) ); // Usage limit woocommerce_wp_text_input( array( 'id' => 'usage_limit', 'label' => __('Usage limit', 'woothemes'), 'placeholder' => __('Unlimited usage', 'woothemes'), 'description' => __('(optional) How many times this coupon can be used before it is void', 'woothemes') ) ); // Expiry date woocommerce_wp_text_input( array( 'id' => 'expiry_date', 'label' => __('Expiry date', 'woothemes'), 'placeholder' => __('Never expire', 'woothemes'), 'description' => __('(optional) The date this coupon will expire, <code>YYYY-MM-DD</code>', 'woothemes'), 'class' => 'short date-picker' ) ); do_action('woocommerce_coupon_options'); ?> </div> <?php } /** * Coupon Data Save * * Function for processing and storing all coupon data. */ add_action('woocommerce_process_shop_coupon_meta', 'woocommerce_process_shop_coupon_meta', 1, 2); function woocommerce_process_shop_coupon_meta( $post_id, $post ) { global $wpdb; $woocommerce_errors = array(); // Add/Replace data to array $type = strip_tags(stripslashes( $_POST['discount_type'] )); $amount = strip_tags(stripslashes( $_POST['coupon_amount'] )); $product_ids = strip_tags(stripslashes( $_POST['product_ids'] )); $exclude_product_ids = strip_tags(stripslashes( $_POST['exclude_product_ids'] )); $usage_limit = (isset($_POST['usage_limit']) && $_POST['usage_limit']>0) ? (int) $_POST['usage_limit'] : ''; $individual_use = isset($_POST['individual_use']) ? 'yes' : 'no'; $expiry_date = strip_tags(stripslashes( $_POST['expiry_date'] )); $apply_before_tax = isset($_POST['apply_before_tax']) ? 'yes' : 'no'; $free_shipping = isset($_POST['free_shipping']) ? 'yes' : 'no'; // Save update_post_meta( $post_id, 'discount_type', $type ); update_post_meta( $post_id, 'coupon_amount', $amount ); update_post_meta( $post_id, 'individual_use', $individual_use ); update_post_meta( $post_id, 'product_ids', $product_ids ); update_post_meta( $post_id, 'exclude_product_ids', $exclude_product_ids ); update_post_meta( $post_id, 'usage_limit', $usage_limit ); update_post_meta( $post_id, 'expiry_date', $expiry_date ); update_post_meta( $post_id, 'apply_before_tax', $apply_before_tax ); update_post_meta( $post_id, 'free_shipping', $free_shipping ); do_action('woocommerce_coupon_options'); // Error Handling if (sizeof($woocommerce_errors)>0) update_option('woocommerce_errors', $woocommerce_errors); }
buger/fotodep_fmagazine
wp-content/plugins/woocommerce/admin/writepanels/writepanel-coupon_data.php
PHP
gpl-2.0
4,970
package verbtester; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JCheckBox; public class RootCheckBox extends JCheckBox { public RootCheckBox(Action a) { super(a); init(); } public RootCheckBox(Icon icon, boolean selected) { super(icon, selected); init(); } public RootCheckBox(Icon icon) { super(icon); init(); } public RootCheckBox(String text, boolean selected) { super(text, selected); init(); } public RootCheckBox(String text, Icon icon, boolean selected) { super(text, icon, selected); init(); } public RootCheckBox(String text, Icon icon) { super(text, icon); init(); } public RootCheckBox(String text) { super(text); init(); } private static final long serialVersionUID = 7420502854359388037L; private List<SlaveCheckBox> slaves; boolean stateChangedFromSlave; public RootCheckBox() { super(); init(); } private void init() { stateChangedFromSlave = false; addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!stateChangedFromSlave && slaves != null) { for(SlaveCheckBox s: slaves) { s.changeStateFromRoot(isSelected()); } } } }); } public void setSlaves(SlaveCheckBox[] theSlaves) { this.slaves = new ArrayList<SlaveCheckBox>(); for(SlaveCheckBox s: theSlaves) { slaves.add(s); } } public void addSlave(SlaveCheckBox s) { slaves.add(s); } public void changeStateFromSlave(boolean isChecked) { stateChangedFromSlave = true; boolean allChecked = true; for(JCheckBox s : slaves) { if(!s.isSelected()) { allChecked = false; } } if(!allChecked) { setSelected(false); } stateChangedFromSlave = false; } }
trombipeti/gerverbtester
src/verbtester/RootCheckBox.java
Java
gpl-2.0
1,867
package ai; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Vector; public class TranspositionPlayer<M extends Move<N>, N extends Node<M, N>> extends Player<M, N> { private M bestFirstMove; private int millis; private TranspositionTable<M, N> table; public TranspositionPlayer(int color, int millis) { super(color); this.millis = millis; table = new TranspositionTable<>(1000000); } @Override public M getMove(N node) { return iterativeDeepening(node); } private M iterativeDeepening(N node) { bestFirstMove = null; int depth = 1; long end = System.currentTimeMillis() + millis; do { negamax(node, depth++); } while (System.currentTimeMillis() < end); System.out.println("Transposition: " + depth); return bestFirstMove; } private void negamax(N node, int depth) { negamax(node, color, depth, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true); } private double negamax(N node, int color, int depth, double alpha, double beta, boolean isRoot) { double alphaOrig = alpha; TranspositionEntry<M> entry = table.get(node); M bestMove = null; if (entry != null && entry.getDepth() >= depth) { switch (entry.getFlag()) { case TranspositionEntry.EXACT: return entry.getValue(); case TranspositionEntry.LOWER_BOUND: alpha = Math.max(alpha, entry.getValue()); break; case TranspositionEntry.UPPER_BOUND: beta = Math.min(beta, entry.getValue()); break; } bestMove = entry.getBestMove(); } if (depth == 0 || node.gameOver()) { return color * node.getValue(color); } double bestValue = Double.NEGATIVE_INFINITY; List<Pair<N, M>> pairs = getSortedMoves(node, color); if (bestMove != null && bestMove.isLegal(node)) { pairs.add(0, new Pair<>(node.apply(bestMove), bestMove)); } for (Pair<N, M> pair : pairs) { double val = -negamax(pair.getKey(), -color, depth - 1, -beta, -alpha, false); if (val > bestValue) { bestValue = val; bestMove = pair.getValue(); } if (val > alpha) { alpha = val; if (isRoot) { bestFirstMove = pair.getValue(); } } if (alpha >= beta) { break; } } int flag; if (bestValue <= alphaOrig) { flag = TranspositionEntry.UPPER_BOUND; } else if (bestValue >= beta) { flag = TranspositionEntry.LOWER_BOUND; } else { flag = TranspositionEntry.EXACT; } table.put(node, new TranspositionEntry<>(node.getZobristHash(), bestMove, bestValue, depth, flag)); return bestValue; } private List<Pair<N, M>> getSortedMoves(N node, final int color) { List<Pair<N, M>> pairs = new Vector<>(); for (M move : node.getLegalMoves()) { pairs.add(new Pair<>(node.apply(move), move)); } Collections.sort(pairs, new Comparator<Pair<N, M>>() { @Override public int compare(Pair<N, M> o1, Pair<N, M> o2) { return color * (o2.getKey().getEstimate() - o1.getKey() .getEstimate()); } }); return pairs; } }
arwheelock/chess
src/ai/TranspositionPlayer.java
Java
gpl-2.0
3,005
require "pulpcore_client" module Katello module Pulp3 class Content extend Katello::Abstract::Pulp::Content class << self def create_upload(size = 0, checksum = nil, content_type = nil) content_unit_href = nil if checksum && content_type content_backend_service = SmartProxy.pulp_master.content_service(content_type) content_list = content_backend_service.content_api.list("digest": checksum) content_unit_href = content_list.results.first.pulp_href unless content_list.results.empty? return {"content_unit_href" => content_unit_href} if content_unit_href end upload_href = uploads_api.create(upload_class.new(size: size)).pulp_href {"upload_id" => upload_href.split("/").last} end def delete_upload(upload_href) #Commit deletes upload request for pulp3. Not needed other than to implement abstract method. end def upload_chunk(upload_href, offset, content, size) upload_href = "/pulp/api/v3/uploads/" + upload_href + "/" offset = offset.try(:to_i) size = size.try(:to_i) begin filechunk = Tempfile.new('filechunk', :encoding => 'ascii-8bit') filechunk.write(content) filechunk.flush actual_chunk_size = File.size(filechunk) uploads_api.update(upload_href, content_range(offset, offset + actual_chunk_size - 1, size), filechunk) ensure filechunk.close filechunk.unlink end end private def core_api_client PulpcoreClient::ApiClient.new(SmartProxy.pulp_master.pulp3_configuration(PulpcoreClient::Configuration)) end def uploads_api PulpcoreClient::UploadsApi.new(core_api_client) end def upload_class PulpcoreClient::Upload end def content_range(start, finish, total) finish = finish > total ? total : finish "bytes #{start}-#{finish}/#{total}" end end end end end
pmoravec/katello
app/services/katello/pulp3/content.rb
Ruby
gpl-2.0
2,122
package com.evaluation.service; import com.evaluation.control.AccountManager; import com.evaluation.dao.DatabaseAdapter; import com.evaluation.util.TcpConnect; import com.evaluation.view.*; import android.os.BatteryManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class HomeService extends Service{ /** * */ private static final String TAG = "effort"; private TcpConnect iTCPConnect = null; //public DatabaseAdapter mDataAdapter; private final IBinder mBinder = new LocalBinder(); public boolean serviceOver = false; private int value; // private TcpConnect iTCPConnect = null; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.e(TAG, "============>HomeService.onBind"); return mBinder; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public class LocalBinder extends Binder{ public HomeService getService(){ return HomeService.this; } } public boolean onUnbind(Intent i){ Log.e(TAG, "===========>HomeService.onUnbind"); return false; } public void onRebind(Intent i){ Log.e(TAG, "===========>HomeService.onRebind"); } public void onCreate(){ IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); registerReceiver(homePressReceiver, homeFilter); registerReceiver(homePressReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); iTCPConnect = new TcpConnect((MyApplication)this.getApplication()); iTCPConnect.start(); // Thread thread = new UnConnectThread(); // thread.start(); } public int onStartCommand(Intent intent,int flags, int startId){ Log.e(TAG, "============>HomeService.onStartCommand"); //iTCPConnect = new TcpConnect(this); //iTCPConnect.start(); return super.onStartCommand(intent, flags, startId); } public void onDestroy(){ if (homePressReceiver != null) { try { unregisterReceiver(homePressReceiver); } catch (Exception e) { Log.e(TAG, "unregisterReceiver homePressReceiver failure :" + e.getCause()); } } Log.e(TAG, "onStop"); serviceOver = true; iTCPConnect.Close(); //Intent i = new Intent("RESTART_ACTIVITY"); //i.addFlags(Intent.flag); //sendBroadcast(i);//传递过去 super.onDestroy(); } private final BroadcastReceiver homePressReceiver = new BroadcastReceiver() { final String SYSTEM_DIALOG_REASON_KEY = "reason"; final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); // if (reason != null // && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { // // 自己随意控制程序,写自己想要的结果 // Log.i(TAG, "home_press"); // Intent i = new Intent("RESTART_ACTIVITY"); // sendBroadcast(i);//传递过去 // } } if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { Intent i = new Intent("TIMEOUT"); int status = intent.getIntExtra("status", 0); switch (status) { case BatteryManager.BATTERY_STATUS_UNKNOWN: break; case BatteryManager.BATTERY_STATUS_CHARGING: break; case BatteryManager.BATTERY_STATUS_DISCHARGING: HomeService.this.sendBroadcast(i); break; case BatteryManager.BATTERY_STATUS_NOT_CHARGING: HomeService.this.sendBroadcast(i); break; case BatteryManager.BATTERY_STATUS_FULL: break; } } } }; private class UnConnectThread extends Thread { public void run() { while(!serviceOver){ try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } int count = iTCPConnect.getCurrentLinkedSocketThreadNum(); Log.e(TAG, "定时检测socket连接数: " + count); if(count < 1) { Intent intent = new Intent("TIMEOUT"); HomeService.this.sendBroadcast(intent); } } } } }
tingken/Evaluation-new
src/com/evaluation/service/HomeService.java
Java
gpl-2.0
4,291
<?php // 调整云标签默认样式 add_filter('widget_tag_cloud_args','style_tags'); function style_tags($args) { $args = array( 'largest'=> '12', //设置标签云的所有标签中,计数最多(最多文章使用)的标签的字体大小,默认值为22pt 'smallest'=> '12', //设置标签云中显示的所有标签中,计数最少(最少文章使用)的标签字体大小,默认值为 8pt 'unit' => 'px', //标签文字字号的单位,默认为pt,可以为px、em、pt、百分比等 'format'=> 'list', //调用标签的格式,可选"flat"、"list"和"array",默认为"flat"平铺,"list"为列表方式; 'number' => '0', //设置标签云中显示的最多标签数量,默认值为45个,设置为"0″则调用所有标签; 'orderby' => 'count', //设置标签云中标签的排序方式,默认值为"name"按名称排序。如果设置成"count"则按关联的文章数量排列; 'order' => 'DESC' //排序方式,默认为"ASC"按正序,"DESC"按倒序,"RAND"按任意顺序; ); return $args; } ?>
Osub/lpy
wp-content/themes/javin/inc/tag-cloud.php
PHP
gpl-2.0
1,098
/** * Copyright (c) 2015 Digi International Inc., * All rights not expressly granted are reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ #include "XBee802.h" #include "IO/IOSample802.h" #include "Frames/802_Frames.h" #include "FrameHandlers/FH_ModemStatus.h" using namespace XBeeLib; /* Class constructor */ XBee802::XBee802(PinName tx, PinName rx, PinName reset, PinName rts, PinName cts, int baud) : XBee(tx, rx, reset, rts, cts, baud), _nd_handler(NULL), _rx_64b_handler(NULL), _rx_16b_handler(NULL), _io_data_64b_handler(NULL), _io_data_16b_handler(NULL) { } /* Class destructor */ XBee802::~XBee802() { unregister_node_discovery_cb(); unregister_receive_cb(); unregister_io_sample_cb(); } RadioStatus XBee802::init() { RadioStatus retval = XBee::init(); uint16_t addr16; RadioStatus error = get_network_address(&addr16); if (error == Success) { digi_log(LogLevelInfo, "ADDR16: %04x\r\n", addr16); } else { digi_log(LogLevelInfo, "ADDR16: UNKNOWN\r\n"); } const RadioProtocol radioProtocol = get_radio_protocol(); if (radioProtocol != Raw_802_15_4) { digi_log(LogLevelError, "Radio protocol does not match, needed a %d got a %d\r\n", Raw_802_15_4, radioProtocol); retval = Failure; } assert(radioProtocol == Raw_802_15_4); return retval; } RadioStatus XBee802::set_channel(uint8_t channel) { AtCmdFrame::AtCmdResp cmdresp; if (is_PRO()) { if (channel < 0x0C || channel > 0x17) { return Failure; } } else { if (channel < 0x0B || channel > 0x1A) { return Failure; } } cmdresp = set_param("CH", channel); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } RadioStatus XBee802::get_channel(uint8_t * const channel) { if (channel == NULL) { return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; cmdresp = get_param("CH", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *channel = var32; return Success; } RadioStatus XBee802::set_panid(uint16_t panid) { AtCmdFrame::AtCmdResp cmdresp; cmdresp = set_param("ID", panid); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } RadioStatus XBee802::get_panid(uint16_t * const panid) { if (panid == NULL) { return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; cmdresp = get_param("ID", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *panid = var32; return Success; } RadioStatus XBee802::set_network_address(uint16_t addr16) { AtCmdFrame::AtCmdResp cmdresp; cmdresp = set_param("MY", addr16); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } return Success; } void XBee802::radio_status_update(AtCmdFrame::ModemStatus modem_status) { /* Update the radio status variables */ if (modem_status == AtCmdFrame::HwReset) { _hw_reset_cnt++; } else if (modem_status == AtCmdFrame::WdReset) { _wd_reset_cnt++; } _modem_status = modem_status; digi_log(LogLevelDebug, "\r\nUpdating radio status: %02x\r\n", modem_status); } TxStatus XBee802::send_data(const RemoteXBee& remote, const uint8_t *const data, uint16_t len, bool syncr) { if (remote.is_valid_addr64b()) { const uint64_t remote64 = remote.get_addr64(); digi_log(LogLevelDebug, "send_data ADDR64: %08x:%08x\r\n", UINT64_HI32(remote64), UINT64_LO32(remote64)); TxFrame802 frame = TxFrame802(remote64, _tx_options, data, len); if (syncr) { return send_data(&frame); } else { frame.set_data(0, 0); /* Set frame id to 0 so there is no answer */ send_api_frame(&frame); return TxStatusSuccess; } } if (remote.is_valid_addr16b()) { const uint16_t remote16 = remote.get_addr16(); digi_log(LogLevelDebug, "send_data ADDR16: %04x\r\n", remote16); TxFrame802 frame = TxFrame802(remote16, _tx_options, data, len); if (syncr) { return send_data(&frame); } else { frame.set_data(0, 0); /* Set frame id to 0 so there is no answer */ send_api_frame(&frame); return TxStatusSuccess; } } return TxStatusInvalidAddr; } XBee802::AssocStatus XBee802::get_assoc_status(void) { return (AssocStatus)get_AI(); } RemoteXBee802 XBee802::get_remote_node_by_id(const char * const node_id) { uint64_t addr64; uint16_t addr16; _get_remote_node_by_id(node_id, &addr64, &addr16); return RemoteXBee802(addr64, addr16); } void XBee802::register_node_discovery_cb(node_discovery_802_cb_t function) { if (_nd_handler == NULL) { _nd_handler = new FH_NodeDiscovery802(); register_frame_handler(_nd_handler); } _nd_handler->register_node_discovery_cb(function); } void XBee802::unregister_node_discovery_cb() { if (_nd_handler != NULL) { _nd_handler->unregister_node_discovery_cb(); unregister_frame_handler(_nd_handler); delete _nd_handler; _nd_handler = NULL; /* as delete does not set to NULL */ } } void XBee802::register_receive_cb(receive_802_cb_t function) { if (_rx_64b_handler == NULL) { _rx_64b_handler = new FH_RxPacket64b802(); register_frame_handler(_rx_64b_handler); } _rx_64b_handler->register_receive_cb(function); if (_rx_16b_handler == NULL) { _rx_16b_handler = new FH_RxPacket16b802(); register_frame_handler(_rx_16b_handler); } _rx_16b_handler->register_receive_cb(function); } void XBee802::unregister_receive_cb() { if (_rx_64b_handler != NULL) { _rx_64b_handler->unregister_receive_cb(); unregister_frame_handler(_rx_64b_handler); delete _rx_64b_handler; _rx_64b_handler = NULL; /* as delete does not set to NULL */ } if (_rx_16b_handler != NULL) { _rx_16b_handler->unregister_receive_cb(); unregister_frame_handler(_rx_16b_handler); delete _rx_16b_handler; _rx_16b_handler = NULL; /* as delete does not set to NULL */ } } void XBee802::register_io_sample_cb(io_data_cb_802_t function) { if (_io_data_64b_handler == NULL) { _io_data_64b_handler = new FH_IoDataSampe64b802(); register_frame_handler(_io_data_64b_handler); } _io_data_64b_handler->register_io_data_cb(function); if (_io_data_16b_handler == NULL) { _io_data_16b_handler = new FH_IoDataSampe16b802(); register_frame_handler(_io_data_16b_handler); } _io_data_16b_handler->register_io_data_cb(function); } void XBee802::unregister_io_sample_cb() { if (_io_data_64b_handler != NULL) { _io_data_64b_handler->unregister_io_data_cb(); unregister_frame_handler(_io_data_64b_handler); delete _io_data_64b_handler; _io_data_64b_handler = NULL; /* as delete does not set to NULL */ } if (_io_data_16b_handler != NULL) { _io_data_16b_handler->unregister_io_data_cb(); unregister_frame_handler(_io_data_16b_handler); delete _io_data_16b_handler; _io_data_16b_handler = NULL; /* as delete does not set to NULL */ } } AtCmdFrame::AtCmdResp XBee802::get_param(const RemoteXBee& remote, const char * const param, uint32_t * const data) { uint16_t len = sizeof *data; AtCmdFrame::AtCmdResp atCmdResponse; if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param); atCmdResponse = send_at_cmd(&cmd_frame, (uint8_t *)data, &len, RadioRemote); } else if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param); atCmdResponse = send_at_cmd(&cmd_frame, (uint8_t *)data, &len, RadioRemote); } else { return AtCmdFrame::AtCmdRespInvalidAddr; } if (atCmdResponse == AtCmdFrame::AtCmdRespOk && len > sizeof *data) { atCmdResponse = AtCmdFrame::AtCmdRespLenMismatch; } return atCmdResponse; } AtCmdFrame::AtCmdResp XBee802::set_param(const RemoteXBee& remote, const char * const param, uint32_t data) { if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param, data); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param, data); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } return AtCmdFrame::AtCmdRespInvalidAddr; } AtCmdFrame::AtCmdResp XBee802::set_param(const RemoteXBee& remote, const char * const param, const uint8_t * data, uint16_t len) { if (remote.is_valid_addr64b()) { const uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param, data, len); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } if (remote.is_valid_addr16b()) { const uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param, data, len); return send_at_cmd(&cmd_frame, NULL, NULL, RadioRemote); } return AtCmdFrame::AtCmdRespInvalidAddr; } AtCmdFrame::AtCmdResp XBee802::get_param(const RemoteXBee& remote, const char * const param, uint8_t * const data, uint16_t * const len) { if (remote.is_valid_addr64b()) { uint64_t dev_addr64 = remote.get_addr64(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr64, param); return send_at_cmd(&cmd_frame, data, len, RadioRemote, false); } if (remote.is_valid_addr16b()) { uint16_t dev_addr16 = remote.get_addr16(); AtCmdFrame cmd_frame = AtCmdFrame(dev_addr16, param); return send_at_cmd(&cmd_frame, data, len, RadioRemote, false); } return AtCmdFrame::AtCmdRespInvalidAddr; } static void get_dio_cmd(XBee802::IoLine line, char * const iocmd) { if (line >= XBee802::PWM0) { iocmd[0] = 'P'; iocmd[1] = '0' + line - XBee802::PWM0; } else { iocmd[0] = 'D'; iocmd[1] = '0' + line; } iocmd[2] = '\0'; } RadioStatus XBee802::set_pin_config(const RemoteXBee& remote, IoLine line, IoMode mode) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3]; get_dio_cmd(line, iocmd); cmdresp = set_param(remote, iocmd, (uint8_t)mode); if (cmdresp != AtCmdFrame::AtCmdRespOk) { digi_log(LogLevelError, "set_pin_config: set_param returned %d\r\n", cmdresp); return Failure; } return Success; } RadioStatus XBee802::get_pin_config(const RemoteXBee& remote, IoLine line, IoMode * const mode) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3]; get_dio_cmd(line, iocmd); uint32_t var32; cmdresp = get_param(remote, iocmd, &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *mode = (IoMode)var32; return Success; } RadioStatus XBee802::set_dio(const RemoteXBee& remote, IoLine line, DioVal val) { if (line > DI8) { digi_log(LogLevelError, "set_dio: Pin %d not supported as IO\r\n", line); return Failure; } if (val == Low) { return set_pin_config(remote, line, DigitalOutLow); } else { return set_pin_config(remote, line, DigitalOutHigh); } } RadioStatus XBee802::get_dio(const RemoteXBee& remote, IoLine line, DioVal * const val) { return get_iosample(remote).get_dio(line, val); } RadioStatus XBee802::get_adc(const RemoteXBee& remote, IoLine line, uint16_t * const val) { return get_iosample(remote).get_adc(line, val); } RadioStatus XBee802::set_pwm(const RemoteXBee& remote, IoLine line, float duty_cycle) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3] = { 'M', '0', '\0' }; if (line != PWM0 && line != PWM1) { return Failure; } if (line == PWM1) { iocmd[1] = '1'; } uint16_t pwm_val = (uint16_t)(duty_cycle * DR_PWM_MAX_VAL / 100); cmdresp = set_param(remote, iocmd, pwm_val); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } IOSample802 XBee802::get_iosample(const RemoteXBee& remote) { uint8_t io_sample[MAX_IO_SAMPLE_802_LEN]; uint16_t len = sizeof io_sample; RadioStatus resp = _get_iosample(remote, io_sample, &len); if (resp != Success) { digi_log(LogLevelError, "XBee802::get_iosample failed to get an IOSample\r\n"); len = 0; } return IOSample802(io_sample, len); } static uint8_t get_dio_mask(XBee802::IoLine line) { switch (line) { case XBee802::DIO4_AD4: return (1 << 0); case XBee802::DIO3_AD3: return (1 << 1); case XBee802::DIO2_AD2: return (1 << 2); case XBee802::DIO1_AD1: return (1 << 3); case XBee802::DIO0_AD0: return (1 << 4); case XBee802::DIO6: return (1 << 5); case XBee802::DI8: return (1 << 6); default: return 0; } } RadioStatus XBee802::set_pin_pull_up(const RemoteXBee& remote, IoLine line, bool enable) { AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; uint8_t pr; cmdresp = get_param(remote, "PR", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } pr = var32; const uint8_t dio_mask = get_dio_mask(line); if (dio_mask == 0) { digi_log(LogLevelError, "XBee802::set_pin_pull_up: invalid pin %d\r\n", line); return Failure; } if (enable) { pr |= dio_mask; } else { pr &= ~dio_mask; } cmdresp = set_param(remote, "PR", pr); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } static uint8_t get_dio_ic_mask(XBee802::IoLine line) { if (line < XBee802::DI8) { return (1 << line); } return 0; } RadioStatus XBee802::enable_dio_change_detection(const RemoteXBee& remote, IoLine line, bool enable) { if (line > DIO7) { digi_log(LogLevelError, "XBee802::enable_dio_change_detection: pin not supported (%d)\r\n", line); return Failure; } AtCmdFrame::AtCmdResp cmdresp; uint32_t var32; uint8_t ic; cmdresp = get_param(remote, "IC", &var32); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } ic = var32; const uint8_t dio_mask = get_dio_ic_mask(line); if (dio_mask == 0) { digi_log(LogLevelError, "XBeeZB::enable_dio_change_detection: invalid pin %d\r\n", line); return Failure; } if (enable) { ic |= dio_mask; } else { ic &= ~dio_mask; } cmdresp = set_param(remote, "IC", ic); return cmdresp == AtCmdFrame::AtCmdRespOk ? Success : Failure; } #ifdef GET_PWM_AVAILABLE RadioStatus XBee802::get_pwm(const RemoteXBee& remote, IoLine line, float * const duty_cycle) { AtCmdFrame::AtCmdResp cmdresp; char iocmd[3] = { 'M', '0', '\0' }; if (line != PWM0 && line != PWM1) { return Failure; } if (line == PWM1) { iocmd[1] = '1'; } uint16_t pwm_val; cmdresp = get_param(remote, iocmd, &pwm_val); if (cmdresp != AtCmdFrame::AtCmdRespOk) { return Failure; } *duty_cycle = (float)(pwm_val * 100 / DR_PWM_MAX_VAL); return Success; } #endif
jon-whit/AtlasQuad
src/XBeeLib/XBee802/XBee802.cpp
C++
gpl-2.0
16,579
<? require('../style/fpdf.php'); include('../inc/functions/connectdb.php'); include('../inc/functions/f_laporan.php'); include('../inc/functions/f_kls_mk.php'); include('../inc/functions/f_mk.php'); include('../inc/functions/f_jurusan.php'); include('../inc/functions/f_fpp.php'); include('../inc/functions/f_mhs.php'); $pdf=new FPDF(); $pdf->AddPage(); $baris=10; $kolom=190; $pdf->SetFont('Arial','B',7); $pdf->Cell($kolom,$baris,"Print time : ".date("j F Y - g:i a"),0,1,'L'); $pdf->SetFont('Arial','B',14); $pdf->Cell($kolom,$baris,'DAFTAR ISI KELAS SAMPAI DENGAN KASUS KHUSUS',0,1,'C'); $pdf->Cell($kolom,$baris,$_GET['semester']." ".$_GET['tahun'],0,1,'C'); $baris=6; $pdf->Cell($kolom,$baris," ",0,1,'L'); $pdf->SetFont('Arial','B',10); $pdf->Cell(15,$baris,'KODE ',1,0,'C'); $pdf->Cell(95,$baris,'NAMA MK ',1,0,'C'); $pdf->Cell(10,$baris,'KP ',1,0,'C'); $pdf->Cell(12,$baris,'KAP ',1,0,'C'); $pdf->Cell(12,$baris,'FPP1 ',1,0,'C'); $pdf->Cell(12,$baris,'FPP2 ',1,0,'C'); $pdf->Cell(12,$baris,'KK ',1,0,'C'); $pdf->Cell(12,$baris,'JML',1,0,'C'); $pdf->Cell(12,$baris,'SISA',1,1,'C'); $pdf->SetFont('Arial','',10); $lap = selectAllKlsMk(); if($lap) { foreach($lap as $display) { $jumlah=0; $pdf->Cell(15,$baris,$display['kode_mk'],1,0,'C'); $nama= getDetailMk($display['kode_mk']); $pdf->Cell(95,$baris,$nama['nama'],1,0,'L'); $pdf->Cell(10,$baris,$display['kp'],1,0,'C'); $pdf->Cell(12,$baris,$display['kapasitas'],1,0,'C'); $kode = "I".substr($_GET['tahun'],2,2).substr($_GET['semester'],0,2); $number = getTerimaKls($kode,$display['kode_kelas']); $jumlah+=$number; $pdf->Cell(12,$baris,$number,1,0,'R'); $kode = "II".substr($_GET['tahun'],2,2).substr($_GET['semester'],0,2); $number = getTerimaKls($kode,$display['kode_kelas']); $jumlah+=$number; $pdf->Cell(12,$baris,$number,1,0,'R'); $kode = "KK".substr($_GET['tahun'],2,2).substr($_GET['semester'],0,2); $number = getTerimaKls($kode,$display['kode_kelas']); $jumlah+=$number; $pdf->Cell(12,$baris,$number,1,0,'R'); $pdf->Cell(12,$baris,$jumlah,1,0,'R'); $pdf->Cell(12,$baris,$display['kapasitas']-$jumlah,1,1,'R'); } } $pdf->Cell($kolom,$baris,' ',0,1,'C'); $pdf->Cell($kolom,$baris,'---------------------------------------------------------------------------------------------------------',0,1,'C'); $pdf->Output(); ?>
fiafayo/ironhide
web/admin/pdf_isi_kls.php
PHP
gpl-2.0
2,449
package de.icybits.ts3.sq.api.commands; import de.icybits.ts3.sq.api.basic.Command; import de.icybits.ts3.sq.api.interfaces.ITS3CommandNames; /** * create snapshot of a virtual server * * @author Alias: Iceac Sarutobi */ public class ServersnapshotcreateCommand extends Command implements ITS3CommandNames { public ServersnapshotcreateCommand() { super(COMMAND_SERVERSNAPSHOTCREATE); } }
icybits/ts3-sq-api
de.icybits.ts3.sq.api/src/de/icybits/ts3/sq/api/commands/ServersnapshotcreateCommand.java
Java
gpl-2.0
401
// <script> elgg.provide('elgg.embed'); elgg.embed.init = function() { // inserts the embed content into the textarea $(".embed-item").live('click', elgg.embed.insert); elgg.register_hook_handler('embed', 'editor', elgg.embed._deprecated_custom_insert_js); // caches the current textarea id $(".embed-control").live('click', function() { var textAreaId = /embed-control-(\S)+/.exec($(this).attr('class'))[0]; elgg.embed.textAreaId = textAreaId.substr("embed-control-".length); }); // special pagination helper for lightbox $('.embed-wrapper .elgg-pagination a').live('click', elgg.embed.forward); $('.embed-section').live('click', elgg.embed.forward); $('.elgg-form-embed').live('submit', elgg.embed.submit); }; /** * Adds support for plugins that extends embed/custom_insert_js deprecated views * * @param {String} hook * @param {String} type * @param {Object} params * @param {String|Boolean} value * @returns {String|Boolean} * @private */ elgg.embed._deprecated_custom_insert_js = function(hook, type, params, value) { var textAreaId = params.textAreaId; var content = params.content; var event = params.event; <?php if (elgg_view_exists ( 'embed/custom_insert_js' )) { elgg_deprecated_notice ( "The view embed/custom_insert_js has been replaced by the js hook 'embed', 'editor'.", 1.9 ); echo elgg_view ( 'embed/custom_insert_js' ); } ?> }; /** * Inserts data attached to an embed list item in textarea * * @param {Object} event * @return void */ elgg.embed.insert = function(event) { var textAreaId = elgg.embed.textAreaId; var textArea = $('#' + textAreaId); // generalize this based on a css class attached to what should be inserted var content = ' ' + $(this).find(".embed-insert").parent().html() + ' '; var value = textArea.val(); var result = textArea.val(); // this is a temporary work-around for #3971 if (content.indexOf('thumbnail.php') != -1) { content = content.replace('size=small', 'size=medium'); } textArea.focus(); if (!elgg.isNullOrUndefined(textArea.prop('selectionStart'))) { var cursorPos = textArea.prop('selectionStart'); var textBefore = value.substring(0, cursorPos); var textAfter = value.substring(cursorPos, value.length); result = textBefore + content + textAfter; } else if (document.selection) { // IE compatibility var sel = document.selection.createRange(); sel.text = content; result = textArea.val(); } // See the ckeditor plugin for an example of this hook result = elgg.trigger_hook('embed', 'editor', { textAreaId: textAreaId, content: content, value: value, event: event }, result); if (result || result === '') { textArea.val(result); } elgg.ui.lightbox.close(); event.preventDefault(); }; /** * Submit an upload form through Ajax * * Requires the jQuery Form Plugin. Because files cannot be uploaded with * XMLHttpRequest, the plugin uses an invisible iframe. This results in the * the X-Requested-With header not being set. To work around this, we are * sending the header as a POST variable and Elgg's code checks for it in * elgg_is_xhr(). * * @param {Object} event * @return bool */ elgg.embed.submit = function(event) { $('.embed-wrapper .elgg-form-file-upload').hide(); $('.embed-throbber').show(); $(this).ajaxSubmit({ dataType : 'json', data : { 'X-Requested-With' : 'XMLHttpRequest'}, success : function(response, status, xhr) { if (response) { if (response.system_messages) { elgg.register_error(response.system_messages.error); elgg.system_message(response.system_messages.success); } if (response.status >= 0) { var forward = $('input[name=embed_forward]').val(); var url = elgg.normalize_url('embed/tab/' + forward); url = elgg.embed.addContainerGUID(url); $('.embed-wrapper').parent().load(url); } else { // incorrect response, presumably an error has been displayed $('.embed-throbber').hide(); $('.embed-wrapper .elgg-form-file-upload').show(); } } // ie 7 and 8 have a null response because of the use of an iFrame // so just show the list after upload. // http://jquery.malsup.com/form/#file-upload claims you can wrap JSON // in a textarea, but a quick test didn't work, and that is fairly // intrusive to the rest of the ajax system. else if (response === undefined && $.browser.msie) { var forward = $('input[name=embed_forward]').val(); var url = elgg.normalize_url('embed/tab/' + forward); url = elgg.embed.addContainerGUID(url); $('.embed-wrapper').parent().load(url); } }, error : function(xhr, status) { elgg.register_error(elgg.echo('actiongatekeeper:uploadexceeded')); $('.embed-throbber').hide(); $('.embed-wrapper .elgg-form-file-upload').show(); } }); // this was bubbling up the DOM causing a submission event.preventDefault(); event.stopPropagation(); }; /** * Loads content within the lightbox * * @param {Object} event * @return void */ elgg.embed.forward = function(event) { // make sure container guid is passed var url = $(this).attr('href'); url = elgg.embed.addContainerGUID(url); $('.embed-wrapper').parent().load(url); event.preventDefault(); }; /** * Adds the container guid to a URL * * @param {string} url * @return string */ elgg.embed.addContainerGUID = function(url) { if (url.indexOf('container_guid=') == -1) { var guid = $('input[name=embed_container_guid]').val(); return url + '?container_guid=' + guid; } else { return url; } }; elgg.register_hook_handler('init', 'system', elgg.embed.init);
MikkelSandbag/seElgg
mod/embed/views/default/js/embed/embed.php
PHP
gpl-2.0
5,583
<?php /** * @file * Search block theme implementation to display a block. * * Available variables: * - $block->subject: Block title. * - $content: Block content. * - $block->module: Module that generated the block. * - $block->delta: An ID for the block, unique within each module. * - $block->region: The block region embedding the current block. * - $classes: String of classes that can be used to style contextually through * CSS. It can be manipulated through the variable $classes_array from * preprocess functions. The default values can be one or more of the following: * - block: The current template type, i.e., "theming hook". * - block-[module]: The module generating the block. For example, the user module * is responsible for handling the default user navigation block. In that case * the class would be "block-user". * - $title_prefix (array): An array containing additional output populated by * modules, intended to be displayed in front of the main title tag that * appears in the template. * - $title_suffix (array): An array containing additional output populated by * modules, intended to be displayed after the main title tag that appears in * the template. * * Helper variables: * - $classes_array: Array of html class attribute values. It is flattened * into a string within the variable $classes. * - $block_zebra: Outputs 'odd' and 'even' dependent on each block region. * - $zebra: Same output as $block_zebra but independent of any block region. * - $block_id: Counter dependent on each block region. * - $id: Same output as $block_id but independent of any block region. * - $is_front: Flags true when presented in the front page. * - $logged_in: Flags true when the current user is a logged-in member. * - $is_admin: Flags true when the current user is an administrator. * - $block_html_id: A valid HTML ID and guaranteed unique. * * @see template_preprocess() * @see template_preprocess_block() * @see template_process() */ ?> <div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>> <div class="grid-inner"> <?php print render($title_prefix); ?> <?php if ($block->subject): ?> <h2<?php print $title_attributes; ?>><?php print $block->subject; ?></h2> <?php endif; ?> <?php print render($title_suffix); ?> <div<?php print $content_attributes; ?>> <?php print $content ?> </div> </div> </div>
mrjeeves/veniceskate
sites/all/themes/arctica/arctica/templates/block--search.tpl.php
PHP
gpl-2.0
2,475
<?php // force UTF-8 Ø global $_zp_themeroot; ?> <p class="mainbutton" id="addcommentbutton"><a href="#addcomment" class="btn"><img src="<?php echo $_zp_themeroot ?>/images/btn_add_a_comment.gif" alt="" width="116" height="21" /></a></p> <!-- BEGIN #addcomment --> <div id="addcomment"> <script type="text/javascript"> // <!-- <![CDATA[ $(function() { window.onload = initCommentState; }); // ]]> --> </script> <h2><?php echo gettext("Add a comment") ?></h2> <form method="post" action="#" id="comments-form"> <input type="hidden" name="comment" value="1" /> <input type="hidden" name="remember" value="1" /> <table cellspacing="0"> <?php if ($req = getOption('comment_name_required')) { if ($req == 'required') { $star = '*'; $required = true; } else { $star = ''; } ?> <tr valign="top" align="left" id="row-name"> <th><?php printf(gettext('%sName:'),$star); ?></th> <td> <?php if ($disabled['name']) { ?> <input tabindex="1" id="name" name="name" class="text" type="hidden" value="<?php echo html_encode($stored['name']);?>" /> <?php echo html_encode($stored['name']);?> <?php } else { ?> <input tabindex="1" id="name" name="name" class="text" value="<?php echo html_encode($stored['name']);?>" /> <?php } ?> <label> (<input type="checkbox" name="anon" value="1"<?php if ($stored['anon']) echo ' checked="checked"'; ; ?> /> <?php echo gettext('<em>anonymous</em>'); ?>) </label> </td> </tr> <?php } if ($req = getOption('comment_email_required')) { if ($req == 'required') { $star = '*'; $required = true; } else { $star = ''; } ?> <tr valign="top" align="left" id="row-email"> <th><?php printf(gettext('Email%s:'),$star); ?></th> <td> <?php if ($disabled['email']) { ?> <input tabindex="2" id="email" name="email" class="text" type="hidden" value="<?php echo html_encode($stored['email']);?>" /> <?php echo html_encode($stored['email']);?> <?php } else { ?> <input tabindex="2" id="email" name="email" class="text" value="<?php echo html_encode($stored['email']);?>" /> <?php } ?> <em><?php echo gettext("(not displayed)"); ?></em> </td> </tr> <?php } if ($req = getOption('comment_web_required')) { if ($req == 'required') { $star = '*'; $required = true; } else { $star = ''; } ?> <tr valign="top" align="left"> <th><?php printf(gettext('URL%s:'),$star); ?></th> <td> <?php if ($disabled['website']) { ?> <input tabindex="3" name="website" id="website" class="text" type="hidden" value="<?php echo html_encode($stored['website']);?>" /> <?php echo html_encode($stored['website']);?> <?php } else { ?> <input tabindex="3" name="website" id="website" class="text" value="<?php echo html_encode($stored['website']);?>" /> <?php } ?> </td> </tr> <?php } if ($req = getOption('comment_form_addresses')) { if ($req == 'required') { $star = '*'; $required = true; } else { $star = ''; } ?> <tr> <th><?php printf(gettext('Street%s:'),$star); ?></th> <td> <?php if ($disabled['street']) { ?> <input name="0-comment_form_street" id="comment_form_street" class="text" type="hidden" size="22" value="<?php echo html_encode($address['street']); ?>" /> <?php echo html_encode($address['street']); ?> <?php } else { ?> <input name="0-comment_form_street" id="comment_form_street" class="text" size="22" value="<?php echo html_encode($address['street']); ?>" /> <?php } ?> </td> </tr> <tr> <th><?php printf(gettext('City:%s'),$star); ?></th> <td> <?php if ($disabled['city']) { ?> <input name="0-comment_form_city" id="comment_form_city" class="text" type="hidden" size="22" value="<?php echo html_encode($address['city']); ?>" /> <?php echo html_encode($address['city']); ?> <?php } else { ?> <input name="0-comment_form_city" id="comment_form_city" class="text" size="22" value="<?php echo html_encode($address['city']); ?>" /> <?php } ?> </td> </tr> <tr> <th><?php printf(gettext('State%s:'),$star); ?></th> <td> <?php if ($disabled['state']) { ?> <input name="0-comment_form_state" id="comment_form_state" class="text" type="hidden" size="22" value="<?php echo html_encode($address['state']); ?>" /> <?php echo html_encode($address['state']); ?> <?php } else { ?> <input name="0-comment_form_state" id="comment_form_state" class="text" size="22" value="<?php echo html_encode($address['state']); ?>" /> <?php } ?> </td> </tr> <tr> <th><?php printf(gettext('Country:%s'),$star); ?></th> <td> <?php if ($disabled['country']) { ?> <input name="comment_form_country" id="comment_form_country" class="text" type="hidden" size="22" value="<?php echo html_encode($address['country']); ?>" /> <?php echo html_encode($address['country']); ?> <?php } else { ?> <input name="comment_form_country" id="comment_form_country" class="text" size="22" value="<?php echo html_encode($address['country']); ?>" /> <?php } ?> </td> </tr> <tr> <th><?php printf(gettext('Postal code%s:'),$star); ?></th> <td> <?php if ($disabled['postal']) { ?> <input name="0-comment_form_postal" id="comment_form_postal" class="text" size="22" type="hidden" value="<?php echo html_encode($address['postal']); ?>" /> <?php echo html_encode($address['postal']); ?> <?php } else { ?> <input name="0-comment_form_postal" id="comment_form_postal" class="text" size="22" value="<?php echo html_encode($address['postal']); ?>" /> <?php } ?> </td> </tr> <?php } if($required) { ?> <tr><td colspan="2"><?php echo gettext('*Required fields'); ?></td></tr> <?php } if (getOption('Use_Captcha')) { printCaptcha("<tr valign=\"top\" align=\"left\"><th>" .gettext('Enter CAPTCHA').' ', "</th><td>", "</td></tr>\n", 16); } ?> <tr valign="top" align="left"> <th><?php echo gettext('Private comment:'); ?></th> <td> <label> <input type="checkbox" name="private" value="1"<?php if ($stored['private']) echo ' checked="checked"'; ; ?> /> <?php echo gettext("(don't publish)"); ?> </label> </td> </tr> <?php ?> <tr valign="top" align="left"> <th><?php echo gettext('Comment:'); ?></th> <td></td> </tr> <tr> <td colspan="2"><textarea tabindex="4" id="comment" name="comment" rows="10" cols="40"><?php echo $stored['comment']; ?></textarea></td> </tr> <tr valign="top" align="left"> <td class="buttons" colspan="2"> <!--<input type="submit" name="preview" tabindex="5" value="Preview" id="btn-preview" />--> <input type="submit" name="post" tabindex="6" value="<?php echo gettext('Post'); ?>" id="btn-post" /> <p><?php echo gettext('Avoid clicking &ldquo;Post&rdquo; more than once.'); ?></p> </td> </tr> </table> </form> </div> <!-- END #addcomment -->
christopherstock/GC_Carpentry
_ASSETS/backup/old_site/v0.1/zenphoto/themes/stopdesign/comment_form/comment_form.php
PHP
gpl-2.0
7,689
<?php class RoxFrontRouterModel extends RoxModelBase { function getPossibleUrlLanguage($urlheadercode = false) { // Uncomment briefly this line in case you have problem with it, save, log in BeWelcome, and add again the comment in this line // return false ; return false; } // end of getPossibleUrlLanguage function getLanguage($langcode = false) { if (!$langcode) { return false; } else { if (is_numeric($langcode)) { return $this->singleLookup(" SELECT languages.id AS id, languages.ShortCode AS ShortCode FROM languages, words WHERE languages.id = '" . $this->dao->escape($langcode) . "' AND languages.id = words.Idlanguage AND words.code = 'welcometosignup'"); } else { return $this->singleLookup(" SELECT languages.id AS id, languages.ShortCode AS ShortCode FROM languages, words WHERE languages.ShortCode = '" . $this->dao->escape($langcode) . "' AND languages.id = words.Idlanguage AND words.code = 'welcometosignup'"); } } } }
gl0bi/rox
roxlauncher/roxfrontroutermodel.php
PHP
gpl-2.0
1,582
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SystemModel.TO; namespace SystemCore.TemplateEngine { /// <summary> /// Klasa mapująca MessageTemplateTO na MessageTemplate /// </summary> public static class MessageTemplateTO2MessageTemplateMapper { public static MessageTemplate map(MessageTemplateTO messageTemplateTO) { if (messageTemplateTO == null) throw new ArgumentNullException("messageTemplateTO"); return new MessageTemplate { Id = messageTemplateTO.MessageId, Title = messageTemplateTO.MessageTitle, Template = messageTemplateTO.MessageTemplate }; } public static IEnumerable<MessageTemplate> map(IEnumerable<MessageTemplateTO> messageTemplateTOs) { if (messageTemplateTOs == null) throw new ArgumentNullException("messageTemplateTOs"); foreach (var template in messageTemplateTOs) yield return map(template); } } }
blisek/HomeSecuritySystem
SystemCore/TemplateEngine/MessageTemplateTO2MessageTemplateMapper.cs
C#
gpl-2.0
1,148
// Register.cpp : implementation file // #include "stdafx.h" #include "Portal.h" #include "Register.h" #include "afxdialogex.h" // Register dialog IMPLEMENT_DYNAMIC(Register, CDialogEx) Register::Register(CWnd* pParent /*=NULL*/) : CDialogEx(Register::IDD, pParent) , m_ID(_T("")) , m_Password(_T("")) , m_EnterYear(0) , m_Phone(_T("")) , m_Address(_T("")) , m_Name(_T("")) { #ifndef _WIN32_WCE EnableActiveAccessibility(); #endif EnableAutomation(); } Register::~Register() { } void Register::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CDialogEx::OnFinalRelease(); } void Register::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, 1007, m_ID); DDX_Text(pDX, 1009, m_Password); DDX_Control(pDX, 1025, m_ComboMajor); DDX_Text(pDX, 1013, m_EnterYear); DDX_Text(pDX, 1015, m_Phone); DDX_Text(pDX, 1012, m_Address); DDX_Text(pDX, 1008, m_Name); DDX_Control(pDX, IDC_COMBO1, m_ComboGender); } BEGIN_MESSAGE_MAP(Register, CDialogEx) ON_BN_CLICKED(1026, &Register::OnBnClicked1026) ON_BN_CLICKED(1027, &Register::OnBnClicked1027) END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(Register, CDialogEx) END_DISPATCH_MAP() // Note: we add support for IID_IRegister to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .IDL file. // {26007234-3268-44D1-AEA7-4EB880885DB9} static const IID IID_IRegister = { 0x26007234, 0x3268, 0x44D1, { 0xAE, 0xA7, 0x4E, 0xB8, 0x80, 0x88, 0x5D, 0xB9 } }; BEGIN_INTERFACE_MAP(Register, CDialogEx) INTERFACE_PART(Register, IID_IRegister, Dispatch) END_INTERFACE_MAP() // Register message handlers // 100835 ÇѽÂȯ BOOL Register::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: Add extra initialization here SYSTEMTIME curTime; // system ½Ã°£ ±¸Á¶Ã¼ ¼±¾ð GetSystemTime(&curTime); // system ½Ã°£ ±¸Á¶Ã¼ ÃʱâÈ­ int semester = 0; if (curTime.wMonth > 2 && curTime.wMonth < 7) semester = 1; // system ½Ã°£ÀÌ 3~6¿ù »çÀÌÀ̸é semester = 1 else if (curTime.wMonth>7 && curTime.wMonth <= 12) semester = 2; // system ½Ã°£ÀÌ 8~12¿ù »çÀÌÀ̸é semester = 2 m_EnterYear = curTime.wYear; UpdateData(FALSE); CSUBJECT_info<CSUBJECT_GETMAJOR> info; UpdateData(TRUE); info.m_YEAR = curTime.wYear; info.m_dwYEARLength = sizeof(LONG); info.m_dwYEARStatus = DBSTATUS_S_OK; info.m_SEMESTER = semester; info.m_dwSEMESTERLength = sizeof(LONG); info.m_dwSEMESTERStatus = DBSTATUS_S_OK; if (info.OpenAll() == S_OK) { while (info.MoveNext() == S_OK) m_ComboMajor.AddString(info.m_MAJOR); m_ComboMajor.SetCurSel(0); // Ãʱâ Ä¿¼­ 0À¸·Î ¼³Á¤ } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // È®ÀÎ ¹öưÀ» ´­·¶À» ¶§ void Register::OnBnClicked1026() { // TODO: Add your control notification handler code here CRegister_Student<CRegister_StudentAccessor> info; UpdateData(TRUE); info.m_SID = atoi(m_ID); info.m_PASSWORD = atoi(m_Password); info.m_Curri_Year = m_EnterYear; CString major; m_ComboMajor.GetLBText(m_ComboMajor.GetCurSel(), major); CString Gender; m_ComboGender.GetLBText(m_ComboGender.GetCurSel(), Gender); strcpy_s(info.m_MAJOR, major); strcpy_s(info.m_Phone_Number, m_Phone); strcpy_s(info.m_SNAME, m_Name); strcpy_s(info.m_ADDERSS, m_Address); strcpy_s(info.m_GENDER, Gender); if (info.OpenAll() == S_OK) // µ¥ÀÌÅͺ£À̽º Á¢¼Ó ¼º°ø AfxMessageBox("ȸ¿ø µî·Ï ¿Ï·á"); else AfxMessageBox("µî·Ï ½ÇÆÐ"); OnOK(); } // Ãë¼Ò ¹öưÀ» ´­·¶À» ¶§ void Register::OnBnClicked1027() { // TODO: Add your control notification handler code here OnCancel(); } // 100835 ÇѽÂȯ
shharn/mysources
StudentMamagement_DBProject/sources/Register.cpp
C++
gpl-2.0
4,007
<?php /** * nnHtml * extra JHTML functions * * @package NoNumber Framework * @version 14.1.1 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2014 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; /** * nnHtml */ class nnHtml { static function selectlist(&$options, $name, $value, $id, $size = 0, $multiple = 0) { if (empty($options)) { return '<fieldset class="radio">' . JText::_('NN_NO_ITEMS_FOUND') . '</fieldset>'; } require_once JPATH_PLUGINS . '/system/nnframework/helpers/parameters.php'; $parameters = NNParameters::getInstance(); $params = $parameters->getPluginParams('nnframework'); if (!is_array($value)) { $value = explode(',', $value); } $count = 0; if ($options != -1) { foreach ($options as $option) { $count++; if (isset($option->links)) { $count += count($option->links); } if ($count > $params->max_list_count) { break; } } } if ($options == -1 || $count > $params->max_list_count) { if (is_array($value)) { $value = implode(',', $value); } if (!$value) { $input = '<textarea name="' . $name . '" id="' . $id . '" cols="40" rows="5" />' . $value . '</textarea>'; } else { $input = '<input type="text" name="' . $name . '" id="' . $id . '" value="' . $value . '" size="60" />'; } return '<fieldset class="radio"><label for="' . $id . '">' . JText::_('NN_ITEM_IDS') . ':</label>' . $input . '</fieldset>'; } $size = $size ? $size : 300; if (!$multiple) { return JHtml::_('select.genericlist', $options, $name, 'class="inputbox"', 'value', 'text', $value); } JHtml::stylesheet('nnframework/multiselect.min.css', false, true); JHtml::script('nnframework/multiselect.min.js', false, true); $html = array(); $html[] = '<div class="well well-small nn_multiselect" id="' . $id . '">'; $html[] = ' <div class="form-inline nn_multiselect-controls"> <span class="small">' . JText::_('JSELECT') . ': <a class="nn_multiselect-checkall" href="javascript://">' . JText::_('JALL') . '</a>, <a class="nn_multiselect-uncheckall" href="javascript://">' . JText::_('JNONE') . '</a>, <a class="nn_multiselect-toggleall" href="javascript://">' . JText::_('NN_TOGGLE') . '</a> </span> <span class="width-20">|</span> <span class="small">' . JText::_('NN_EXPAND') . ': <a class="nn_multiselect-expandall" href="javascript://">' . JText::_('JALL') . '</a>, <a class="nn_multiselect-collapseall" href="javascript://">' . JText::_('JNONE') . '</a> </span> <span class="width-20">|</span> <span class="small">' . JText::_('JSHOW') . ': <a class="nn_multiselect-showall" href="javascript://">' . JText::_('JALL') . '</a>, <a class="nn_multiselect-showselected" href="javascript://">' . JText::_('NN_SELECTED') . '</a> </span> <span class="nn_multiselect-maxmin"> <span class="width-20">|</span> <span class="small"> <a class="nn_multiselect-maximize" href="javascript://">' . JText::_('NN_MAXIMIZE') . '</a> <a class="nn_multiselect-minimize" style="display:none;" href="javascript://">' . JText::_('NN_MINIMIZE') . '</a> </span> </span> <input type="text" name=""nn_multiselect-filter" class="nn_multiselect-filter input-medium search-query pull-right" size="16" autocomplete="off" placeholder="' . JText::_('JSEARCH_FILTER') . '" aria-invalid="false" tabindex="-1"> </div> <div class="clearfix"></div> <hr class="hr-condensed" />'; $o = array(); foreach ($options as $option) { $option->level = isset($option->level) ? $option->level : 0; $o[] = $option; if (isset($option->links)) { foreach ($option->links as $link) { $link->level = $option->level + (isset($link->level) ? $link->level : 1); $o[] = $link; } } } $html[] = '<ul class="nn_multiselect-ul" style="max-height:' . (int) $size . 'px;overflow-x: hidden;">'; $prevlevel = 0; foreach ($o as $i => $option) { if ($prevlevel < $option->level) { $html[] = '<ul class="nn_multiselect-sub">'; } else if ($prevlevel > $option->level) { $html[] = str_repeat('</li></ul>', $prevlevel - $option->level); } else if ($i) { $html[] = '</li>'; } $labelclass = trim('pull-left ' . (isset($option->labelclass) ? $option->labelclass : '')); $html[] = '<li>'; $item = '<div class="' . trim('nn_multiselect-item pull-left ' . (isset($option->class) ? $option->class : '')) . '">'; if (isset($option->title)) { $labelclass .= ' nav-header'; } if (isset($option->title) && (!isset($option->value) || !$option->value)) { $item .= '<label class="' . $labelclass . '">' . $option->title . '</label>'; } else { $selected = in_array($option->value, $value) ? ' checked="checked"' : ''; $disabled = (isset($option->disable) && $option->disable) ? ' readonly="readonly" style="visibility:hidden"' : ''; $item .= '<input type="checkbox" class="pull-left" name="' . $name . '" id="' . $id . $option->value . '" value="' . $option->value . '"' . $selected . $disabled . ' /> <label for="' . $id . $option->value . '" class="' . $labelclass . '">' . $option->text . '</label>'; } $item .= '</div>'; $html[] = $item; if (!isset($o[$i + 1])) { $html[] = str_repeat('</li></ul>', $option->level); } $prevlevel = $option->level; } $html[] = '</ul>'; $html[] = ' <div style="display:none;" class="nn_multiselect-menu-block"> <div class="pull-left nav-hover nn_multiselect-menu"> <div class="btn-group"> <a href="#" data-toggle="dropdown" class="dropdown-toggle btn btn-micro"> <span class="caret"></span> </a> <ul class="dropdown-menu"> <li class="nav-header">' . JText::_('COM_MODULES_SUBITEMS') . '</li> <li class="divider"></li> <li class=""><a class="checkall" href="javascript://"><span class="icon-checkbox"></span> ' . JText::_('JSELECT') . '</a> </li> <li><a class="uncheckall" href="javascript://"><span class="icon-checkbox-unchecked"></span> ' . JText::_('COM_MODULES_DESELECT') . '</a> </li> <div class="nn_multiselect-menu-expand"> <li class="divider"></li> <li><a class="expandall" href="javascript://"><span class="icon-plus"></span> ' . JText::_('NN_EXPAND') . '</a></li> <li><a class="collapseall" href="javascript://"><span class="icon-minus"></span> ' . JText::_('NN_COLLAPSE') . '</a></li> </div> </ul> </div> </div> </div>'; $html[] = '</div>'; $html = implode('', $html); return preg_replace('#>\[\[\:(.*?)\:\]\]#si', ' style="\1">', $html); } }
alexrah/lorenzetto2
plugins/system/nnframework/helpers/html.php
PHP
gpl-2.0
6,887
""" Builds out and synchronizes yum repo mirrors. Initial support for rsync, perhaps reposync coming later. Copyright 2006-2007, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ import os import os.path import time import yaml # Howell-Clark version import sys HAS_YUM = True try: import yum except: HAS_YUM = False import utils from cexceptions import * import traceback import errno from utils import _ import clogger class RepoSync: """ Handles conversion of internal state to the tftpboot tree layout """ # ================================================================================== def __init__(self,config,tries=1,nofail=False,logger=None): """ Constructor """ self.verbose = True self.api = config.api self.config = config self.distros = config.distros() self.profiles = config.profiles() self.systems = config.systems() self.settings = config.settings() self.repos = config.repos() self.rflags = self.settings.reposync_flags self.tries = tries self.nofail = nofail self.logger = logger if logger is None: self.logger = clogger.Logger() self.logger.info("hello, reposync") # =================================================================== def run(self, name=None, verbose=True): """ Syncs the current repo configuration file with the filesystem. """ self.logger.info("run, reposync, run!") try: self.tries = int(self.tries) except: utils.die(self.logger,"retry value must be an integer") self.verbose = verbose report_failure = False for repo in self.repos: env = repo.environment for k in env.keys(): self.logger.info("environment: %s=%s" % (k,env[k])) if env[k] is not None: os.putenv(k,env[k]) if name is not None and repo.name != name: # invoked to sync only a specific repo, this is not the one continue elif name is None and not repo.keep_updated: # invoked to run against all repos, but this one is off self.logger.info("%s is set to not be updated" % repo.name) continue repo_mirror = os.path.join(self.settings.webdir, "repo_mirror") repo_path = os.path.join(repo_mirror, repo.name) mirror = repo.mirror if not os.path.isdir(repo_path) and not repo.mirror.lower().startswith("rhn://"): os.makedirs(repo_path) # which may actually NOT reposync if the repo is set to not mirror locally # but that's a technicality for x in range(self.tries+1,1,-1): success = False try: self.sync(repo) success = True except: utils.log_exc(self.logger) self.logger.warning("reposync failed, tries left: %s" % (x-2)) if not success: report_failure = True if not self.nofail: utils.die(self.logger,"reposync failed, retry limit reached, aborting") else: self.logger.error("reposync failed, retry limit reached, skipping") self.update_permissions(repo_path) if report_failure: utils.die(self.logger,"overall reposync failed, at least one repo failed to synchronize") return True # ================================================================================== def sync(self, repo): """ Conditionally sync a repo, based on type. """ if repo.breed == "rhn": return self.rhn_sync(repo) elif repo.breed == "yum": return self.yum_sync(repo) #elif repo.breed == "apt": # return self.apt_sync(repo) elif repo.breed == "rsync": return self.rsync_sync(repo) else: utils.die(self.logger,"unable to sync repo (%s), unknown or unsupported repo type (%s)" % (repo.name, repo.breed)) # ==================================================================================== def createrepo_walker(self, repo, dirname, fnames): """ Used to run createrepo on a copied Yum mirror. """ if os.path.exists(dirname) or repo['breed'] == 'rsync': utils.remove_yum_olddata(dirname) # add any repo metadata we can use mdoptions = [] if os.path.isfile("%s/.origin/repomd.xml" % (dirname)): if not HAS_YUM: utils.die(self.logger,"yum is required to use this feature") rmd = yum.repoMDObject.RepoMD('', "%s/.origin/repomd.xml" % (dirname)) if rmd.repoData.has_key("group"): groupmdfile = rmd.getData("group").location[1] mdoptions.append("-g %s" % groupmdfile) if rmd.repoData.has_key("prestodelta"): # need createrepo >= 0.9.7 to add deltas if utils.check_dist() == "redhat" or utils.check_dist() == "suse": cmd = "/usr/bin/rpmquery --queryformat=%{VERSION} createrepo" createrepo_ver = utils.subprocess_get(self.logger, cmd) if createrepo_ver >= "0.9.7": mdoptions.append("--deltas") else: utils.die(self.logger,"this repo has presto metadata; you must upgrade createrepo to >= 0.9.7 first and then need to resync the repo through cobbler.") blended = utils.blender(self.api, False, repo) flags = blended.get("createrepo_flags","(ERROR: FLAGS)") try: # BOOKMARK cmd = "createrepo %s %s %s" % (" ".join(mdoptions), flags, dirname) utils.subprocess_call(self.logger, cmd) except: utils.log_exc(self.logger) self.logger.error("createrepo failed.") del fnames[:] # we're in the right place # ==================================================================================== def rsync_sync(self, repo): """ Handle copying of rsync:// and rsync-over-ssh repos. """ repo_mirror = repo.mirror if not repo.mirror_locally: utils.die(self.logger,"rsync:// urls must be mirrored locally, yum cannot access them directly") if repo.rpm_list != "" and repo.rpm_list != []: self.logger.warning("--rpm-list is not supported for rsync'd repositories") # FIXME: don't hardcode dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) spacer = "" if not repo.mirror.startswith("rsync://") and not repo.mirror.startswith("/"): spacer = "-e ssh" if not repo.mirror.endswith("/"): repo.mirror = "%s/" % repo.mirror # FIXME: wrapper for subprocess that logs to logger cmd = "rsync -rltDv %s --delete --exclude-from=/etc/cobbler/rsync.exclude %s %s" % (spacer, repo.mirror, dest_path) rc = utils.subprocess_call(self.logger, cmd) if rc !=0: utils.die(self.logger,"cobbler reposync failed") os.path.walk(dest_path, self.createrepo_walker, repo) self.create_local_file(dest_path, repo) # ==================================================================================== def rhn_sync(self, repo): """ Handle mirroring of RHN repos. """ repo_mirror = repo.mirror # FIXME? warn about not having yum-utils. We don't want to require it in the package because # RHEL4 and RHEL5U0 don't have it. if not os.path.exists("/usr/bin/reposync"): utils.die(self.logger,"no /usr/bin/reposync found, please install yum-utils") cmd = "" # command to run has_rpm_list = False # flag indicating not to pull the whole repo # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # create yum config file for use by reposync # FIXME: don't hardcode dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path): # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) # how we invoke yum-utils depends on whether this is RHN content or not. # this is the somewhat more-complex RHN case. # NOTE: this requires that you have entitlements for the server and you give the mirror as rhn://$channelname if not repo.mirror_locally: utils.die("rhn:// repos do not work with --mirror-locally=1") if has_rpm_list: self.logger.warning("warning: --rpm-list is not supported for RHN content") rest = repo.mirror[6:] # everything after rhn:// cmd = "/usr/bin/reposync %s -r %s --download_path=%s" % (self.rflags, rest, "/var/www/cobbler/repo_mirror") if repo.name != rest: args = { "name" : repo.name, "rest" : rest } utils.die(self.logger,"ERROR: repository %(name)s needs to be renamed %(rest)s as the name of the cobbler repository must match the name of the RHN channel" % args) if repo.arch == "i386": # counter-intuitive, but we want the newish kernels too repo.arch = "i686" if repo.arch != "": cmd = "%s -a %s" % (cmd, repo.arch) # now regardless of whether we're doing yumdownloader or reposync # or whether the repo was http://, ftp://, or rhn://, execute all queued # commands here. Any failure at any point stops the operation. if repo.mirror_locally: rc = utils.subprocess_call(self.logger, cmd) # Don't die if reposync fails, it is logged # if rc !=0: # utils.die(self.logger,"cobbler reposync failed") # some more special case handling for RHN. # create the config file now, because the directory didn't exist earlier temp_file = self.create_local_file(temp_path, repo, output=False) # now run createrepo to rebuild the index if repo.mirror_locally: os.path.walk(dest_path, self.createrepo_walker, repo) # create the config file the hosts will use to access the repository. self.create_local_file(dest_path, repo) # ==================================================================================== def yum_sync(self, repo): """ Handle copying of http:// and ftp:// yum repos. """ repo_mirror = repo.mirror # warn about not having yum-utils. We don't want to require it in the package because # RHEL4 and RHEL5U0 don't have it. if not os.path.exists("/usr/bin/reposync"): utils.die(self.logger,"no /usr/bin/reposync found, please install yum-utils") cmd = "" # command to run has_rpm_list = False # flag indicating not to pull the whole repo # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # create yum config file for use by reposync dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path) and repo.mirror_locally: # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) # create the config file that yum will use for the copying if repo.mirror_locally: temp_file = self.create_local_file(temp_path, repo, output=False) if not has_rpm_list and repo.mirror_locally: # if we have not requested only certain RPMs, use reposync cmd = "/usr/bin/reposync %s --config=%s --repoid=%s --download_path=%s" % (self.rflags, temp_file, repo.name, "/var/www/cobbler/repo_mirror") if repo.arch != "": if repo.arch == "x86": repo.arch = "i386" # FIX potential arch errors if repo.arch == "i386": # counter-intuitive, but we want the newish kernels too cmd = "%s -a i686" % (cmd) else: cmd = "%s -a %s" % (cmd, repo.arch) elif repo.mirror_locally: # create the output directory if it doesn't exist if not os.path.exists(dest_path): os.makedirs(dest_path) use_source = "" if repo.arch == "src": use_source = "--source" # older yumdownloader sometimes explodes on --resolvedeps # if this happens to you, upgrade yum & yum-utils extra_flags = self.settings.yumdownloader_flags cmd = "/usr/bin/yumdownloader %s %s --disablerepo=* --enablerepo=%s -c %s --destdir=%s %s" % (extra_flags, use_source, repo.name, temp_file, dest_path, " ".join(repo.rpm_list)) # now regardless of whether we're doing yumdownloader or reposync # or whether the repo was http://, ftp://, or rhn://, execute all queued # commands here. Any failure at any point stops the operation. if repo.mirror_locally: rc = utils.subprocess_call(self.logger, cmd) if rc !=0: utils.die(self.logger,"cobbler reposync failed") repodata_path = os.path.join(dest_path, "repodata") if not os.path.exists("/usr/bin/wget"): utils.die(self.logger,"no /usr/bin/wget found, please install wget") # grab repomd.xml and use it to download any metadata we can use cmd2 = "/usr/bin/wget -q %s/repodata/repomd.xml -O %s/repomd.xml" % (repo_mirror, temp_path) rc = utils.subprocess_call(self.logger,cmd2) if rc == 0: # create our repodata directory now, as any extra metadata we're # about to download probably lives there if not os.path.isdir(repodata_path): os.makedirs(repodata_path) rmd = yum.repoMDObject.RepoMD('', "%s/repomd.xml" % (temp_path)) for mdtype in rmd.repoData.keys(): # don't download metadata files that are created by default if mdtype not in ["primary", "primary_db", "filelists", "filelists_db", "other", "other_db"]: mdfile = rmd.getData(mdtype).location[1] cmd3 = "/usr/bin/wget -q %s/%s -O %s/%s" % (repo_mirror, mdfile, dest_path, mdfile) utils.subprocess_call(self.logger,cmd3) if rc !=0: utils.die(self.logger,"wget failed") # now run createrepo to rebuild the index if repo.mirror_locally: os.path.walk(dest_path, self.createrepo_walker, repo) # create the config file the hosts will use to access the repository. self.create_local_file(dest_path, repo) # ==================================================================================== # def apt_sync(self, repo): # # """ # Handle copying of http:// and ftp:// debian repos. # """ # # repo_mirror = repo.mirror # # # warn about not having mirror program. # # mirror_program = "/usr/bin/debmirror" # if not os.path.exists(mirror_program): # utils.die(self.logger,"no %s found, please install it"%(mirror_program)) # # cmd = "" # command to run # has_rpm_list = False # flag indicating not to pull the whole repo # # # detect cases that require special handling # # if repo.rpm_list != "" and repo.rpm_list != []: # utils.die(self.logger,"has_rpm_list not yet supported on apt repos") # # if not repo.arch: # utils.die(self.logger,"Architecture is required for apt repositories") # # # built destination path for the repo # dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) # # if repo.mirror_locally: # mirror = repo.mirror.replace("@@suite@@",repo.os_version) # # idx = mirror.find("://") # method = mirror[:idx] # mirror = mirror[idx+3:] # # idx = mirror.find("/") # host = mirror[:idx] # mirror = mirror[idx+1:] # # idx = mirror.rfind("/dists/") # suite = mirror[idx+7:] # mirror = mirror[:idx] # # mirror_data = "--method=%s --host=%s --root=%s --dist=%s " % ( method , host , mirror , suite ) # # # FIXME : flags should come from repo instead of being hardcoded # # rflags = "--passive --nocleanup" # for x in repo.yumopts: # if repo.yumopts[x]: # rflags += " %s %s" % ( x , repo.yumopts[x] ) # else: # rflags += " %s" % x # cmd = "%s %s %s %s" % (mirror_program, rflags, mirror_data, dest_path) # if repo.arch == "src": # cmd = "%s --source" % cmd # else: # arch = repo.arch # if arch == "x86": # arch = "i386" # FIX potential arch errors # if arch == "x86_64": # arch = "amd64" # FIX potential arch errors # cmd = "%s --nosource -a %s" % (cmd, arch) # # rc = utils.subprocess_call(self.logger, cmd) # if rc !=0: # utils.die(self.logger,"cobbler reposync failed") # ================================================================================== def create_local_file(self, dest_path, repo, output=True): """ Creates Yum config files for use by reposync Two uses: (A) output=True, Create local files that can be used with yum on provisioned clients to make use of this mirror. (B) output=False, Create a temporary file for yum to feed into yum for mirroring """ # the output case will generate repo configuration files which are usable # for the installed systems. They need to be made compatible with --server-override # which means they are actually templates, which need to be rendered by a cobbler-sync # on per profile/system basis. if output: fname = os.path.join(dest_path,"config.repo") else: fname = os.path.join(dest_path, "%s.repo" % repo.name) self.logger.debug("creating: %s" % fname) if not os.path.exists(dest_path): utils.mkdir(dest_path) config_file = open(fname, "w+") config_file.write("[%s]\n" % repo.name) config_file.write("name=%s\n" % repo.name) optenabled = False optgpgcheck = False if output: if repo.mirror_locally: line = "baseurl=http://${server}/cobbler/repo_mirror/%s\n" % (repo.name) else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = "baseurl=%s\n" % mstr config_file.write(line) # user may have options specific to certain yum plugins # add them to the file for x in repo.yumopts: config_file.write("%s=%s\n" % (x, repo.yumopts[x])) if x == "enabled": optenabled = True if x == "gpgcheck": optgpgcheck = True else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = "baseurl=%s\n" % mstr if self.settings.http_port not in (80, '80'): http_server = "%s:%s" % (self.settings.server, self.settings.http_port) else: http_server = self.settings.server line = line.replace("@@server@@",http_server) config_file.write(line) if not optenabled: config_file.write("enabled=1\n") config_file.write("priority=%s\n" % repo.priority) # FIXME: potentially might want a way to turn this on/off on a per-repo basis if not optgpgcheck: config_file.write("gpgcheck=0\n") config_file.close() return fname # ================================================================================== def update_permissions(self, repo_path): """ Verifies that permissions and contexts after an rsync are as expected. Sending proper rsync flags should prevent the need for this, though this is largely a safeguard. """ # all_path = os.path.join(repo_path, "*") cmd1 = "chown -R root:apache %s" % repo_path utils.subprocess_call(self.logger, cmd1) cmd2 = "chmod -R 755 %s" % repo_path utils.subprocess_call(self.logger, cmd2)
colloquium/cobbler
cobbler/action_reposync.py
Python
gpl-2.0
22,241
<?php /** * Link Helper class: com_form2content.form * * @package Better Preview * @version 4.1.2PRO * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2015 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; include_once __DIR__ . '/helper.php'; class HelperBetterPreviewLinkForm2ContentForm extends HelperBetterPreviewLink { function getLinks() { $helper = new HelperBetterPreviewHelperForm2ContentForm($this->params); if (!$item = $helper->getArticle()) { return; } $parents = $helper->getArticleParents($item); return array_merge(array($item), $parents); } }
quanghung0404/it2tech
plugins/system/betterpreview/helpers/com_form2content/form/link.php
PHP
gpl-2.0
768
using System; using System.Drawing; using System.IO; using System.Linq; using System.Diagnostics; using System.Windows.Forms; using System.Threading; using System.Collections.Generic; using CurePlease.Properties; namespace CurePlease { using FFACETools; public partial class Form1 : Form { public static FFACE _FFACEPL; public FFACE _FFACEMonitored; public ListBox processids = new ListBox(); // Stores the previously-colored button, if any float plX; float plY; float plZ; byte playerOptionsSelected; byte autoOptionsSelected; bool castingLock = false; bool pauseActions = false; int castingSafetyPercentage = 100; private bool islowmp = false; //private Dictionary<int, string> PTMemberList; #region "== Auto Casting bool" bool[] autoHasteEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoHaste_IIEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoFlurryEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoFlurry_IIEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoPhalanx_IIEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoRegen_IVEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoRegen_VEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoShell_IVEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoShell_VEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoProtect_IVEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoProtect_VEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoRefreshEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; bool[] autoRefresh_IIEnabled = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }; #endregion #region "== Auto Casting DateTime" DateTime currentTime = DateTime.Now; DateTime[] playerHaste = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerHaste_II = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerFlurry = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerFlurry_II = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerShell_IV = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerShell_V = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerProtect_IV = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerProtect_V = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerPhalanx_II = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerRegen_IV = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerRegen_V = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerRefresh = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; DateTime[] playerRefresh_II = new DateTime[] { new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0), new DateTime(1970, 1, 1, 0, 0, 0) }; #endregion #region "== Auto Casting TimeSpan" TimeSpan[] playerHasteSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerHaste_IISpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerFlurrySpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerFlurry_IISpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerShell_IVSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerShell_VSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerProtect_IVSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerProtect_VSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerPhalanx_IISpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerRegen_IVSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerRegen_VSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerRefreshSpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; TimeSpan[] playerRefresh_IISpan = new TimeSpan[] { new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan(), new TimeSpan() }; #endregion #region "== Getting POL Process and FFACE dll Check" //FFXI Process public Form1() { InitializeComponent(); Process[] pol = Process.GetProcessesByName("pol"); if (pol.Length < 1) { MessageBox.Show("FFXI not found"); } else { for (int i = 0; i < pol.Length; i++) { POLID.Items.Add(pol[i].MainWindowTitle); POLID2.Items.Add(pol[i].MainWindowTitle); processids.Items.Add(pol[i].Id); } POLID.SelectedIndex = 0; POLID2.SelectedIndex = 0; processids.SelectedIndex = 0; } } private void setinstance_Click(object sender, EventArgs e) { if (!CheckForDLLFiles()) { MessageBox.Show( "Unable to locate FFACE.dll or FFACETools.dll\nMake sure both files are in the same directory as the application", "Error"); return; } processids.SelectedIndex = POLID.SelectedIndex; _FFACEPL = new FFACE((int)processids.SelectedItem); plLabel.Text = "Currently selected PL: " + _FFACEPL.Player.Name; plLabel.ForeColor = Color.Green; POLID.BackColor = Color.White; plPosition.Enabled = true; setinstance2.Enabled = true; } private void setinstance2_Click(object sender, EventArgs e) { if (!CheckForDLLFiles()) { MessageBox.Show( "Unable to locate FFACE.dll or FFACETools.dll\nMake sure both files are in the same directory as the application", "Error"); return; } processids.SelectedIndex = POLID2.SelectedIndex; _FFACEMonitored = new FFACE((int)processids.SelectedItem); monitoredLabel.Text = "Currently monitoring: " + _FFACEMonitored.Player.Name; monitoredLabel.ForeColor = Color.Green; POLID2.BackColor = Color.White; partyMembersUpdate.Enabled = true; actionTimer.Enabled = true; pauseButton.Enabled = true; hpUpdates.Enabled = true; } private bool CheckForDLLFiles() { if (!File.Exists("fface.dll") || !File.Exists("ffacetools.dll")) { return false; } return true; } #endregion #region "== partyMemberUpdate" private bool partyMemberUpdateMethod(byte partyMemberId) { if (_FFACEMonitored.PartyMember[partyMemberId].Active) { if (_FFACEPL.Player.Zone == _FFACEMonitored.PartyMember[partyMemberId].Zone) return true; return false; } return false; } private void partyMembersUpdate_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus == LoginStatus.Loading || _FFACEMonitored.Player.GetLoginStatus == LoginStatus.Loading) { // We zoned out so wait 15 seconds before continuing any type of action Thread.Sleep(15000); } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } if (partyMemberUpdateMethod(0)) { player0.Text = _FFACEMonitored.PartyMember[0].Name; player0.Enabled = true; player0optionsButton.Enabled = true; player0buffsButton.Enabled = true; } else { player0.Text = "Inactive or out of zone"; player0.Enabled = false; player0HP.Value = 0; player0optionsButton.Enabled = false; player0buffsButton.Enabled = false; } if (partyMemberUpdateMethod(1)) { player1.Text = _FFACEMonitored.PartyMember[1].Name; player1.Enabled = true; player1optionsButton.Enabled = true; player1buffsButton.Enabled = true; } else { player1.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player1.Enabled = false; player1HP.Value = 0; player1optionsButton.Enabled = false; player1buffsButton.Enabled = false; } if (partyMemberUpdateMethod(2)) { player2.Text = _FFACEMonitored.PartyMember[2].Name; player2.Enabled = true; player2optionsButton.Enabled = true; player2buffsButton.Enabled = true; } else { player2.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player2.Enabled = false; player2HP.Value = 0; player2optionsButton.Enabled = false; player2buffsButton.Enabled = false; } if (partyMemberUpdateMethod(3)) { player3.Text = _FFACEMonitored.PartyMember[3].Name; player3.Enabled = true; player3optionsButton.Enabled = true; player3buffsButton.Enabled = true; } else { player3.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player3.Enabled = false; player3HP.Value = 0; player3optionsButton.Enabled = false; player3buffsButton.Enabled = false; } if (partyMemberUpdateMethod(4)) { player4.Text = _FFACEMonitored.PartyMember[4].Name; player4.Enabled = true; player4optionsButton.Enabled = true; player4buffsButton.Enabled = true; } else { player4.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player4.Enabled = false; player4HP.Value = 0; player4optionsButton.Enabled = false; player4buffsButton.Enabled = false; } if (partyMemberUpdateMethod(5)) { player5.Text = _FFACEMonitored.PartyMember[5].Name; player5.Enabled = true; player5optionsButton.Enabled = true; player5buffsButton.Enabled = true; } else { player5.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player5.Enabled = false; player5HP.Value = 0; player5optionsButton.Enabled = false; player5buffsButton.Enabled = false; } if (partyMemberUpdateMethod(6)) { player6.Text = _FFACEMonitored.PartyMember[6].Name; player6.Enabled = true; player6optionsButton.Enabled = true; } else { player6.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player6.Enabled = false; player6HP.Value = 0; player6optionsButton.Enabled = false; } if (partyMemberUpdateMethod(7)) { player7.Text = _FFACEMonitored.PartyMember[7].Name; player7.Enabled = true; player7optionsButton.Enabled = true; } else { player7.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player7.Enabled = false; player7HP.Value = 0; player7optionsButton.Enabled = false; } if (partyMemberUpdateMethod(8)) { player8.Text = _FFACEMonitored.PartyMember[8].Name; player8.Enabled = true; player8optionsButton.Enabled = true; } else { player8.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player8.Enabled = false; player8HP.Value = 0; player8optionsButton.Enabled = false; } if (partyMemberUpdateMethod(9)) { player9.Text = _FFACEMonitored.PartyMember[9].Name; player9.Enabled = true; player9optionsButton.Enabled = true; } else { player9.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player9.Enabled = false; player9HP.Value = 0; player9optionsButton.Enabled = false; } if (partyMemberUpdateMethod(10)) { player10.Text = _FFACEMonitored.PartyMember[10].Name; player10.Enabled = true; player10optionsButton.Enabled = true; } else { player10.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player10.Enabled = false; player10HP.Value = 0; player10optionsButton.Enabled = false; } if (partyMemberUpdateMethod(11)) { player11.Text = _FFACEMonitored.PartyMember[11].Name; player11.Enabled = true; player11optionsButton.Enabled = true; } else { player11.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player11.Enabled = false; player11HP.Value = 0; player11optionsButton.Enabled = false; } if (partyMemberUpdateMethod(12)) { player12.Text = _FFACEMonitored.PartyMember[12].Name; player12.Enabled = true; player12optionsButton.Enabled = true; } else { player12.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player12.Enabled = false; player12HP.Value = 0; player12optionsButton.Enabled = false; } if (partyMemberUpdateMethod(13)) { player13.Text = _FFACEMonitored.PartyMember[13].Name; player13.Enabled = true; player13optionsButton.Enabled = true; } else { player13.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player13.Enabled = false; player13HP.Value = 0; player13optionsButton.Enabled = false; } if (partyMemberUpdateMethod(14)) { player14.Text = _FFACEMonitored.PartyMember[14].Name; player14.Enabled = true; player14optionsButton.Enabled = true; } else { player14.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player14.Enabled = false; player14HP.Value = 0; player14optionsButton.Enabled = false; } if (partyMemberUpdateMethod(15)) { player15.Text = _FFACEMonitored.PartyMember[15].Name; player15.Enabled = true; player15optionsButton.Enabled = true; } else { player15.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player15.Enabled = false; player15HP.Value = 0; player15optionsButton.Enabled = false; } if (partyMemberUpdateMethod(16)) { player16.Text = _FFACEMonitored.PartyMember[16].Name; player16.Enabled = true; player16optionsButton.Enabled = true; } else { player16.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player16.Enabled = false; player16HP.Value = 0; player16optionsButton.Enabled = false; } if (partyMemberUpdateMethod(17)) { player17.Text = _FFACEMonitored.PartyMember[17].Name; player17.Enabled = true; player17optionsButton.Enabled = true; } else { player17.Text = Resources.Form1_partyMembersUpdate_Tick_Inactive; player17.Enabled = false; player17HP.Value = 0; player17optionsButton.Enabled = false; } } #endregion #region "== hpUpdates" private void hpUpdates_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } if (player0.Enabled) UpdateHPProgressBar(player0HP, _FFACEMonitored.PartyMember[0].HPPCurrent); if (player0.Enabled) UpdateHPProgressBar(player0HP, _FFACEMonitored.PartyMember[0].HPPCurrent); if (player1.Enabled) UpdateHPProgressBar(player1HP, _FFACEMonitored.PartyMember[1].HPPCurrent); if (player2.Enabled) UpdateHPProgressBar(player2HP, _FFACEMonitored.PartyMember[2].HPPCurrent); if (player3.Enabled) UpdateHPProgressBar(player3HP, _FFACEMonitored.PartyMember[3].HPPCurrent); if (player4.Enabled) UpdateHPProgressBar(player4HP, _FFACEMonitored.PartyMember[4].HPPCurrent); if (player5.Enabled) UpdateHPProgressBar(player5HP, _FFACEMonitored.PartyMember[5].HPPCurrent); if (player6.Enabled) UpdateHPProgressBar(player6HP, _FFACEMonitored.PartyMember[6].HPPCurrent); if (player7.Enabled) UpdateHPProgressBar(player7HP, _FFACEMonitored.PartyMember[7].HPPCurrent); if (player8.Enabled) UpdateHPProgressBar(player8HP, _FFACEMonitored.PartyMember[8].HPPCurrent); if (player9.Enabled) UpdateHPProgressBar(player9HP, _FFACEMonitored.PartyMember[9].HPPCurrent); if (player10.Enabled) UpdateHPProgressBar(player10HP, _FFACEMonitored.PartyMember[10].HPPCurrent); if (player11.Enabled) UpdateHPProgressBar(player11HP, _FFACEMonitored.PartyMember[11].HPPCurrent); if (player12.Enabled) UpdateHPProgressBar(player12HP, _FFACEMonitored.PartyMember[12].HPPCurrent); if (player13.Enabled) UpdateHPProgressBar(player13HP, _FFACEMonitored.PartyMember[13].HPPCurrent); if (player14.Enabled) UpdateHPProgressBar(player14HP, _FFACEMonitored.PartyMember[14].HPPCurrent); if (player15.Enabled) UpdateHPProgressBar(player15HP, _FFACEMonitored.PartyMember[15].HPPCurrent); if (player16.Enabled) UpdateHPProgressBar(player16HP, _FFACEMonitored.PartyMember[16].HPPCurrent); if (player17.Enabled) UpdateHPProgressBar(player17HP, _FFACEMonitored.PartyMember[17].HPPCurrent); label1.Text = _FFACEPL.Item.SelectedItemID.ToString() + ": " + _FFACEPL.Item.SelectedItemName; } #endregion #region "== UpdateHPProgressBar" private void UpdateHPProgressBar(NewProgressBar playerHP, int hppCurrent) { playerHP.Value = hppCurrent; if (hppCurrent >= 75) playerHP.ForeColor = Color.Green; else if (hppCurrent > 50 && hppCurrent < 75) playerHP.ForeColor = Color.Yellow; else if (hppCurrent > 25 && hppCurrent < 50) playerHP.ForeColor = Color.Orange; else if (hppCurrent < 25) playerHP.ForeColor = Color.Red; } #endregion #region "== plPosition (Power Levelers Position)" private void plPosition_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } plX = _FFACEPL.Player.PosX; plY = _FFACEPL.Player.PosY; plZ = _FFACEPL.Player.PosZ; } #endregion #region "== CastLock" private void CastLockMethod() { castingLock = true; castingLockLabel.Text = "Casting is LOCKED"; castingLockTimer.Enabled = true; actionTimer.Enabled = false; } #endregion #region "== ActionLock" private void ActionLockMethod() { castingLock = true; castingLockLabel.Text = "Casting is LOCKED"; actionUnlockTimer.Enabled = true; actionTimer.Enabled = false; } #endregion #region "== CureCalculator" private void CureCalculator(byte partyMemberId) { if ((Settings.Default.cure6enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure6amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure_VI) == 0) && (_FFACEPL.Player.MPCurrent > 227)) { _FFACEPL.Windower.SendString("/ma \"Cure VI\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } else if ((Settings.Default.cure5enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure5amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure_V) == 0) && (_FFACEPL.Player.MPCurrent > 125)) { _FFACEPL.Windower.SendString("/ma \"Cure V\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } else if ((Settings.Default.cure4enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure4amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure_IV) == 0) && (_FFACEPL.Player.MPCurrent > 88)) { _FFACEPL.Windower.SendString("/ma \"Cure IV\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } else if ((Settings.Default.cure3enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure3amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure_III) == 0) && (_FFACEPL.Player.MPCurrent > 46)) { _FFACEPL.Windower.SendString("/ma \"Cure III\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } else if ((Settings.Default.cure2enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure2amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure_II) == 0) && (_FFACEPL.Player.MPCurrent > 24)) { _FFACEPL.Windower.SendString("/ma \"Cure II\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } else if ((Settings.Default.cure1enabled) && ((((_FFACEMonitored.PartyMember[partyMemberId].HPCurrent * 100) / _FFACEMonitored.PartyMember[partyMemberId].HPPCurrent) - _FFACEMonitored.PartyMember[partyMemberId].HPCurrent) >= Settings.Default.cure1amount) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cure) == 0) && (_FFACEPL.Player.MPCurrent > 8)) { _FFACEPL.Windower.SendString("/ma \"Cure\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); CastLockMethod(); } } #endregion #region "== CastingPossible (Distance)" private bool castingPossible(byte partyMemberId) { if ((_FFACEPL.NPC.Distance(_FFACEMonitored.PartyMember[partyMemberId].ID) < 21) && (_FFACEPL.NPC.Distance(_FFACEMonitored.PartyMember[partyMemberId].ID) > 0) && (_FFACEMonitored.PartyMember[partyMemberId].HPCurrent > 0) || (_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[partyMemberId].ID) && (_FFACEMonitored.PartyMember[partyMemberId].HPCurrent > 0)) { return true; } return false; } #endregion #region "== PL and Monitored StatusCheck" private bool plStatusCheck(StatusEffect requestedStatus) { bool statusFound = false; foreach (StatusEffect status in _FFACEPL.Player.StatusEffects) { if (requestedStatus == status) { statusFound = true; } } return statusFound; } private bool monitoredStatusCheck(StatusEffect requestedStatus) { bool statusFound = false; foreach (StatusEffect status in _FFACEMonitored.Player.StatusEffects) { if (requestedStatus == status) { statusFound = true; } } return statusFound; } #endregion #region "== partyMember Spell Casting (Auto Spells) private void castSpell(string partyMemberName, string spellName) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"" + spellName + "\" " + partyMemberName); } private void hastePlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Haste\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerHaste[partyMemberId] = DateTime.Now; } private void haste_IIPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Haste II\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerHaste_II[partyMemberId] = DateTime.Now; } private void FlurryPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Flurry\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerFlurry[partyMemberId] = DateTime.Now; } private void Flurry_IIPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Flurry II\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerFlurry_II[partyMemberId] = DateTime.Now; } private void Phalanx_IIPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Phalanx II\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerPhalanx_II[partyMemberId] = DateTime.Now; } private void Regen_IVPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Regen IV\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerRegen_IV[partyMemberId] = DateTime.Now; } private void Regen_VPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Regen V\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerRegen_V[partyMemberId] = DateTime.Now; } private void RefreshPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Refresh\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerRefresh[partyMemberId] = DateTime.Now; } private void Refresh_IIPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Refresh II\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerRefresh_II[partyMemberId] = DateTime.Now; } private void protect_IVPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Protect IV\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerProtect_IV[partyMemberId] = DateTime.Now; } private void protect_VPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Protect V\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerProtect_V[partyMemberId] = DateTime.Now; } private void shell_IVPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Shell IV\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerShell_IV[partyMemberId] = DateTime.Now; } private void shell_VPlayer(byte partyMemberId) { CastLockMethod(); _FFACEPL.Windower.SendString("/ma \"Shell V\" " + _FFACEMonitored.PartyMember[partyMemberId].Name); playerShell_V[partyMemberId] = DateTime.Now; } #endregion #region "== actionTimer (LoginStatus)" private void actionTimer_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } if (_FFACEPL.Player.GetLoginStatus == LoginStatus.Loading || _FFACEMonitored.Player.GetLoginStatus == LoginStatus.Loading) { // We zoned out so wait 15 seconds before continuing any type of action Thread.Sleep(15000); } #endregion // Grab current time for calculations below #region "== Calculate time since an Auto Spell was cast on particular player" currentTime = DateTime.Now; // Calculate time since haste was cast on particular player playerHasteSpan[0] = currentTime.Subtract(playerHaste[0]); playerHasteSpan[1] = currentTime.Subtract(playerHaste[1]); playerHasteSpan[2] = currentTime.Subtract(playerHaste[2]); playerHasteSpan[3] = currentTime.Subtract(playerHaste[3]); playerHasteSpan[4] = currentTime.Subtract(playerHaste[4]); playerHasteSpan[5] = currentTime.Subtract(playerHaste[5]); playerHasteSpan[6] = currentTime.Subtract(playerHaste[6]); playerHasteSpan[7] = currentTime.Subtract(playerHaste[7]); playerHasteSpan[8] = currentTime.Subtract(playerHaste[8]); playerHasteSpan[9] = currentTime.Subtract(playerHaste[9]); playerHasteSpan[10] = currentTime.Subtract(playerHaste[10]); playerHasteSpan[11] = currentTime.Subtract(playerHaste[11]); playerHasteSpan[12] = currentTime.Subtract(playerHaste[12]); playerHasteSpan[13] = currentTime.Subtract(playerHaste[13]); playerHasteSpan[14] = currentTime.Subtract(playerHaste[14]); playerHasteSpan[15] = currentTime.Subtract(playerHaste[15]); playerHasteSpan[16] = currentTime.Subtract(playerHaste[16]); playerHasteSpan[17] = currentTime.Subtract(playerHaste[17]); playerHaste_IISpan[0] = currentTime.Subtract(playerHaste_II[0]); playerHaste_IISpan[1] = currentTime.Subtract(playerHaste_II[1]); playerHaste_IISpan[2] = currentTime.Subtract(playerHaste_II[2]); playerHaste_IISpan[3] = currentTime.Subtract(playerHaste_II[3]); playerHaste_IISpan[4] = currentTime.Subtract(playerHaste_II[4]); playerHaste_IISpan[5] = currentTime.Subtract(playerHaste_II[5]); playerHaste_IISpan[6] = currentTime.Subtract(playerHaste_II[6]); playerHaste_IISpan[7] = currentTime.Subtract(playerHaste_II[7]); playerHaste_IISpan[8] = currentTime.Subtract(playerHaste_II[8]); playerHaste_IISpan[9] = currentTime.Subtract(playerHaste_II[9]); playerHaste_IISpan[10] = currentTime.Subtract(playerHaste_II[10]); playerHaste_IISpan[11] = currentTime.Subtract(playerHaste_II[11]); playerHaste_IISpan[12] = currentTime.Subtract(playerHaste_II[12]); playerHaste_IISpan[13] = currentTime.Subtract(playerHaste_II[13]); playerHaste_IISpan[14] = currentTime.Subtract(playerHaste_II[14]); playerHaste_IISpan[15] = currentTime.Subtract(playerHaste_II[15]); playerHaste_IISpan[16] = currentTime.Subtract(playerHaste_II[16]); playerHaste_IISpan[17] = currentTime.Subtract(playerHaste_II[17]); playerFlurrySpan[0] = currentTime.Subtract(playerFlurry[0]); playerFlurrySpan[1] = currentTime.Subtract(playerFlurry[1]); playerFlurrySpan[2] = currentTime.Subtract(playerFlurry[2]); playerFlurrySpan[3] = currentTime.Subtract(playerFlurry[3]); playerFlurrySpan[4] = currentTime.Subtract(playerFlurry[4]); playerFlurrySpan[5] = currentTime.Subtract(playerFlurry[5]); playerFlurrySpan[6] = currentTime.Subtract(playerFlurry[6]); playerFlurrySpan[7] = currentTime.Subtract(playerFlurry[7]); playerFlurrySpan[8] = currentTime.Subtract(playerFlurry[8]); playerFlurrySpan[9] = currentTime.Subtract(playerFlurry[9]); playerFlurrySpan[10] = currentTime.Subtract(playerFlurry[10]); playerFlurrySpan[11] = currentTime.Subtract(playerFlurry[11]); playerFlurrySpan[12] = currentTime.Subtract(playerFlurry[12]); playerFlurrySpan[13] = currentTime.Subtract(playerFlurry[13]); playerFlurrySpan[14] = currentTime.Subtract(playerFlurry[14]); playerFlurrySpan[15] = currentTime.Subtract(playerFlurry[15]); playerFlurrySpan[16] = currentTime.Subtract(playerFlurry[16]); playerFlurrySpan[17] = currentTime.Subtract(playerFlurry[17]); playerFlurry_IISpan[0] = currentTime.Subtract(playerFlurry_II[0]); playerFlurry_IISpan[1] = currentTime.Subtract(playerFlurry_II[1]); playerFlurry_IISpan[2] = currentTime.Subtract(playerFlurry_II[2]); playerFlurry_IISpan[3] = currentTime.Subtract(playerFlurry_II[3]); playerFlurry_IISpan[4] = currentTime.Subtract(playerFlurry_II[4]); playerFlurry_IISpan[5] = currentTime.Subtract(playerFlurry_II[5]); playerFlurry_IISpan[6] = currentTime.Subtract(playerFlurry_II[6]); playerFlurry_IISpan[7] = currentTime.Subtract(playerFlurry_II[7]); playerFlurry_IISpan[8] = currentTime.Subtract(playerFlurry_II[8]); playerFlurry_IISpan[9] = currentTime.Subtract(playerFlurry_II[9]); playerFlurry_IISpan[10] = currentTime.Subtract(playerFlurry_II[10]); playerFlurry_IISpan[11] = currentTime.Subtract(playerFlurry_II[11]); playerFlurry_IISpan[12] = currentTime.Subtract(playerFlurry_II[12]); playerFlurry_IISpan[13] = currentTime.Subtract(playerFlurry_II[13]); playerFlurry_IISpan[14] = currentTime.Subtract(playerFlurry_II[14]); playerFlurry_IISpan[15] = currentTime.Subtract(playerFlurry_II[15]); playerFlurry_IISpan[16] = currentTime.Subtract(playerFlurry_II[16]); playerFlurry_IISpan[17] = currentTime.Subtract(playerFlurry_II[17]); // Calculate time since protect IV was cast on particular player playerProtect_IVSpan[0] = currentTime.Subtract(playerProtect_IV[0]); playerProtect_IVSpan[1] = currentTime.Subtract(playerProtect_IV[1]); playerProtect_IVSpan[2] = currentTime.Subtract(playerProtect_IV[2]); playerProtect_IVSpan[3] = currentTime.Subtract(playerProtect_IV[3]); playerProtect_IVSpan[4] = currentTime.Subtract(playerProtect_IV[4]); playerProtect_IVSpan[5] = currentTime.Subtract(playerProtect_IV[5]); playerProtect_IVSpan[6] = currentTime.Subtract(playerProtect_IV[6]); playerProtect_IVSpan[7] = currentTime.Subtract(playerProtect_IV[7]); playerProtect_IVSpan[8] = currentTime.Subtract(playerProtect_IV[8]); playerProtect_IVSpan[9] = currentTime.Subtract(playerProtect_IV[9]); playerProtect_IVSpan[10] = currentTime.Subtract(playerProtect_IV[10]); playerProtect_IVSpan[11] = currentTime.Subtract(playerProtect_IV[11]); playerProtect_IVSpan[12] = currentTime.Subtract(playerProtect_IV[12]); playerProtect_IVSpan[13] = currentTime.Subtract(playerProtect_IV[13]); playerProtect_IVSpan[14] = currentTime.Subtract(playerProtect_IV[14]); playerProtect_IVSpan[15] = currentTime.Subtract(playerProtect_IV[15]); playerProtect_IVSpan[16] = currentTime.Subtract(playerProtect_IV[16]); playerProtect_IVSpan[17] = currentTime.Subtract(playerProtect_IV[17]); // Calculate time since protect V was cast on particular player playerProtect_VSpan[0] = currentTime.Subtract(playerProtect_V[0]); playerProtect_VSpan[1] = currentTime.Subtract(playerProtect_V[1]); playerProtect_VSpan[2] = currentTime.Subtract(playerProtect_V[2]); playerProtect_VSpan[3] = currentTime.Subtract(playerProtect_V[3]); playerProtect_VSpan[4] = currentTime.Subtract(playerProtect_V[4]); playerProtect_VSpan[5] = currentTime.Subtract(playerProtect_V[5]); playerProtect_VSpan[6] = currentTime.Subtract(playerProtect_V[6]); playerProtect_VSpan[7] = currentTime.Subtract(playerProtect_V[7]); playerProtect_VSpan[8] = currentTime.Subtract(playerProtect_V[8]); playerProtect_VSpan[9] = currentTime.Subtract(playerProtect_V[9]); playerProtect_VSpan[10] = currentTime.Subtract(playerProtect_V[10]); playerProtect_VSpan[11] = currentTime.Subtract(playerProtect_V[11]); playerProtect_VSpan[12] = currentTime.Subtract(playerProtect_V[12]); playerProtect_VSpan[13] = currentTime.Subtract(playerProtect_V[13]); playerProtect_VSpan[14] = currentTime.Subtract(playerProtect_V[14]); playerProtect_VSpan[15] = currentTime.Subtract(playerProtect_V[15]); playerProtect_VSpan[16] = currentTime.Subtract(playerProtect_V[16]); playerProtect_VSpan[17] = currentTime.Subtract(playerProtect_V[17]); // Calculate time since shell IV was cast on particular player playerShell_IVSpan[0] = currentTime.Subtract(playerShell_IV[0]); playerShell_IVSpan[1] = currentTime.Subtract(playerShell_IV[1]); playerShell_IVSpan[2] = currentTime.Subtract(playerShell_IV[2]); playerShell_IVSpan[3] = currentTime.Subtract(playerShell_IV[3]); playerShell_IVSpan[4] = currentTime.Subtract(playerShell_IV[4]); playerShell_IVSpan[5] = currentTime.Subtract(playerShell_IV[5]); playerShell_IVSpan[6] = currentTime.Subtract(playerShell_IV[6]); playerShell_IVSpan[7] = currentTime.Subtract(playerShell_IV[7]); playerShell_IVSpan[8] = currentTime.Subtract(playerShell_IV[8]); playerShell_IVSpan[9] = currentTime.Subtract(playerShell_IV[9]); playerShell_IVSpan[10] = currentTime.Subtract(playerShell_IV[10]); playerShell_IVSpan[11] = currentTime.Subtract(playerShell_IV[11]); playerShell_IVSpan[12] = currentTime.Subtract(playerShell_IV[12]); playerShell_IVSpan[13] = currentTime.Subtract(playerShell_IV[13]); playerShell_IVSpan[14] = currentTime.Subtract(playerShell_IV[14]); playerShell_IVSpan[15] = currentTime.Subtract(playerShell_IV[15]); playerShell_IVSpan[16] = currentTime.Subtract(playerShell_IV[16]); playerShell_IVSpan[17] = currentTime.Subtract(playerShell_IV[17]); // Calculate time since shell V was cast on particular player playerShell_VSpan[0] = currentTime.Subtract(playerShell_V[0]); playerShell_VSpan[1] = currentTime.Subtract(playerShell_V[1]); playerShell_VSpan[2] = currentTime.Subtract(playerShell_V[2]); playerShell_VSpan[3] = currentTime.Subtract(playerShell_V[3]); playerShell_VSpan[4] = currentTime.Subtract(playerShell_V[4]); playerShell_VSpan[5] = currentTime.Subtract(playerShell_V[5]); playerShell_VSpan[6] = currentTime.Subtract(playerShell_V[6]); playerShell_VSpan[7] = currentTime.Subtract(playerShell_V[7]); playerShell_VSpan[8] = currentTime.Subtract(playerShell_V[8]); playerShell_VSpan[9] = currentTime.Subtract(playerShell_V[9]); playerShell_VSpan[10] = currentTime.Subtract(playerShell_V[10]); playerShell_VSpan[11] = currentTime.Subtract(playerShell_V[11]); playerShell_VSpan[12] = currentTime.Subtract(playerShell_V[12]); playerShell_VSpan[13] = currentTime.Subtract(playerShell_V[13]); playerShell_VSpan[14] = currentTime.Subtract(playerShell_V[14]); playerShell_VSpan[15] = currentTime.Subtract(playerShell_V[15]); playerShell_VSpan[16] = currentTime.Subtract(playerShell_V[16]); playerShell_VSpan[17] = currentTime.Subtract(playerShell_V[17]); // Calculate time since phalanx II was cast on particular player playerPhalanx_IISpan[0] = currentTime.Subtract(playerPhalanx_II[0]); playerPhalanx_IISpan[1] = currentTime.Subtract(playerPhalanx_II[1]); playerPhalanx_IISpan[2] = currentTime.Subtract(playerPhalanx_II[2]); playerPhalanx_IISpan[3] = currentTime.Subtract(playerPhalanx_II[3]); playerPhalanx_IISpan[4] = currentTime.Subtract(playerPhalanx_II[4]); playerPhalanx_IISpan[5] = currentTime.Subtract(playerPhalanx_II[5]); // Calculate time since regen IV was cast on particular player playerRegen_IVSpan[0] = currentTime.Subtract(playerRegen_IV[0]); playerRegen_IVSpan[1] = currentTime.Subtract(playerRegen_IV[1]); playerRegen_IVSpan[2] = currentTime.Subtract(playerRegen_IV[2]); playerRegen_IVSpan[3] = currentTime.Subtract(playerRegen_IV[3]); playerRegen_IVSpan[4] = currentTime.Subtract(playerRegen_IV[4]); playerRegen_IVSpan[5] = currentTime.Subtract(playerRegen_IV[5]); // Calculate time since regen V was cast on particular player playerRegen_VSpan[0] = currentTime.Subtract(playerRegen_V[0]); playerRegen_VSpan[1] = currentTime.Subtract(playerRegen_V[1]); playerRegen_VSpan[2] = currentTime.Subtract(playerRegen_V[2]); playerRegen_VSpan[3] = currentTime.Subtract(playerRegen_V[3]); playerRegen_VSpan[4] = currentTime.Subtract(playerRegen_V[4]); playerRegen_VSpan[5] = currentTime.Subtract(playerRegen_V[5]); // Calculate time since Refresh was cast on particular player playerRefreshSpan[0] = currentTime.Subtract(playerRefresh[0]); playerRefreshSpan[1] = currentTime.Subtract(playerRefresh[1]); playerRefreshSpan[2] = currentTime.Subtract(playerRefresh[2]); playerRefreshSpan[3] = currentTime.Subtract(playerRefresh[3]); playerRefreshSpan[4] = currentTime.Subtract(playerRefresh[4]); playerRefreshSpan[5] = currentTime.Subtract(playerRefresh[5]); // Calculate time since Refresh II was cast on particular player playerRefresh_IISpan[0] = currentTime.Subtract(playerRefresh_II[0]); playerRefresh_IISpan[1] = currentTime.Subtract(playerRefresh_II[1]); playerRefresh_IISpan[2] = currentTime.Subtract(playerRefresh_II[2]); playerRefresh_IISpan[3] = currentTime.Subtract(playerRefresh_II[3]); playerRefresh_IISpan[4] = currentTime.Subtract(playerRefresh_II[4]); playerRefresh_IISpan[5] = currentTime.Subtract(playerRefresh_II[5]); #endregion #region "== Set array values for GUI (Enabled) Checkboxes" // Set array values for GUI "Enabled" checkboxes CheckBox[] enabledBoxes = new CheckBox[18]; enabledBoxes[0] = player0enabled; enabledBoxes[1] = player1enabled; enabledBoxes[2] = player2enabled; enabledBoxes[3] = player3enabled; enabledBoxes[4] = player4enabled; enabledBoxes[5] = player5enabled; enabledBoxes[6] = player6enabled; enabledBoxes[7] = player7enabled; enabledBoxes[8] = player8enabled; enabledBoxes[9] = player9enabled; enabledBoxes[10] = player10enabled; enabledBoxes[11] = player11enabled; enabledBoxes[12] = player12enabled; enabledBoxes[13] = player13enabled; enabledBoxes[14] = player14enabled; enabledBoxes[15] = player15enabled; enabledBoxes[16] = player16enabled; enabledBoxes[17] = player17enabled; #endregion #region "== Set array values for GUI (High Priority) Checkboxes" // Set array values for GUI "High Priority" checkboxes CheckBox[] highPriorityBoxes = new CheckBox[18]; highPriorityBoxes[0] = player0priority; highPriorityBoxes[1] = player1priority; highPriorityBoxes[2] = player2priority; highPriorityBoxes[3] = player3priority; highPriorityBoxes[4] = player4priority; highPriorityBoxes[5] = player5priority; highPriorityBoxes[6] = player6priority; highPriorityBoxes[7] = player7priority; highPriorityBoxes[8] = player8priority; highPriorityBoxes[9] = player9priority; highPriorityBoxes[10] = player10priority; highPriorityBoxes[11] = player11priority; highPriorityBoxes[12] = player12priority; highPriorityBoxes[13] = player13priority; highPriorityBoxes[14] = player14priority; highPriorityBoxes[15] = player15priority; highPriorityBoxes[16] = player16priority; highPriorityBoxes[17] = player17priority; #endregion #region "== Job ability Divine Seal and Convert" if (Settings.Default.divineSealBox && _FFACEPL.Player.MPPCurrent <= 11 // && _FFACEPL.Timer.GetAbilityRecast(AbilityList.Divine_Seal) == 0 && !_FFACEPL.Player.StatusEffects.Contains(StatusEffect.Weakness)) { Thread.Sleep(3000); _FFACEPL.Windower.SendString("/ja \"Divine Seal\" <me>"); ActionLockMethod(); } else if (Settings.Default.Convert && _FFACEPL.Player.MPPCurrent <= 10 // && _FFACEPL.Timer.GetAbilityRecast(AbilityList.Convert) == 0 && !_FFACEPL.Player.StatusEffects.Contains(StatusEffect.Weakness)) { Thread.Sleep(1000); _FFACEPL.Windower.SendString("/ja \"Convert\" <me>"); return; //ActionLockMethod(); } #endregion #region "== Low MP Tell / MP OK Tell" if (_FFACEPL.Player.MPCurrent <= (int)Settings.Default.mpMinCastValue && _FFACEPL.Player.MPCurrent != 0) { if (Settings.Default.lowMPcheckBox && !islowmp) { _FFACEPL.Windower.SendString("/tell " + _FFACEMonitored.Player.Name + " MP is low!"); islowmp = true; return; } islowmp = true; return; } if (_FFACEPL.Player.MPCurrent > (int)Settings.Default.mpMinCastValue && _FFACEPL.Player.MPCurrent != 0) { if (Settings.Default.lowMPcheckBox && islowmp) { _FFACEPL.Windower.SendString("/tell " + _FFACEMonitored.Player.Name + " MP OK!"); islowmp = false; } } #endregion #region "== PL stationary for Cures (Casting Possible)" // Only perform actions if PL is stationary if ((_FFACEPL.Player.PosX == plX) && (_FFACEPL.Player.PosY == plY) && (_FFACEPL.Player.PosZ == plZ) && (_FFACEPL.Player.GetLoginStatus == LoginStatus.LoggedIn) && (!pauseActions) && ((_FFACEPL.Player.Status == Status.Standing) || (_FFACEPL.Player.Status == Status.Fighting))) { var playerHpOrder = _FFACEMonitored.PartyMember.Keys.OrderBy(k => _FFACEMonitored.PartyMember[k].HPPCurrent); // Loop through keys in order of lowest HP to highest HP foreach (byte id in playerHpOrder) { // Cures // First, is casting possible, and enabled? if (castingPossible(id) && (_FFACEMonitored.PartyMember[id].Active) && (enabledBoxes[id].Checked) && (_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (!castingLock)) { if ((highPriorityBoxes[id].Checked) && (_FFACEMonitored.PartyMember[id].HPPCurrent <= Settings.Default.priorityCurePercentage)) { CureCalculator(id); break; } if ((_FFACEMonitored.PartyMember[id].HPPCurrent <= Settings.Default.curePercentage) && (castingPossible(id))) { CureCalculator(id); break; } } } #endregion #region "== PL Debuff Removal with Spells or Items" // PL and Monitored Player Debuff Removal // Starting with PL foreach (StatusEffect plEffect in _FFACEPL.Player.StatusEffects) { if ((plEffect == StatusEffect.Silence) && (Settings.Default.plSilenceItemEnabled)) { // Check to make sure we have echo drops if (_FFACEPL.Item.GetInventoryItemCount((ushort)FFACE.ParseResources.GetItemId(Settings.Default.plSilenceItemString)) > 0 || _FFACEPL.Item.GetTempItemCount((ushort)FFACE.ParseResources.GetItemId(Settings.Default.plSilenceItemString)) > 0) { _FFACEPL.Windower.SendString(string.Format("/item \"{0}\" <me>", Settings.Default.plSilenceItemString)); Thread.Sleep(2000); } } if ((plEffect == StatusEffect.Doom && Settings.Default.plDoomEnabled) /* Add more options from UI HERE*/) { // Check to make sure we have holy water if (_FFACEPL.Item.GetInventoryItemCount((ushort)FFACE.ParseResources.GetItemId(Settings.Default.PLDoomitem)) > 0 || _FFACEPL.Item.GetTempItemCount((ushort)FFACE.ParseResources.GetItemId(Settings.Default.PLDoomitem)) > 0) { _FFACEPL.Windower.SendString(string.Format("/item \"{0}\" <me>", Settings.Default.PLDoomitem)); Thread.Sleep(2000); } } else if ((plEffect == StatusEffect.Doom) && (Settings.Default.plDoom) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEPL.Player.Name, "Cursna"); } else if ((plEffect == StatusEffect.Paralysis) && (Settings.Default.plParalysis) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Paralyna) == 0)) { castSpell(_FFACEPL.Player.Name, "Paralyna"); } else if ((plEffect == StatusEffect.Poison) && (Settings.Default.plPoison) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Poisona) == 0)) { castSpell(_FFACEPL.Player.Name, "Poisona"); } else if ((plEffect == StatusEffect.Attack_Down) && (Settings.Default.plAttackDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Blindness) && (Settings.Default.plBlindness) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Blindna) == 0)) { castSpell(_FFACEPL.Player.Name, "Blindna"); } else if ((plEffect == StatusEffect.Bind) && (Settings.Default.plBind) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Weight) && (Settings.Default.plWeight) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Slow) && (Settings.Default.plSlow) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Curse) && (Settings.Default.plCurse) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEPL.Player.Name, "Cursna"); } else if ((plEffect == StatusEffect.Curse2) && (Settings.Default.plCurse2) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEPL.Player.Name, "Cursna"); } else if ((plEffect == StatusEffect.Addle) && (Settings.Default.plAddle) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Bane) && (Settings.Default.plBane) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEPL.Player.Name, "Cursna"); } else if ((plEffect == StatusEffect.Plague) && (Settings.Default.plPlague) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Viruna) == 0)) { castSpell(_FFACEPL.Player.Name, "Viruna"); } else if ((plEffect == StatusEffect.Disease) && (Settings.Default.plDisease) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Viruna) == 0)) { castSpell(_FFACEPL.Player.Name, "Viruna"); } else if ((plEffect == StatusEffect.Burn) && (Settings.Default.plBurn) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Frost) && (Settings.Default.plFrost) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Choke) && (Settings.Default.plChoke) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Rasp) && (Settings.Default.plRasp) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Shock) && (Settings.Default.plShock) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Drown) && (Settings.Default.plDrown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Dia) && (Settings.Default.plDia) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Bio) && (Settings.Default.plBio) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.STR_Down) && (Settings.Default.plStrDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.DEX_Down) && (Settings.Default.plDexDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.VIT_Down) && (Settings.Default.plVitDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.AGI_Down) && (Settings.Default.plAgiDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.INT_Down) && (Settings.Default.plIntDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.MND_Down) && (Settings.Default.plMndDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.CHR_Down) && (Settings.Default.plChrDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Max_HP_Down) && (Settings.Default.plMaxHpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Max_MP_Down) && (Settings.Default.plMaxMpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Accuracy_Down) && (Settings.Default.plAccuracyDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Evasion_Down) && (Settings.Default.plEvasionDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Defense_Down) && (Settings.Default.plDefenseDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Flash) && (Settings.Default.plFlash) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Magic_Acc_Down) && (Settings.Default.plMagicAccDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Magic_Atk_Down) && (Settings.Default.plMagicAtkDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Helix) && (Settings.Default.plHelix) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Max_TP_Down) && (Settings.Default.plMaxTpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Requiem) && (Settings.Default.plRequiem) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Elegy) && (Settings.Default.plElegy) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } else if ((plEffect == StatusEffect.Threnody) && (Settings.Default.plThrenody) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEPL.Player.Name, "Erase"); } } #endregion #region "== Monitored Player Debuff Removal" // Next, we check monitored player if ((_FFACEPL.NPC.Distance(_FFACEMonitored.Player.ID) < 21) && (_FFACEPL.NPC.Distance(_FFACEMonitored.Player.ID) > 0) && (_FFACEMonitored.Player.HPCurrent > 0)) { foreach (StatusEffect monitoredEffect in _FFACEMonitored.Player.StatusEffects) { if ((monitoredEffect == StatusEffect.Doom) && (Settings.Default.monitoredDoom) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Cursna"); } else if ((monitoredEffect == StatusEffect.Sleep) && (Settings.Default.monitoredSleep) && (Settings.Default.wakeSleepEnabled)) { castSpell(_FFACEMonitored.Player.Name, Settings.Default.wakeSleepSpellString); } else if ((monitoredEffect == StatusEffect.Sleep2) && (Settings.Default.monitoredSleep2) && (Settings.Default.wakeSleepEnabled)) { castSpell(_FFACEMonitored.Player.Name, Settings.Default.wakeSleepSpellString); } else if ((monitoredEffect == StatusEffect.Silence) && (Settings.Default.monitoredSilence) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Silena) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Silena"); } else if ((monitoredEffect == StatusEffect.Petrification) && (Settings.Default.monitoredPetrification) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Stona) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Stona"); } else if ((monitoredEffect == StatusEffect.Paralysis) && (Settings.Default.monitoredParalysis) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Paralyna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Paralyna"); } else if ((monitoredEffect == StatusEffect.Poison) && (Settings.Default.monitoredPoison) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Poisona) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Poisona"); } else if ((monitoredEffect == StatusEffect.Attack_Down) && (Settings.Default.monitoredAttackDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Blindness) && (Settings.Default.monitoredBlindness && (_FFACEPL.Timer.GetSpellRecast(SpellList.Blindna) == 0))) { castSpell(_FFACEMonitored.Player.Name, "Blindna"); } else if ((monitoredEffect == StatusEffect.Bind) && (Settings.Default.monitoredBind) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Weight) && (Settings.Default.monitoredWeight) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Slow) && (Settings.Default.monitoredSlow) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Curse) && (Settings.Default.monitoredCurse) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Cursna"); } else if ((monitoredEffect == StatusEffect.Curse2) && (Settings.Default.monitoredCurse2) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Cursna"); } else if ((monitoredEffect == StatusEffect.Addle) && (Settings.Default.monitoredAddle) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Bane) && (Settings.Default.monitoredBane) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Cursna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Cursna"); } else if ((monitoredEffect == StatusEffect.Plague) && (Settings.Default.monitoredPlague) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Viruna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Viruna"); } else if ((monitoredEffect == StatusEffect.Disease) && (Settings.Default.monitoredDisease) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Viruna) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Viruna"); } else if ((monitoredEffect == StatusEffect.Burn) && (Settings.Default.monitoredBurn) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Frost) && (Settings.Default.monitoredFrost) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Choke) && (Settings.Default.monitoredChoke) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Rasp) && (Settings.Default.monitoredRasp) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Shock) && (Settings.Default.monitoredShock) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Drown) && (Settings.Default.monitoredDrown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Dia) && (Settings.Default.monitoredDia) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Bio) && (Settings.Default.monitoredBio) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.STR_Down) && (Settings.Default.monitoredStrDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.DEX_Down) && (Settings.Default.monitoredDexDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.VIT_Down) && (Settings.Default.monitoredVitDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.AGI_Down) && (Settings.Default.monitoredAgiDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.INT_Down) && (Settings.Default.monitoredIntDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.MND_Down) && (Settings.Default.monitoredMndDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.CHR_Down) && (Settings.Default.monitoredChrDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Max_HP_Down) && (Settings.Default.monitoredMaxHpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Max_MP_Down) && (Settings.Default.monitoredMaxMpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Accuracy_Down) && (Settings.Default.monitoredAccuracyDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Evasion_Down) && (Settings.Default.monitoredEvasionDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Defense_Down) && (Settings.Default.monitoredDefenseDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Flash) && (Settings.Default.monitoredFlash) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Magic_Acc_Down) && (Settings.Default.monitoredMagicAccDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Magic_Atk_Down) && (Settings.Default.monitoredMagicAtkDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Helix) && (Settings.Default.monitoredHelix) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Max_TP_Down) && (Settings.Default.monitoredMaxTpDown) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Requiem) && (Settings.Default.monitoredRequiem) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Elegy) && (Settings.Default.monitoredElegy) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } else if ((monitoredEffect == StatusEffect.Threnody) && (Settings.Default.monitoredThrenody) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Erase) == 0)) { castSpell(_FFACEMonitored.Player.Name, "Erase"); } } } // End Debuff Removal #endregion #region "== PL Auto Buffs" // PL Auto Buffs if (!castingLock && _FFACEPL.Player.GetLoginStatus == LoginStatus.LoggedIn) { if ((Settings.Default.plBlink) && (!plStatusCheck(StatusEffect.Blink)) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Blink) == 0)) { castSpell("<me>", "Blink"); } else if ((Settings.Default.plReraise) && (!plStatusCheck(StatusEffect.Reraise))) { if ((Settings.Default.plReraiseLevel == 1) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Reraise) == 0) && _FFACEPL.Player.MPCurrent > 150) { castSpell("<me>", "Reraise"); } else if ((Settings.Default.plReraiseLevel == 2) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Reraise_II) == 0) && _FFACEPL.Player.MPCurrent > 150) { castSpell("<me>", "Reraise II"); } else if ((Settings.Default.plReraiseLevel == 3) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Reraise_III) == 0) && _FFACEPL.Player.MPCurrent > 150) { castSpell("<me>", "Reraise III"); } } else if ((Settings.Default.plRefresh) && (!plStatusCheck(StatusEffect.Refresh))) { if ((Settings.Default.plRefreshLevel == 1) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Refresh) == 0)) { castSpell("<me>", "Refresh"); } else if ((Settings.Default.plRefreshLevel == 2) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Refresh_II) == 0)) { castSpell("<me>", "Refresh II"); } } else if ((Settings.Default.plStoneskin) && (!plStatusCheck(StatusEffect.Stoneskin)) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Stoneskin) == 0)) { castSpell("<me>", "Stoneskin"); } else if ((Settings.Default.plShellra) && (!plStatusCheck(StatusEffect.Shell)) && CheckShellraLevelRecast()) { castSpell("<me>", GetShellraLevel(Settings.Default.plShellralevel)); } else if ((Settings.Default.plProtectra) && (!plStatusCheck(StatusEffect.Protect)) && CheckProtectraLevelRecast()) { castSpell("<me>", GetProtectraLevel(Settings.Default.plProtectralevel)); } } // End PL Auto Buffs #endregion // Auto Casting #region "== Auto Haste" foreach (byte id in playerHpOrder) { if ((autoHasteEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Haste) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Haste)) { hastePlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Haste)) { // Check if we are hasting only if fighting if (Settings.Default.AutoCastEngageCheckBox) { // if we are, check to make sure we are fighting before hasting if (_FFACEMonitored.Player.Status == Status.Fighting) { // Haste player hastePlayer(id); } } // If we are not hasting only during fighting, cast haste else { hastePlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerHasteSpan[id].Minutes >= Settings.Default.autoHasteMinutes)) { hastePlayer(id); } } #endregion #region "== Auto Haste II" { if ((autoHaste_IIEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Haste_II) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Haste)) { haste_IIPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Haste)) { // Check if we are hasting only if fighting if (Settings.Default.AutoCastEngageCheckBox) { // if we are, check to make sure we are fighting before hasting if (_FFACEMonitored.Player.Status == Status.Fighting) { // Haste II player haste_IIPlayer(id); } } // If we are not hasting only during fighting, cast haste else { haste_IIPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerHaste_IISpan[id].Minutes >= Settings.Default.autoHasteMinutes)) { haste_IIPlayer(id); } } #endregion #region "== Auto Flurry " { if ((autoFlurryEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Flurry) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck((StatusEffect)581)) { FlurryPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck((StatusEffect)581)) { // Check if we are flurring only if fighting if (Settings.Default.AutoCastEngageCheckBox) { // if we are, check to make sure we are fighting before flurring if (_FFACEMonitored.Player.Status == Status.Fighting) { // Flurry player FlurryPlayer(id); } } // If we are not flurring only during fighting, cast flurry else { FlurryPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerFlurrySpan[id].Minutes >= Settings.Default.autoHasteMinutes)) { FlurryPlayer(id); } } #endregion #region "== Auto Flurry II" { if ((autoFlurry_IIEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Flurry_II) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck((StatusEffect)581)) { Flurry_IIPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck((StatusEffect)581)) { // Check if we are flurring only if fighting if (Settings.Default.AutoCastEngageCheckBox) { // if we are, check to make sure we are fighting before flurring if (_FFACEMonitored.Player.Status == Status.Fighting) { // Flurry II player Flurry_IIPlayer(id); } } // If we are not flurring only during fighting, cast flurry else { Flurry_IIPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerFlurry_IISpan[id].Minutes >= Settings.Default.autoHasteMinutes)) { Flurry_IIPlayer(id); } } #endregion #region "== Auto Shell IV & V" if ((autoShell_IVEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Shell_IV) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Shell)) { shell_IVPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Shell)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { shell_IVPlayer(id); } } else { shell_IVPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerShell_IVSpan[id].Minutes >= Settings.Default.autoShell_IVMinutes)) { shell_IVPlayer(id); } } if ((autoShell_VEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Shell_V) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Shell)) { shell_VPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Shell)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { shell_VPlayer(id); } } else { shell_VPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerShell_VSpan[id].Minutes >= Settings.Default.autoShell_VMinutes)) { shell_VPlayer(id); } } #endregion #region "== Auto Protect IV & V" if ((autoProtect_IVEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Protect_IV) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Protect)) { protect_IVPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Protect)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { protect_IVPlayer(id); } } else { protect_IVPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerProtect_IVSpan[id].Minutes >= Settings.Default.autoProtect_IVMinutes)) { protect_IVPlayer(id); } } if ((autoProtect_VEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Protect_V) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Protect)) { protect_VPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Protect)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { protect_VPlayer(id); } } else { protect_VPlayer(id); } } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerProtect_VSpan[id].Minutes >= Settings.Default.autoProtect_VMinutes)) { protect_VPlayer(id); } } #endregion #region "== Auto Phalanx II" if ((autoPhalanx_IIEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Phalanx_II) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Phalanx)) { Phalanx_IIPlayer(id); } } else if ((_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!monitoredStatusCheck(StatusEffect.Phalanx)) { Phalanx_IIPlayer(id); } } else if ((_FFACEMonitored.PartyMember[id].HPCurrent > 0) && (playerPhalanx_IISpan[id].Minutes >= Settings.Default.autoPhalanxIIMinutes)) { Phalanx_IIPlayer(id); } } #endregion #region "== Auto Regen IV & V" if ((autoRegen_IVEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Regen_IV) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Regen)) { Regen_IVPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Regen)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { Regen_IVPlayer(id); } } else { Regen_IVPlayer(id); } } } else if (_FFACEMonitored.PartyMember[id].HPCurrent > 0 && (playerRegen_IVSpan[id].Equals(TimeSpan.FromMinutes((double)Settings.Default.autoRegenIVMinutes)) || (playerRegen_IVSpan[id].CompareTo(TimeSpan.FromMinutes((double)Settings.Default.autoRegenIVMinutes)) == 1))) { Regen_IVPlayer(id); } } if ((autoRegen_VEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Regen_V) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Regen)) { Regen_VPlayer(id); } } else if (_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID) { if (!monitoredStatusCheck(StatusEffect.Regen)) { if (Settings.Default.AutoCastEngageCheckBox) { if (_FFACEMonitored.Player.Status == Status.Fighting) { Regen_VPlayer(id); } } else { Regen_VPlayer(id); } } } else if (_FFACEMonitored.PartyMember[id].HPCurrent > 0 && (playerRegen_VSpan[id].Equals(TimeSpan.FromMinutes((double)Settings.Default.autoRegenVMinutes)) || (playerRegen_VSpan[id].CompareTo(TimeSpan.FromMinutes((double)Settings.Default.autoRegenVMinutes)) == 1))) { Regen_VPlayer(id); } } #endregion #region "== Auto Refresh & II" if ((autoRefreshEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Refresh) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Refresh)) { RefreshPlayer(id); } } else if ((_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!monitoredStatusCheck(StatusEffect.Refresh)) { RefreshPlayer(id); } } else if (_FFACEMonitored.PartyMember[id].HPCurrent > 0 && (playerRefreshSpan[id].Equals(TimeSpan.FromMinutes((double)Settings.Default.autoRefreshMinutes)) || (playerRefreshSpan[id].CompareTo(TimeSpan.FromMinutes((double)Settings.Default.autoRefreshMinutes)) == 1))) { RefreshPlayer(id); } } if ((autoRefresh_IIEnabled[id]) && (_FFACEPL.Timer.GetSpellRecast(SpellList.Refresh_II) == 0) && (_FFACEPL.Player.MPCurrent > Settings.Default.mpMinCastValue) && (!castingLock) && (castingPossible(id))) { if ((_FFACEPL.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!plStatusCheck(StatusEffect.Refresh)) { Refresh_IIPlayer(id); } } else if ((_FFACEMonitored.Player.ID == _FFACEMonitored.PartyMember[id].ID)) { if (!monitoredStatusCheck(StatusEffect.Refresh)) { Refresh_IIPlayer(id); } } else if (_FFACEMonitored.PartyMember[id].HPCurrent > 0 && (playerRefresh_IISpan[id].Equals(TimeSpan.FromMinutes((double)Settings.Default.autoRefreshIIMinutes)) || (playerRefresh_IISpan[id].CompareTo(TimeSpan.FromMinutes((double)Settings.Default.autoRefreshIIMinutes)) == 1))) { Refresh_IIPlayer(id); } } } #endregion // so PL job abilities are in order #region "== All other Job Abilities" if (!castingLock && !plStatusCheck(StatusEffect.Amnesia)) { if ((Settings.Default.afflatusSolice) && (!plStatusCheck(StatusEffect.Afflatus_Solace)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Afflatus_Solace) == 0)) { _FFACEPL.Windower.SendString("/ja \"Afflatus Solace\" <me>"); ActionLockMethod(); } else if ((Settings.Default.afflatusMisery) && (!plStatusCheck(StatusEffect.Afflatus_Misery)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Afflatus_Misery) == 0)) { _FFACEPL.Windower.SendString("/ja \"Afflatus Misery\" <me>"); ActionLockMethod(); } else if ((Settings.Default.Composure) && (!plStatusCheck(StatusEffect.Composure)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Composure) == 0)) { _FFACEPL.Windower.SendString("/ja \"Composure\" <me>"); ActionLockMethod(); } else if ((Settings.Default.lightArts) && (!plStatusCheck(StatusEffect.Light_Arts)) && (!plStatusCheck(StatusEffect.Addendum_White)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Light_Arts) == 0)) { _FFACEPL.Windower.SendString("/ja \"Light Arts\" <me>"); ActionLockMethod(); } else if ((Settings.Default.addWhite) && (!plStatusCheck(StatusEffect.Addendum_White)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Stratagems) == 0)) { _FFACEPL.Windower.SendString("/ja \"Addendum: White\" <me>"); ActionLockMethod(); } else if ((Settings.Default.sublimation) && (!plStatusCheck(StatusEffect.Sublimation_Activated)) && (!plStatusCheck(StatusEffect.Sublimation_Complete)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Sublimation) == 0)) { _FFACEPL.Windower.SendString("/ja \"Sublimation\" <me>"); ActionLockMethod(); } else if ((Settings.Default.sublimation) && ((_FFACEPL.Player.MPMax - _FFACEPL.Player.MPCurrent) > (_FFACEPL.Player.HPMax * .4)) && (plStatusCheck(StatusEffect.Sublimation_Complete)) && (_FFACEPL.Timer.GetAbilityRecast(AbilityList.Sublimation) == 0)) { _FFACEPL.Windower.SendString("/ja \"Sublimation\" <me>"); ActionLockMethod(); } } } } } } } #endregion #region "== Get Shellra & Protectra level" private string GetShellraLevel (decimal p) { switch ((int)p) { case 1: return "Shellra"; case 2: return "Shellra II"; case 3: return "Shellra III"; case 4: return "Shellra IV"; case 5: return "Shellra V"; default: return "Shellra"; } } private string GetProtectraLevel (decimal p) { switch ((int)p) { case 1: return "Protectra"; case 2: return "Protectra II"; case 3: return "Protectra III"; case 4: return "Protectra IV"; case 5: return "Protectra V"; default: return "Protectra"; } } #endregion #region "== settingsToolStripMenuItem (settings Tab)" private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { Form2 settings = new Form2(); settings.Show(); } #endregion #region "== playerOptionsButtons (MENU Button)" private void player0optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 0; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[0]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[0]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[0]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[0]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[0]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[0]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[0]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[0]; playerOptions.Show(party0, new Point(0, 0)); } private void player1optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 1; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[1]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[1]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[1]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[1]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[1]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[1]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[1]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[1]; playerOptions.Show(party0, new Point(0, 0)); } private void player2optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 2; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[2]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[2]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[2]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[2]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[2]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[2]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[2]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[2]; playerOptions.Show(party0, new Point(0, 0)); } private void player3optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 3; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[3]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[3]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[3]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[3]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[3]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[3]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[3]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[3]; playerOptions.Show(party0, new Point(0, 0)); } private void player4optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 4; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[4]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[4]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[4]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[4]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[4]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[4]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[4]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[4]; playerOptions.Show(party0, new Point(0, 0)); } private void player5optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 5; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[5]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[5]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[5]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[5]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[5]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[5]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[5]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[5]; playerOptions.Show(party0, new Point(0, 0)); } private void player6optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 6; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[6]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[6]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[6]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[6]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[6]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[6]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[6]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[6]; playerOptions.Show(party1, new Point(0, 0)); } private void player7optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 7; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[7]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[7]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[7]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[7]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[7]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[7]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[7]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[7]; playerOptions.Show(party1, new Point(0, 0)); } private void player8optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 8; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[8]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[8]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[8]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[8]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[8]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[8]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[8]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[8]; playerOptions.Show(party1, new Point(0, 0)); } private void player9optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 9; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[9]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[9]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[9]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[9]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[9]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[9]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[9]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[9]; playerOptions.Show(party1, new Point(0, 0)); } private void player10optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 10; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[10]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[10]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[10]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[10]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[10]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[10]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[10]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[10]; playerOptions.Show(party1, new Point(0, 0)); } private void player11optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 11; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[11]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[11]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[11]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[11]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[11]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[11]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[11]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[11]; playerOptions.Show(party1, new Point(0, 0)); } private void player12optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 12; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[12]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[12]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[12]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[12]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[12]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[12]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[12]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[12]; playerOptions.Show(party2, new Point(0, 0)); } private void player13optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 13; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[13]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[13]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[13]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[13]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[13]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[13]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[13]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[13]; playerOptions.Show(party2, new Point(0, 0)); } private void player14optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 14; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[14]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[14]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[14]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[14]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[14]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[14]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[14]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[14]; playerOptions.Show(party2, new Point(0, 0)); } private void player15optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 15; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[15]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[15]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[15]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[15]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[15]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[15]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[15]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[15]; playerOptions.Show(party2, new Point(0, 0)); } private void player16optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 16; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[16]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[16]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[16]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[16]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[16]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[16]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[16]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[16]; playerOptions.Show(party2, new Point(0, 0)); } private void player17optionsButton_Click(object sender, EventArgs e) { playerOptionsSelected = 17; autoHasteToolStripMenuItem.Checked = autoHasteEnabled[17]; autoHasteIIToolStripMenuItem.Checked = autoHaste_IIEnabled[17]; autoFlurryToolStripMenuItem.Checked = autoFlurryEnabled[17]; autoFlurryIIToolStripMenuItem.Checked = autoFlurry_IIEnabled[17]; autoProtectIVToolStripMenuItem1.Checked = autoProtect_IVEnabled[17]; autoProtectVToolStripMenuItem1.Checked = autoProtect_VEnabled[17]; autoShellIVToolStripMenuItem.Checked = autoShell_IVEnabled[17]; autoShellVToolStripMenuItem.Checked = autoShell_VEnabled[17]; playerOptions.Show(party2, new Point(0, 0)); } #endregion #region "== autoOptions (Auto Button)" private void player0buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 0; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[0]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[0]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[0]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[0]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[0]; autoOptions.Show(party0, new Point(0, 0)); } private void player1buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 1; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[1]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[1]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[1]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[1]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[1]; autoOptions.Show(party0, new Point(0, 0)); } private void player2buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 2; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[2]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[2]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[2]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[2]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[2]; autoOptions.Show(party0, new Point(0, 0)); } private void player3buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 3; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[3]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[3]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[3]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[3]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[3]; autoOptions.Show(party0, new Point(0, 0)); } private void player4buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 4; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[4]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[4]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[4]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[4]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[4]; autoOptions.Show(party0, new Point(0, 0)); } private void player5buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 5; autoPhalanxIIToolStripMenuItem1.Checked = autoPhalanx_IIEnabled[5]; autoRegenIVToolStripMenuItem1.Checked = autoRegen_IVEnabled[5]; autoRefreshToolStripMenuItem1.Checked = autoRefreshEnabled[5]; autoRegenVToolStripMenuItem.Checked = autoRegen_VEnabled[5]; autoRefreshIIToolStripMenuItem.Checked = autoRefresh_IIEnabled[5]; autoOptions.Show(party0, new Point(0, 0)); } private void player6buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 6; autoOptions.Show(party1, new Point(0, 0)); } private void player7buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 7; autoOptions.Show(party1, new Point(0, 0)); } private void player8buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 8; autoOptions.Show(party1, new Point(0, 0)); } private void player9buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 9; autoOptions.Show(party1, new Point(0, 0)); } private void player10buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 10; autoOptions.Show(party1, new Point(0, 0)); } private void player11buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 11; autoOptions.Show(party1, new Point(0, 0)); } private void player12buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 12; autoOptions.Show(party2, new Point(0, 0)); } private void player13buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 13; autoOptions.Show(party2, new Point(0, 0)); } private void player14buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 14; autoOptions.Show(party2, new Point(0, 0)); } private void player15buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 15; autoOptions.Show(party2, new Point(0, 0)); } private void player16buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 16; autoOptions.Show(party2, new Point(0, 0)); } private void player17buffsButton_Click(object sender, EventArgs e) { autoOptionsSelected = 17; autoOptions.Show(party2, new Point(0, 0)); } #endregion #region "== castingLockTimer" private void castingLockTimer_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } castingLockTimer.Enabled = false; castingStatusCheck.Enabled = true; } private void castingStatusCheck_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } if (_FFACEPL.Player.CastPercentEx >= 75) { castingLockLabel.Text = "Casting is soon to be UNLOCKED!"; castingStatusCheck.Enabled = false; castingUnlockTimer.Enabled = true; } else if (castingSafetyPercentage == _FFACEPL.Player.CastPercentEx) { castingLockLabel.Text = "Casting is INTERRUPTED!"; castingStatusCheck.Enabled = false; castingUnlockTimer.Enabled = true; } castingSafetyPercentage = _FFACEPL.Player.CastPercentEx; } private void castingUnlockTimer_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } castingLockLabel.Text = "Casting is UNLOCKED!"; castingLock = false; actionTimer.Enabled = true; castingUnlockTimer.Enabled = false; } private void actionUnlockTimer_Tick(object sender, EventArgs e) { if (_FFACEPL == null || _FFACEMonitored == null) { return; } if (_FFACEPL.Player.GetLoginStatus != LoginStatus.LoggedIn || _FFACEMonitored.Player.GetLoginStatus != LoginStatus.LoggedIn) { return; } castingLockLabel.Text = "Casting is UNLOCKED!"; castingLock = false; actionUnlockTimer.Enabled = false; actionTimer.Enabled = true; } #endregion #region "== auto spells ToolStripItem_Click" private void autoHasteToolStripMenuItem_Click(object sender, EventArgs e) { autoHasteEnabled[playerOptionsSelected] = !autoHasteEnabled[playerOptionsSelected]; } private void autoHasteIIToolStripMenuItem_Click(object sender, EventArgs e) { autoHaste_IIEnabled[playerOptionsSelected] = !autoHaste_IIEnabled[playerOptionsSelected]; } private void autoFlurryToolStripMenuItem_Click(object sender, EventArgs e) { autoFlurryEnabled[playerOptionsSelected] = !autoFlurryEnabled[playerOptionsSelected]; } private void autoFlurryIIToolStripMenuItem_Click(object sender, EventArgs e) { autoFlurry_IIEnabled[playerOptionsSelected] = !autoFlurry_IIEnabled[playerOptionsSelected]; } private void autoProtectIVToolStripMenuItem1_Click(object sender, EventArgs e) { autoProtect_IVEnabled[playerOptionsSelected] = !autoProtect_IVEnabled[playerOptionsSelected]; } private void autoProtectVToolStripMenuItem1_Click(object sender, EventArgs e) { autoProtect_VEnabled[playerOptionsSelected] = !autoProtect_VEnabled[playerOptionsSelected]; } private void autoShellIVToolStripMenuItem_Click(object sender, EventArgs e) { autoShell_IVEnabled[playerOptionsSelected] = !autoShell_IVEnabled[playerOptionsSelected]; } private void autoShellVToolStripMenuItem_Click(object sender, EventArgs e) { autoShell_VEnabled[playerOptionsSelected] = !autoShell_VEnabled[playerOptionsSelected]; } private void autoHasteToolStripMenuItem1_Click(object sender, EventArgs e) { autoHasteEnabled[autoOptionsSelected] = !autoHasteEnabled[autoOptionsSelected]; } private void autoPhalanxIIToolStripMenuItem1_Click(object sender, EventArgs e) { autoPhalanx_IIEnabled[autoOptionsSelected] = !autoPhalanx_IIEnabled[autoOptionsSelected]; } private void autoRegenIVToolStripMenuItem1_Click(object sender, EventArgs e) { autoRegen_IVEnabled[autoOptionsSelected] = !autoRegen_IVEnabled[autoOptionsSelected]; } private void autoRegenVToolStripMenuItem_Click(object sender, EventArgs e) { autoRegen_VEnabled[autoOptionsSelected] = !autoRegen_VEnabled[autoOptionsSelected]; } private void autoRefreshToolStripMenuItem1_Click(object sender, EventArgs e) { autoRefreshEnabled[autoOptionsSelected] = !autoRefreshEnabled[autoOptionsSelected]; } private void autoRefreshIIToolStripMenuItem_Click(object sender, EventArgs e) { autoRefresh_IIEnabled[autoOptionsSelected] = !autoRefresh_IIEnabled[autoOptionsSelected]; } #endregion #region "== spells ToolStripMenuItem_Click" private void hasteToolStripMenuItem_Click(object sender, EventArgs e) { hastePlayer(playerOptionsSelected); } private void followToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/follow " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void phalanxIIToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Phalanx II\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void invisibleToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Invisible\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void refreshToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Refresh\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void refreshIIToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Refresh II\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void sneakToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Sneak\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void regenIIToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Regen II\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void regenIIIToolStripMenuItem_Click (object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Regen III\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void regenIVToolStripMenuItem_Click (object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Regen IV\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void eraseToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Erase\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void sacrificeToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Sacrifice\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void blindnaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Blindna\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void cursnaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Cursna\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void paralynaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Paralyna\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void poisonaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Poisona\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void stonaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Stona\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void silenaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Silena\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void virunaToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Viruna\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void protectIVToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Protect IV\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void protectVToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Protect V\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void shellIVToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Shell IV\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } private void shellVToolStripMenuItem_Click(object sender, EventArgs e) { _FFACEPL.Windower.SendString("/ma \"Shell V\" " + _FFACEMonitored.PartyMember[playerOptionsSelected].Name); CastLockMethod(); } #endregion #region "== Pause Button" private void button3_Click(object sender, EventArgs e) { pauseActions = !pauseActions; if (!pauseActions) { pauseButton.Text = "Pause"; pauseButton.ForeColor = Color.Black; } else if (pauseActions) { pauseButton.Text = "Paused!"; pauseButton.ForeColor = Color.Red; } } #endregion #region "== Player (debug) Button" private void button1_Click(object sender, EventArgs e) { if (_FFACEMonitored == null) { MessageBox.Show("Attach to process before pressing this button","Error"); return; } var items = _FFACEMonitored.PartyMember.Keys.OrderBy(k => _FFACEMonitored.PartyMember[k].HPPCurrent); /* * var items = from k in _FFACEMonitored.PartyMember.Keys orderby _FFACEMonitored.PartyMember[k].HPPCurrent ascending select k; */ foreach (byte id in items) { MessageBox.Show(id.ToString() + ": " + _FFACEMonitored.PartyMember[id].Name + ": " + _FFACEMonitored.PartyMember[id].HPPCurrent.ToString() + ": " + _FFACEMonitored.PartyMember[id].Active.ToString()); } } #endregion #region "== Always on Top Check Box" private void checkBox1_CheckedChanged(object sender, EventArgs e) { { if (TopMost) { TopMost = false; } else { TopMost = true; } } } #endregion #region "== Tray Icon" private void MouseClickTray(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Minimized && this.Visible == false) { this.Show(); this.WindowState = FormWindowState.Normal; } else { this.Hide(); this.WindowState = FormWindowState.Minimized; } } #endregion #region "== About Tab ToolStripMenu Item" private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new Form3().Show(); } #endregion #region "== Transparency (Opacity Value)" private void trackBar1_Scroll(object sender, EventArgs e) { Opacity = trackBar1.Value * 0.01; } #endregion #region "== Shellra & Protectra Recast Level" private bool CheckShellraLevelRecast () { switch ((int)Settings.Default.plShellralevel) { case 1: return _FFACEPL.Timer.GetSpellRecast(SpellList.Shellra) == 0; case 2: return _FFACEPL.Timer.GetSpellRecast(SpellList.Shellra_II) == 0; case 3: return _FFACEPL.Timer.GetSpellRecast(SpellList.Shellra_III) == 0; case 4: return _FFACEPL.Timer.GetSpellRecast(SpellList.Shellra_IV) == 0; case 5: return _FFACEPL.Timer.GetSpellRecast(SpellList.Shellra_V) == 0; default: return false; } } private bool CheckProtectraLevelRecast () { switch ((int)Settings.Default.plProtectralevel) { case 1: return _FFACEPL.Timer.GetSpellRecast(SpellList.Protectra) == 0; case 2: return _FFACEPL.Timer.GetSpellRecast(SpellList.Protectra_II) == 0; case 3: return _FFACEPL.Timer.GetSpellRecast(SpellList.Protectra_III) == 0; case 4: return _FFACEPL.Timer.GetSpellRecast(SpellList.Protectra_IV) == 0; case 5: return _FFACEPL.Timer.GetSpellRecast(SpellList.Protectra_V) == 0; default: return false; } } #endregion #region "== pl Medicine Check" private bool IsMedicated() { return plStatusCheck(StatusEffect.Medicine); } #endregion } }
h1pp0/Cure-Please
Form1.cs
C#
gpl-2.0
161,840
<?php /*-------------------------------------------------------------------------- Setup Page Metaboxes /*------------------------------------------------------------------------*/ class APageMetabox extends AMetabox { static function getMenuList () { $menus = array(''); foreach (wp_get_nav_menus() as $menu) $menus[$menu->name] = $menu->name; return $menus; } static function getTypeList () { $types = array('' => 'Disabled'); foreach (get_terms('item-type') as $type) $types[$type->term_id] = $type->name; return $types; } static function getPagesList () { $pages = array(); foreach (get_pages() as $page) $pages[$page->ID] = $page->post_title; return $pages; } static function init () { # Page Style parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'default', 'class' => 'hide-for-template-contact-php hide-for-template-singlepage-php hide-for-template-fullscreen-php', 'title' => __('Page Style', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('Image Fill Style', A_DOMAIN), 'desc'=> '', 'id' => '_page-style', 'type'=> 'select', 'std' => '', 'opts'=> array( __('Simple Background Image (Original size)', A_DOMAIN), 'title'=>__('Dark Background (fit in Titles)', A_DOMAIN), 'full'=>__('Dark Background (fit in Fullpage)', A_DOMAIN))) ,array( 'name'=> __('Image Source', A_DOMAIN), 'desc'=> '', 'id' => '_bg-image', 'std' => '', // A_THEME_URL . '/img/default-bg.jpg', 'type'=> 'text' ) ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ) ); # Single Page Setup parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'default', 'class' => 'hidden show-for-template-singlepage-php', 'title' => __('Single Page Setup', A_DOMAIN), 'desc' => __('Single-page creation process is an automatic gluing of trivial pages that have been already created. So first <a href="nav-menus.php">create a menu</a>, fill it with pages, then select here the menu you created. Anthe will do the rest.', A_DOMAIN), 'fields' => array( array( 'name'=> __('Construction Menu', A_DOMAIN), 'desc'=> '', 'id' => '_construction_menu_id', 'type'=> 'select', 'std' => '', 'opts'=> self::getMenuList()) ) ); # Contact Page Settings parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'core', 'class' => 'hidden show-for-template-contact-php', 'title' => __('Contact Page Settings', A_DOMAIN), 'desc' => '', 'fields' => array( # starting field id with '_' hiding it from custom fields box array( 'name'=> __('Map Latitude', A_DOMAIN), 'desc'=> '', 'id' => '_map-lat', 'std' => '51.508', 'type'=> 'text' ), array( 'name'=> __('Map Longitude', A_DOMAIN), 'desc'=> __("Don't drop leading '+' or '-' if available", A_DOMAIN), 'id' => '_map-long', 'std' => '-0.128', 'type'=> 'text' ), array( 'name'=> __('Map Zoom', A_DOMAIN), 'desc'=> '', 'id' => '_map-zoom', 'std' => 17, 'type'=> 'select', 'opts'=> array( 19 => __('City Bird', A_DOMAIN), 17 => __('Hot Air Balloon', A_DOMAIN), 15 => __('Corporate Helicopter', A_DOMAIN), 13 => __('Aeroplane', A_DOMAIN), 9 => __('Sputnik', A_DOMAIN))), array( 'name'=> __('Map Style', A_DOMAIN), 'desc'=> '', 'id' => '_map-style', 'std' => '', 'type'=> 'select', 'opts'=> array( __('Google Default', A_DOMAIN), A_THEME_NAME.__(' Special', A_DOMAIN))) ) ); # Services Page Setup parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'high', 'class' => 'hidden show-for-template-services-php show-for-template-services-6-php', 'title' => __('Services Page Setup', A_DOMAIN), 'desc' => __('Choose the pages, from what content will be fetched (Page titles, content &amp; Featured Images as slides).', A_DOMAIN), 'fields' => array( array( 'name'=> __('First Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_1', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Second Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_2', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Third Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_3', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Slider Max Height', A_DOMAIN), 'desc'=> '', 'id' => '_service-slider-max-height', 'std' => '360px', 'type'=> 'text' ) ) ); # Services Page Setup #2 parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'high', 'class' => 'hidden show-for-template-services-6-php', 'title' => __('Services Page Setup #2', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('Fourth Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_4', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Fifth Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_5', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Sixth Service Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_service_src_6', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()) ) ); # Fullscreen Slide Setup $pre = '&nbsp;&#8627;&nbsp;'; parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'default', 'class' => 'hidden show-for-template-fullscreen-php show-for-template-fullscreen-6-php', 'title' => __('Fullscreen Slide Setup', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('Slide Image I', A_DOMAIN), 'desc'=> '', 'id' => '_slide_1_img', 'std' => A_THEME_URL . '/img/slide.jpg', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_1_h1', 'std' => 'First Line | Second Line | Third Line', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_1_h3', 'std' => 'Normal Text | Strong Text', 'type'=> 'text') ,array( 'name'=> __('Slide Image II', A_DOMAIN), 'desc'=> '', 'id' => '_slide_2_img', 'std' => '', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_2_h1', 'std' => '', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_2_h3', 'std' => '', 'type'=> 'text') ,array( 'name'=> __('Slide Image III', A_DOMAIN), 'desc'=> '', 'id' => '_slide_3_img', 'std' => '', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_3_h1', 'std' => '', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_3_h3', 'std' => '', 'type'=> 'text') ,array( 'id' => 'Fullscreen Slider Timeout', 'std' => 13, 'type'=> 'custom') ,array( 'id' => 'Fullscreen Slider Speed', 'std' => 1.3, 'type'=> 'custom') ) ); # Fullscreen Slide Setup #2 parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'default', 'class' => 'hidden show-for-template-fullscreen-6-php', 'title' => __('Fullscreen Slide Setup #2', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('Slide Image IV', A_DOMAIN), 'desc'=> '', 'id' => '_slide_4_img', 'std' => '', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_4_h1', 'std' => '', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_4_h3', 'std' => '', 'type'=> 'text') ,array( 'name'=> __('Slide Image V', A_DOMAIN), 'desc'=> '', 'id' => '_slide_5_img', 'std' => '', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_5_h1', 'std' => '', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_5_h3', 'std' => '', 'type'=> 'text') ,array( 'name'=> __('Slide Image VI', A_DOMAIN), 'desc'=> '', 'id' => '_slide_6_img', 'std' => '', 'type'=> 'text') ,array( 'std' => __('Upload', A_DOMAIN), 'type' => 'button' ) ,array( 'name'=> $pre.__('Main Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_6_h1', 'std' => '', 'type'=> 'text') ,array( 'name'=> $pre.__('Foot Copy', A_DOMAIN), 'desc'=> '', 'id' => '_slide_6_h3', 'std' => '', 'type'=> 'text') ) ); # Process Page Setup parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'high', 'class' => 'hidden show-for-template-process-php show-for-template-process-6-php', 'title' => __('Process Page Setup', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('First Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_1', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('First Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_1', 'std' => "First line.\nSecond line.", 'type'=> 'textarea'), array( 'name'=> __('Second Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_2', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Second Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_2', 'std' => "First line.\nSecond line.", 'type'=> 'textarea'), array( 'name'=> __('Third Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_3', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Third Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_3', 'std' => "First line.\nSecond line.", 'type'=> 'textarea') ) ); # Process Page Setup #2 parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'high', 'class' => 'hidden show-for-template-process-6-php', 'title' => __('Process Page Setup #2', A_DOMAIN), 'desc' => '', 'fields' => array( array( 'name'=> __('Fourth Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_4', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Fourth Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_4', 'std' => "First line.\nSecond line.", 'type'=> 'textarea'), array( 'name'=> __('Fifth Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_5', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Fifth Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_5', 'std' => "First line.\nSecond line.", 'type'=> 'textarea'), array( 'name'=> __('Sixth Step Content', A_DOMAIN), 'desc'=> __('Choose a source page', A_DOMAIN), 'id' => '_page_src_6', 'std' => '', 'type'=> 'select', 'opts'=> self::getPagesList()), array( 'name'=> __('Sixth Step Excerpt', A_DOMAIN), 'desc'=> __('Hand-crafted summary', A_DOMAIN), 'id' => '_excerpt_6', 'std' => "First line.\nSecond line.", 'type'=> 'textarea') ) ); # Works Options parent::$boxes[] = array( 'page' => 'page', 'context' => 'normal', 'priority'=> 'core', 'class' => 'hidden show-for-template-works-php', 'title' => __('Works Options', A_DOMAIN), 'desc' => __('This page will render all your <a href="edit.php?post_type=item">Works</a> according to these settings:', A_DOMAIN), 'fields' => array( array( 'name'=> __('Category Filter', A_DOMAIN), 'desc'=> '', 'id' => 'category', 'type'=> 'select', 'std' => '', 'opts'=> self::getTypeList()), array( 'name'=> __('Ordering', A_DOMAIN), 'desc'=> '', 'id' => 'order', 'type'=> 'select', 'std' => '', 'opts'=> array( '' => 'by Date', 'abc' => 'by Title (alphabetically)', 'rnd' => 'in Random Order')) ) ); } } /*-------------------------------------------------------------------------- Register This Metabox /*------------------------------------------------------------------------*/ add_action ( 'admin_init', 'APageMetabox::init' );
Phumbert/ZAKE
wp-content/themes/anthe/theme/metabox.page.php
PHP
gpl-2.0
16,727
<?php include "inc/class_paging.php"; ?> <div align="left" style="float: left; margin: 5px 0 0 10px;"> <!-- post content block --> <div id="post"> <?php include "inc/breadcrumbs.php"; ?> <div style="margin-top: 20px;"> <h3>List Data Komentar</h3> <table width="100%" border="0"> <tr> <td width="60%" align="left"> <?php if (isset($_SESSION['login']) and $_SESSION['login']==1) { $user=$_SESSION['user']; $level=$_SESSION['level']; if ($level=='superuser' || $level=='admin') { ?> <a href="export/exp_komentar.php" target="_blank" title="Download Data"> <button type="submit" name="tambah_data" class="button-style" style="margin-left: -3px; margin-right: 3px;">Download</button> </a> <?php } } ?> </td> <td width="40%" align="right"> <form action="?page=search_komentar" method="post" class="form-wrapper cf" style="margin-right: -2px;"> <input name="key" id="input" type="text" placeholder="Ketik nama disini..." required="required" /> <button id="button" type="submit" style="padding-right: 0;"><font style="padding-right: 3px;">Search</font></button> </form> </td> </tr> </table> <table class="table" width="100%" border="0"> <tr> <th>NO.</th> <th>NAMA LENGKAP</th> <th>KOMENTAR</th> <th>WAKTU</th> <th>OPTION</th> </tr> <?php $limit=20; $query=new CnnNav($limit,'guestbook','*','no_id'); $result=$query ->getResult(); if (isset($_GET['offset'])) { $number=($limit*$_GET['offset'])+1; } else { $number=1; } while ($data=mysql_fetch_array($result)) { if ($number%2==1) { $color='#fff'; } else { $color='#eee'; } if (isset($_SESSION['login']) and $_SESSION['login']==1) { $user=$_SESSION['user']; $level=$_SESSION['level']; if ($level=='superuser' || $level=='admin') { ?> <tr bgcolor="<?php echo $color; ?>"> <td align="center"><?php echo $number; ?></td> <td align="left" width="20%"><a href="mailto:<?php echo $data['email']; ?>"><?php echo $data['nama']; ?></a></td> <td align="left"><?php echo $data['komentar']; ?></td> <td align="left" width="25%"><?php echo $data['waktu']; ?></td> <td align="center"> <a href="?page=data_komentar&menu=hapus&id=<?php echo $data['no_id'];?>" <?php hapus(); ?>><img src="images/delete.png" width="13px" height="auto" title="Hapus data" /></a> </td> </tr> <?php } } $number++; } $x="select * from guestbook"; $y=mysql_query($x); $rows=mysql_num_rows($y); ?> </table> <table width="100%" border="0" style="font-size: 12px; margin-top: 3px; margin-bottom: 15px;"> <tr> <td width="75%" align="left"> <?php if ($rows > $limit) { ?> Halaman: <?php $query->printNav(); ?> <?php } ?> </td> <td width="25%" align="right">Jumlah: <b><?php echo $rows; ?></b> komentar</td> </tr> </table> </div> </div> </div> <?php $menu=isset($_GET['menu'])? $_GET['menu']:''; $id=isset($_GET['id'])? $_GET['id']:''; if ($menu=="hapus") { $hapus=mysql_query("delete from guestbook where no_id='$id'"); echo "<script>alert('Data berhasil dihapus')</script>"; direct("?page=data_komentar"); } ?>
umamscarlet/prakerin-smk
user/data_komentar.php
PHP
gpl-2.0
3,212
/* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is provided for educational purposes and is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ #include "standarditem.hpp" StandardItem::StandardItem(const QString &text, bool done) : QStandardItem(text) { setCheckable(true); setCheckState(done ? Qt::Checked : Qt::Unchecked); setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled| Qt::ItemIsEditable|Qt::ItemIsUserCheckable); m_today = new QStandardItem; m_today->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); m_today->setTextAlignment(Qt::AlignVCenter|Qt::AlignRight); m_total = new QStandardItem; m_total->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); m_total->setTextAlignment(Qt::AlignVCenter|Qt::AlignRight); } void StandardItem::incrementLastEndTime(int msec) { Q_ASSERT(!m_dateTimes.isEmpty()); QDateTime &endTime = m_dateTimes.last().second; endTime.setTime(endTime.time().addMSecs(msec)); } QString StandardItem::todaysTime() const { int minutes = minutesForTask(true); return QString("%1:%2").arg(minutes / 60) .arg(minutes % 60, 2, 10, QChar('0')); } QString StandardItem::totalTime() const { int minutes = minutesForTask(false); return QString("%1:%2").arg(minutes / 60) .arg(minutes % 60, 2, 10, QChar('0')); } int StandardItem::minutesForTask(bool onlyForToday) const { int minutes = 0; QListIterator<QPair<QDateTime, QDateTime> > i(m_dateTimes); while (i.hasNext()) { const QPair<QDateTime, QDateTime> &dateTime = i.next(); if (onlyForToday && dateTime.first.date() != QDate::currentDate()) continue; minutes += (dateTime.first.secsTo(dateTime.second) / 60); } for (int row = 0; row < rowCount(); ++row) { StandardItem *item = static_cast<StandardItem*>(child(row, 0)); Q_ASSERT(item); minutes += item->minutesForTask(onlyForToday); } return minutes; }
paradiseOffice/Bash_and_Cplus-plus
CPP/full_examples/aqp-qt5/timelog1/standarditem.cpp
C++
gpl-2.0
2,620
<?php /** * InsertFile extension for BlueSpice * * Dialogbox to upload files and enter a file link. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * This file is part of BlueSpice for MediaWiki * For further information visit http://www.blue-spice.org * * @author Markus Glaser <glaser@hallowelt.biz> * @author Sebastian Ulbricht * @version 2.22.0 stable * @package BlueSpice_Extensions * @subpackage InsertFile * @copyright Copyright (C) 2012 Hallo Welt! - Medienwerkstatt GmbH, All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License v2 or later * @filesource */ /* Changelog * v1.20.0 * * v1.1.0 * Added external ExtJS resources and components * v1.0.0 * - raised to stable * v0.1 * - initial commit */ /** * Class for file upload and management assistent * @package BlueSpice_Extensions * @subpackage InsertFile */ class InsertFile extends BsExtensionMW { /** * Constructor of InsertFile */ public function __construct() { wfProfileIn( 'BS::' . __METHOD__ ); // Base settings $this->mExtensionFile = __FILE__; $this->mExtensionType = EXTTYPE::VARIABLE; $this->mInfo = array( EXTINFO::NAME => 'InsertFile', EXTINFO::DESCRIPTION => wfMessage( 'bs-insertfile-desc' )->escaped(), EXTINFO::AUTHOR => 'Markus Glaser, Sebastian Ulbricht, Robert Vogel', EXTINFO::VERSION => 'default', EXTINFO::STATUS => 'default', EXTINFO::PACKAGE => 'default', EXTINFO::URL => 'http://www.hallowelt.biz', EXTINFO::DEPS => array( 'bluespice' => '2.22.0' ) ); $this->mExtensionKey = 'MW::InsertFile'; wfProfileOut( 'BS::' . __METHOD__ ); } /** * Initialise the InsertFile extension */ protected function initExt() { wfProfileIn( 'BS::' . __METHOD__ ); $this->setHook( 'VisualEditorConfig' ); $this->setHook( 'BSExtendedEditBarBeforeEditToolbar' ); wfProfileOut( 'BS::' . __METHOD__ ); } /** * Hook Handler for VisualEditorConfig Hook * @param Array $aConfigStandard reference * @param Array $aConfigOverwrite reference * @param Array &$aLoaderUsingDeps reference * @return boolean always true to keep hook alife */ public function onVisualEditorConfig( &$aConfigStandard, &$aConfigOverwrite, &$aLoaderUsingDeps ) { $aLoaderUsingDeps[] = 'ext.bluespice.insertFile'; // TODO SW: use string as parameter !! $iIndexStandard = array_search( 'unlink',$aConfigStandard["toolbar1"] ); array_splice( $aConfigStandard["toolbar1"], $iIndexStandard + 1, 0, "bsimage" ); array_splice( $aConfigStandard["toolbar1"], $iIndexStandard + 2, 0, "bsfile" ); $iIndexOverwrite = array_search( 'unlink',$aConfigOverwrite["toolbar2"] ); array_splice( $aConfigOverwrite["toolbar2"], $iIndexOverwrite + 1, 0, "bsimage" ); // Add context menu entry $aConfigStandard["contextmenu"] = str_replace('bsContextMenuMarker', 'bsContextMenuMarker bsContextImage', $aConfigStandard["contextmenu"] ); return true; } public function onBSExtendedEditBarBeforeEditToolbar( &$aRows, &$aButtonCfgs ) { $this->getOutput()->addModuleStyles('ext.bluespice.insertFile.styles'); $this->getOutput()->addModules('ext.bluespice.insertFile'); $aRows[0]['dialogs'][20] = 'bs-editbutton-insertimage'; $aRows[0]['dialogs'][30] = 'bs-editbutton-insertfile'; $aButtonCfgs['bs-editbutton-insertimage'] = array( 'tip' => wfMessage( 'bs-insertfile-insert-image' )->plain() ); $aButtonCfgs['bs-editbutton-insertfile'] = array( 'tip' => wfMessage( 'bs-insertfile-insert-file' )->plain() ); return true; } }
scolladogsp/wiki
extensions/BlueSpiceExtensions/InsertFile/InsertFile.class.php
PHP
gpl-2.0
4,265
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.model; public interface MockServiceDaemonMBean extends ServiceDaemonMBean { }
bugcy013/opennms-tmp-tools
opennms-model/src/main/java/org/opennms/netmgt/model/MockServiceDaemonMBean.java
Java
gpl-2.0
1,294
<?php /** * @file * Contains \Drupal\Tests\user\Unit\Plugin\Core\Entity\UserTest. */ namespace Drupal\Tests\user\Unit\Plugin\Core\Entity; use Drupal\Tests\Core\Session\UserSessionTest; use Drupal\user\RoleInterface; /** * @coversDefaultClass \Drupal\user\Entity\User * @group user */ class UserTest extends UserSessionTest { /** * {@inheritdoc} */ protected function createUserSession(array $rids = array(), $authenticated = FALSE) { $user = $this->getMockBuilder('Drupal\user\Entity\User') ->disableOriginalConstructor() ->setMethods(array('get', 'id')) ->getMock(); $user->expects($this->any()) ->method('id') // @todo Also test the uid = 1 handling. ->will($this->returnValue($authenticated ? 2 : 0)); $roles = array(); foreach ($rids as $rid) { $roles[] = (object) array( 'target_id' => $rid, ); } $user->expects($this->any()) ->method('get') ->with('roles') ->will($this->returnValue($roles)); return $user; } /** * Tests the method getRoles exclude or include locked roles based in param. * * @see \Drupal\user\Entity\User::getRoles() * @covers ::getRoles */ public function testUserGetRoles() { // Anonymous user. $user = $this->createUserSession(array()); $this->assertEquals(array(RoleInterface::ANONYMOUS_ID), $user->getRoles()); $this->assertEquals(array(), $user->getRoles(TRUE)); // Authenticated user. $user = $this->createUserSession(array(), TRUE); $this->assertEquals(array(RoleInterface::AUTHENTICATED_ID), $user->getRoles()); $this->assertEquals(array(), $user->getRoles(TRUE)); } }
papillon-cendre/d8
core/modules/user/tests/src/Unit/Plugin/Core/Entity/UserTest.php
PHP
gpl-2.0
1,683
/* * Copyright 2009-2022 Contributors (see credits.txt) * * This file is part of jEveAssets. * * jEveAssets is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * jEveAssets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jEveAssets; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package net.nikr.eve.jeveasset.i18n; import java.util.Locale; import uk.me.candle.translations.conf.DefaultBundleConfiguration; import uk.me.candle.translations.service.BasicBundleService; import uk.me.candle.translations.service.BundleService; public class BundleServiceFactory { private static BundleService bundleService; public static BundleService getBundleService() { //XXX - Workaround for default language if (bundleService == null) { bundleService = new BasicBundleService(new DefaultBundleConfiguration(), Locale.ENGLISH); } return bundleService; } }
GoldenGnu/jeveassets
src/main/java/net/nikr/eve/jeveasset/i18n/BundleServiceFactory.java
Java
gpl-2.0
1,439
/* Copyright (c) 2006 Colin Dewey (University of Wisconsin-Madison) cdewey@biostat.wisc.edu This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "util/stl.hh" #include "bio/alignment/PairwiseAlignment.hh" namespace bio { namespace alignment { size_t PairwiseAlignment::getNumIdentities() const { return util::stl::matches(seq1.begin(), seq1.end(), seq2.begin()); } PairwiseAlignment PairwiseAlignment::slice(size_t seqNum, size_t start, size_t end) const { std::string seq = (seqNum == 0 ? seq1 : seq2); size_t startCol = seq.find_first_not_of('-'); while (start > 0) { startCol = seq.find_first_not_of('-', startCol + 1); --start; --end; } size_t endCol = startCol; while (end > 0) { if (end == 1) { ++endCol; } else { endCol = seq.find_first_not_of('-', endCol + 1); } --end; } return PairwiseAlignment(seq1.substr(startCol, endCol - startCol), seq2.substr(startCol, endCol - startCol)); } } }
hyphaltip/cndtools
lib/bio/alignment/PairwiseAlignment.cc
C++
gpl-2.0
1,648
package com.mediatek.engineermode.hqanfc; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import com.mediatek.engineermode.Elog; import com.mediatek.engineermode.R; import com.mediatek.engineermode.hqanfc.NfcCommand.BitMapValue; import com.mediatek.engineermode.hqanfc.NfcCommand.CommandType; import com.mediatek.engineermode.hqanfc.NfcCommand.EmAction; import com.mediatek.engineermode.hqanfc.NfcCommand.P2pDisableCardM; import com.mediatek.engineermode.hqanfc.NfcCommand.RspResult; import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pNtf; import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pReq; import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmAlsP2pRsp; import java.nio.ByteBuffer; public class PeerToPeerMode extends Activity { protected static final String KEY_P2P_RSP_ARRAY = "p2p_rsp_array"; private static final int HANDLER_MSG_GET_RSP = 200; private static final int HANDLER_MSG_GET_NTF = 201; private static final int DIALOG_ID_RESULT = 0; private static final int DIALOG_ID_WAIT = 1; private static final int CHECKBOX_TYPEA = 0; private static final int CHECKBOX_TYPEA_106 = 1; private static final int CHECKBOX_TYPEA_212 = 2; private static final int CHECKBOX_TYPEA_424 = 3; private static final int CHECKBOX_TYPEA_848 = 4; private static final int CHECKBOX_TYPEF = 5; private static final int CHECKBOX_TYPEF_212 = 6; private static final int CHECKBOX_TYPEF_424 = 7; private static final int CHECKBOX_PASSIVE_MODE = 8; private static final int CHECKBOX_ACTIVE_MODE = 9; private static final int CHECKBOX_INITIATOR = 10; private static final int CHECKBOX_TARGET = 11; private static final int CHECKBOX_DISABLE_CARD = 12; private static final int CHECKBOX_NUMBER = 13; private CheckBox[] mSettingsCkBoxs = new CheckBox[CHECKBOX_NUMBER]; private Button mBtnSelectAll; private Button mBtnClearAll; private Button mBtnStart; private Button mBtnReturn; private Button mBtnRunInBack; private NfcEmAlsP2pNtf mP2pNtf; private NfcEmAlsP2pRsp mP2pRsp; private byte[] mRspArray; private String mNtfContent; private boolean mEnableBackKey = true; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]mReceiver onReceive: " + action); mRspArray = intent.getExtras().getByteArray(NfcCommand.MESSAGE_CONTENT_KEY); if ((NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_NTF).equals(action)) { if (null != mRspArray) { ByteBuffer buffer = ByteBuffer.wrap(mRspArray); mP2pNtf = new NfcEmAlsP2pNtf(); mP2pNtf.readRaw(buffer); mHandler.sendEmptyMessage(HANDLER_MSG_GET_NTF); } } else if ((NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_RSP).equals(action)) { if (null != mRspArray) { ByteBuffer buffer = ByteBuffer.wrap(mRspArray); mP2pRsp = new NfcEmAlsP2pRsp(); mP2pRsp.readRaw(buffer); mHandler.sendEmptyMessage(HANDLER_MSG_GET_RSP); } } else { Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]Other response"); } } }; private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); String toastMsg = null; if (HANDLER_MSG_GET_NTF == msg.what) { switch (mP2pNtf.mResult) { case RspResult.SUCCESS: toastMsg = "P2P Data Exchange is terminated"; // mNtfContent = new String(mP2pNtf.mData); // showDialog(DIALOG_ID_RESULT); break; case RspResult.FAIL: toastMsg = "P2P Data Exchange is On-going"; break; default: toastMsg = "P2P Data Exchange is ERROR"; break; } } else if (HANDLER_MSG_GET_RSP == msg.what) { dismissDialog(DIALOG_ID_WAIT); switch (mP2pRsp.mResult) { case RspResult.SUCCESS: toastMsg = "P2P Mode Rsp Result: SUCCESS"; if (mBtnStart.getText().equals(PeerToPeerMode.this.getString(R.string.hqa_nfc_start))) { setButtonsStatus(false); } else { setButtonsStatus(true); } break; case RspResult.FAIL: toastMsg = "P2P Mode Rsp Result: FAIL"; break; default: toastMsg = "P2P Mode Rsp Result: ERROR"; break; } } Toast.makeText(PeerToPeerMode.this, toastMsg, Toast.LENGTH_SHORT).show(); } }; private final CheckBox.OnCheckedChangeListener mCheckedListener = new CheckBox.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean checked) { Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]onCheckedChanged view is " + buttonView.getText() + " value is " + checked); if (buttonView.equals(mSettingsCkBoxs[CHECKBOX_TYPEA])) { for (int i = CHECKBOX_TYPEA_106; i < CHECKBOX_TYPEF; i++) { mSettingsCkBoxs[i].setChecked(checked); } } else if (buttonView.equals(mSettingsCkBoxs[CHECKBOX_TYPEF])) { for (int i = CHECKBOX_TYPEF_212; i < CHECKBOX_PASSIVE_MODE; i++) { mSettingsCkBoxs[i].setChecked(checked); } } } }; private final Button.OnClickListener mClickListener = new Button.OnClickListener() { @Override public void onClick(View arg0) { Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]onClick button view is " + ((Button) arg0).getText()); if (arg0.equals(mBtnStart)) { if (!checkRoleSelect()) { Toast.makeText(PeerToPeerMode.this, R.string.hqa_nfc_p2p_role_tip, Toast.LENGTH_LONG).show(); } else { showDialog(DIALOG_ID_WAIT); doTestAction(mBtnStart.getText().equals(PeerToPeerMode.this.getString(R.string.hqa_nfc_start))); } } else if (arg0.equals(mBtnSelectAll)) { changeAllSelect(true); } else if (arg0.equals(mBtnClearAll)) { changeAllSelect(false); } else if (arg0.equals(mBtnReturn)) { PeerToPeerMode.this.onBackPressed(); } else if (arg0.equals(mBtnRunInBack)) { doTestAction(null); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hqa_nfc_p2p_mode); initComponents(); changeAllSelect(true); IntentFilter filter = new IntentFilter(); filter.addAction(NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_RSP); filter.addAction(NfcCommand.ACTION_PRE + CommandType.MTK_NFC_EM_ALS_P2P_MODE_NTF); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } @Override public void onBackPressed() { if (!mEnableBackKey) { return; } super.onBackPressed(); } private void initComponents() { Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]initComponents"); mSettingsCkBoxs[CHECKBOX_TYPEA] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea); mSettingsCkBoxs[CHECKBOX_TYPEA].setOnCheckedChangeListener(mCheckedListener); mSettingsCkBoxs[CHECKBOX_TYPEA_106] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_106); mSettingsCkBoxs[CHECKBOX_TYPEA_212] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_212); mSettingsCkBoxs[CHECKBOX_TYPEA_424] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_424); mSettingsCkBoxs[CHECKBOX_TYPEA_848] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typea_848); mSettingsCkBoxs[CHECKBOX_TYPEF] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef); mSettingsCkBoxs[CHECKBOX_TYPEF].setOnCheckedChangeListener(mCheckedListener); mSettingsCkBoxs[CHECKBOX_TYPEF_212] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef_212); mSettingsCkBoxs[CHECKBOX_TYPEF_424] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_typef_424); mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_passive_mode); mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_active_mode); mSettingsCkBoxs[CHECKBOX_INITIATOR] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_initiator); mSettingsCkBoxs[CHECKBOX_TARGET] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_target); mSettingsCkBoxs[CHECKBOX_DISABLE_CARD] = (CheckBox) findViewById(R.id.hqa_p2pmode_cb_disable_card_emul); mBtnSelectAll = (Button) findViewById(R.id.hqa_p2pmode_btn_select_all); mBtnSelectAll.setOnClickListener(mClickListener); mBtnClearAll = (Button) findViewById(R.id.hqa_p2pmode_btn_clear_all); mBtnClearAll.setOnClickListener(mClickListener); mBtnStart = (Button) findViewById(R.id.hqa_p2pmode_btn_start_stop); mBtnStart.setOnClickListener(mClickListener); mBtnReturn = (Button) findViewById(R.id.hqa_p2pmode_btn_return); mBtnReturn.setOnClickListener(mClickListener); mBtnRunInBack = (Button) findViewById(R.id.hqa_p2pmode_btn_run_back); mBtnRunInBack.setOnClickListener(mClickListener); mBtnRunInBack.setEnabled(false); } private void setButtonsStatus(boolean b) { if (b) { mBtnStart.setText(R.string.hqa_nfc_start); } else { mBtnStart.setText(R.string.hqa_nfc_stop); } mBtnRunInBack.setEnabled(!b); mEnableBackKey = b; mBtnReturn.setEnabled(b); mBtnSelectAll.setEnabled(b); mBtnClearAll.setEnabled(b); } private void changeAllSelect(boolean checked) { Elog.v(NfcMainPage.TAG, "[PeerToPeerMode]changeAllSelect status is " + checked); for (int i = CHECKBOX_TYPEA; i < mSettingsCkBoxs.length; i++) { mSettingsCkBoxs[i].setChecked(checked); } } private void doTestAction(Boolean bStart) { sendCommand(bStart); } private void sendCommand(Boolean bStart) { NfcEmAlsP2pReq requestCmd = new NfcEmAlsP2pReq(); fillRequest(bStart, requestCmd); NfcClient.getInstance().sendCommand(CommandType.MTK_NFC_EM_ALS_P2P_MODE_REQ, requestCmd); } private void fillRequest(Boolean bStart, NfcEmAlsP2pReq requestCmd) { if (null == bStart) { requestCmd.mAction = EmAction.ACTION_RUNINBG; } else if (bStart.booleanValue()) { requestCmd.mAction = EmAction.ACTION_START; } else { requestCmd.mAction = EmAction.ACTION_STOP; } int temp = 0; temp |= mSettingsCkBoxs[CHECKBOX_TYPEA].isChecked() ? NfcCommand.EM_ALS_READER_M_TYPE_A : 0; temp |= mSettingsCkBoxs[CHECKBOX_TYPEF].isChecked() ? NfcCommand.EM_ALS_READER_M_TYPE_F : 0; requestCmd.mSupportType = temp; CheckBox[] typeADateRateBoxs = { mSettingsCkBoxs[CHECKBOX_TYPEA_106], mSettingsCkBoxs[CHECKBOX_TYPEA_212], mSettingsCkBoxs[CHECKBOX_TYPEA_424], mSettingsCkBoxs[CHECKBOX_TYPEA_848] }; requestCmd.mTypeADataRate = BitMapValue.getTypeAbDataRateValue(typeADateRateBoxs); CheckBox[] typeFDateRateBoxs = { mSettingsCkBoxs[CHECKBOX_TYPEF_212], mSettingsCkBoxs[CHECKBOX_TYPEF_424] }; requestCmd.mTypeFDataRate = BitMapValue.getTypeFDataRateValue(typeFDateRateBoxs); requestCmd.mIsDisableCardM = mSettingsCkBoxs[CHECKBOX_DISABLE_CARD].isChecked() ? P2pDisableCardM.DISABLE : P2pDisableCardM.NOT_DISABLE; temp = 0; temp |= mSettingsCkBoxs[CHECKBOX_INITIATOR].isChecked() ? NfcCommand.EM_P2P_ROLE_INITIATOR_MODE : 0; temp |= mSettingsCkBoxs[CHECKBOX_TARGET].isChecked() ? NfcCommand.EM_P2P_ROLE_TARGET_MODE : 0; requestCmd.mRole = temp; temp = 0; temp |= mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE].isChecked() ? NfcCommand.EM_P2P_MODE_PASSIVE_MODE : 0; temp |= mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE].isChecked() ? NfcCommand.EM_P2P_MODE_ACTIVE_MODE : 0; requestCmd.mMode = temp; } @Override protected Dialog onCreateDialog(int id) { if (DIALOG_ID_WAIT == id) { ProgressDialog dialog = null; dialog = new ProgressDialog(this); dialog.setMessage(getString(R.string.hqa_nfc_dialog_wait_message)); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setCancelable(false); return dialog; } else if (DIALOG_ID_RESULT == id) { AlertDialog alertDialog = null; alertDialog = new AlertDialog.Builder(PeerToPeerMode.this).setTitle(R.string.hqa_nfc_p2p_mode_ntf_title) .setMessage(mNtfContent).setPositiveButton(android.R.string.ok, null).create(); return alertDialog; } return null; } private boolean checkRoleSelect() { boolean result = true; if (!mSettingsCkBoxs[CHECKBOX_INITIATOR].isChecked() && !mSettingsCkBoxs[CHECKBOX_TARGET].isChecked()) { result = false; } if (!mSettingsCkBoxs[CHECKBOX_PASSIVE_MODE].isChecked() && !mSettingsCkBoxs[CHECKBOX_ACTIVE_MODE].isChecked()) { result = false; } return result; } }
rex-xxx/mt6572_x201
mediatek/packages/apps/EngineerMode/src/com/mediatek/engineermode/hqanfc/PeerToPeerMode.java
Java
gpl-2.0
14,964
<?php /** * sh404SEF - SEO extension for Joomla! * * @author Yannick Gaultier * @copyright (c) Yannick Gaultier 2014 * @package sh404SEF * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @version 4.4.6.2271 * @date 2014-11-03 */ // Security check to ensure this file is being included by a parent file. if (!defined('_JEXEC')) die('Direct Access to this location is not allowed.'); ?> <div class="sh404sef-updates" id="sh404sef-updates"> <!-- start updates panel markup --> <table class="table table-bordered"> <?php if(!$this->updates->status) : ?> <thead> <tr> <td class="span3 shl-right"> <?php $button = ShlHtmlBs_Helper::button(JText::_('COM_SH404SEF_CHECK_UPDATES')); echo '<a href="javascript: void(0);" onclick="javascript: shSetupUpdates(\'forced\');" >' . $button .'</a>'; ?> </td> <td > <?php echo JText::_('COM_SH404SEF_ERROR_CHECKING_NEW_VERSION'); ?> </td> </tr> </thead> <?php else : ?> <thead> <tr> <td class="span3 shl-right"> <?php $button = ShlHtmlBs_Helper::button(JText::_('COM_SH404SEF_CHECK_UPDATES')); echo '<a href="javascript: void(0);" onclick="javascript: shSetupUpdates(\'forced\');" >' . $button .'</a>'; ?> </td> <td > <?php echo ShlHtmlBs_Helper::label($this->updates->statusMessage, $this->updates->shouldUpdate ? 'important' : 'success'); ?> </td> </tr> </thead> <?php if ($this->updates->shouldUpdate) : ?> <tr> <td class="span3 shl-right"> <?php echo ShlMvcLayout_Helper::render('com_sh404sef.updates.update_j3'); ?> </td> <td> <?php if (!empty( $this->updates->current)) { echo $this->updates->current . ' [' . '<a target="_blank" href="' . $this->escape( $this->updates->changelogLink) . '" >' . JText::_('COM_SH404SEF_VIEW_CHANGELOG') . '</a>]' . '&nbsp[' . '<a target="_blank" href="' . $this->escape( $this->updates->downloadLink) . '" >' . JText::_('COM_SH404SEF_GET_IT') . '</a>]'; } ?> </td> </tr> <tr> <td class="shl-right"> <?php echo JText::_( 'COM_SH404SEF_NOTES')?> </td> <td> <?php echo $this->escape($this->updates->note); ?> </td> </tr> <?php endif; endif; ?> </table> <!-- end updates panel markup --></div>
davidguillemet/fashionphotosub
administrator/components/com_sh404sef/views/default/tmpl/updates_j3.php
PHP
gpl-2.0
2,471
package com.meep.core.libs.configs; import net.minecraftforge.common.config.Configuration; /** * Created by poppypoppop on 22/12/2014. */ public class BiomeConfigHandler { //Catagories public static String general = "General"; public static String ids = "Biome IDs"; //Options public static int oasisID; public static void configOptions(Configuration config) { oasisID = config.getInt("Oasis Biome ID", ids, 40, 40, 128, "Oasis Biome ID"); } }
MagiciansArtificeTeam/MEEP
src/com/meep/core/libs/configs/BiomeConfigHandler.java
Java
gpl-2.0
485
<?php /** * Copyright (c) by the ACP3 Developers. * See the LICENSE file at the top-level module directory for licensing details. */ namespace ACP3\Core\Test\View\Renderer\Smarty\Filters; use ACP3\Core\Controller\AreaEnum; use ACP3\Core\Http\Request; use ACP3\Core\Test\View\Renderer\Smarty\AbstractPluginTest; use ACP3\Core\View\Renderer\Smarty\Filters\PageCssClasses; class PageCssClassesTest extends AbstractPluginTest { /** * @var PageCssClasses */ protected $plugin; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $pageCssClassesMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $requestMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $smartyInternalTemplateMock; protected function setUp() { $this->setUpMockObjects(); $this->plugin = new PageCssClasses( $this->pageCssClassesMock, $this->requestMock ); } private function setUpMockObjects() { $this->pageCssClassesMock = $this->createMock(\ACP3\Core\Assets\PageCssClasses::class); $this->requestMock = $this->createMock(Request::class); $this->smartyInternalTemplateMock = $this->createMock(\Smarty_Internal_Template::class); } /** * @return string */ protected function getExpectedExtensionName() { return 'output'; } public function testProcessInFrontend() { $this->setUpPageCssClassesMockExpectations(); $this->setUpRequestMockExpectations(); $expected = <<<HTML <html> <head> <title>Foobar</title> </head> <body class="foo foo-bar-baz foo-bar-pagetitle"> <p>Baz</p> </body> </html> HTML; $this->assertEquals( $expected, $this->plugin->__invoke($this->getTemplateContent(), $this->smartyInternalTemplateMock) ); } /** * @param int $getDetailsCalls */ private function setUpPageCssClassesMockExpectations($getDetailsCalls = 1) { $this->pageCssClassesMock ->expects($this->once()) ->method('getModule') ->willReturn('foo'); $this->pageCssClassesMock ->expects($this->once()) ->method('getControllerAction') ->willReturn('foo-bar-baz'); $this->pageCssClassesMock ->expects($this->exactly($getDetailsCalls)) ->method('getDetails') ->willReturn('foo-bar-pagetitle'); } /** * @param bool $isHomepage * @param string $area */ private function setUpRequestMockExpectations($isHomepage = false, $area = AreaEnum::AREA_FRONTEND) { $this->requestMock->expects($area === AreaEnum::AREA_FRONTEND ? $this->once() : $this->never()) ->method('isHomepage') ->willReturn($isHomepage); $this->requestMock->expects($this->once()) ->method('getArea') ->willReturn($area); } /** * @return string */ private function getTemplateContent() { return <<<HTML <html> <head> <title>Foobar</title> </head> <body> <p>Baz</p> </body> </html> HTML; } public function testProcessIsHomepage() { $this->setUpPageCssClassesMockExpectations(0); $this->setUpRequestMockExpectations(true); $expected = <<<HTML <html> <head> <title>Foobar</title> </head> <body class="foo foo-bar-baz is-homepage"> <p>Baz</p> </body> </html> HTML; $this->assertEquals( $expected, $this->plugin->__invoke($this->getTemplateContent(), $this->smartyInternalTemplateMock) ); } public function testProcessInAdmin() { $this->setUpPageCssClassesMockExpectations(0); $this->setUpRequestMockExpectations(false, AreaEnum::AREA_ADMIN); $expected = <<<HTML <html> <head> <title>Foobar</title> </head> <body class="foo foo-bar-baz in-admin"> <p>Baz</p> </body> </html> HTML; $this->assertEquals( $expected, $this->plugin->__invoke($this->getTemplateContent(), $this->smartyInternalTemplateMock) ); } public function testProcessWithNoHtmlBodyTag() { $templateContent = <<<HTML <p>Baz</p> HTML; $this->assertEquals( $templateContent, $this->plugin->__invoke($templateContent, $this->smartyInternalTemplateMock) ); } }
ACP3/core
Test/View/Renderer/Smarty/Filters/PageCssClassesTest.php
PHP
gpl-2.0
4,465
/* AbiWord * Copyright (C) 2003 Dom Lachowicz <cinamod@hotmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gr_Painter.h" #include "gr_Graphics.h" GR_Painter::GR_Painter (GR_Graphics * pGr, bool bDisableCarets) : m_pGr (pGr), m_bCaretsDisabled(bDisableCarets), m_bDoubleBufferingToken(false), m_bSuspendDrawingToken(false) { UT_ASSERT (m_pGr); if (m_bCaretsDisabled) m_pGr->disableAllCarets(); m_pGr->beginPaint (); } GR_Painter::~GR_Painter () { endDoubleBuffering(); m_pGr->endPaint (); if (m_bCaretsDisabled) m_pGr->enableAllCarets(); } void GR_Painter::drawLine(UT_sint32 x1, UT_sint32 y1, UT_sint32 x2, UT_sint32 y2) { m_pGr->drawLine (x1, y1, x2, y2); } #if XAP_DONTUSE_XOR #else void GR_Painter::xorLine(UT_sint32 x1, UT_sint32 y1, UT_sint32 x2, UT_sint32 y2) { m_pGr->xorLine (x1, y1, x2, y2); } void GR_Painter::xorRect(UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h) { m_pGr->xorRect (x, y, w, h); } void GR_Painter::xorRect(const UT_Rect& r) { m_pGr->xorRect (r); } #endif void GR_Painter::invertRect(const UT_Rect* pRect) { m_pGr->invertRect (pRect); } void GR_Painter::fillRect(const UT_RGBColor& c, UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h) { m_pGr->fillRect (c, x, y, w, h); } void GR_Painter::fillRect(GR_Image *pImg, const UT_Rect &src, const UT_Rect & dest) { m_pGr->fillRect (pImg, src, dest); } void GR_Painter::clearArea(UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h) { m_pGr->clearArea (x, y, w, h); } void GR_Painter::drawImage(GR_Image* pImg, UT_sint32 xDest, UT_sint32 yDest) { m_pGr->drawImage (pImg, xDest, yDest); } void GR_Painter::fillRect(const UT_RGBColor& c, const UT_Rect &r) { m_pGr->fillRect (c, r); } void GR_Painter::polygon(UT_RGBColor& c, UT_Point *pts, UT_uint32 nPoints) { m_pGr->polygon (c, pts, nPoints); } void GR_Painter::polyLine(UT_Point * pts, UT_uint32 nPoints) { m_pGr->polyLine(pts, nPoints); } void GR_Painter::drawGlyph(UT_uint32 glyph_idx, UT_sint32 xoff, UT_sint32 yoff) { m_pGr->drawGlyph (glyph_idx, xoff, yoff); } void GR_Painter::drawChars(const UT_UCSChar* pChars, int iCharOffset, int iLength, UT_sint32 xoff, UT_sint32 yoff, int* pCharWidths) { m_pGr->drawChars (pChars, iCharOffset, iLength, xoff, yoff, pCharWidths); } void GR_Painter::drawCharsRelativeToBaseline(const UT_UCSChar* pChars, int iCharOffset, int iLength, UT_sint32 xoff, UT_sint32 yoff, int* pCharWidths) { m_pGr->drawCharsRelativeToBaseline (pChars, iCharOffset, iLength, xoff, yoff, pCharWidths); } void GR_Painter::renderChars(GR_RenderInfo & ri) { m_pGr->renderChars(ri); } void GR_Painter::fillRect(GR_Graphics::GR_Color3D c, UT_Rect &r) { m_pGr->fillRect (c, r.left, r.top, r.width, r.height); } void GR_Painter::fillRect(GR_Graphics::GR_Color3D c, UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h) { m_pGr->fillRect (c, x, y, w, h); } GR_Image * GR_Painter::genImageFromRectangle(const UT_Rect & r) { return m_pGr->genImageFromRectangle(r); } void GR_Painter::beginDoubleBuffering() { m_bDoubleBufferingToken = m_pGr -> beginDoubleBuffering(); } void GR_Painter::endDoubleBuffering() { m_pGr -> endDoubleBuffering(m_bDoubleBufferingToken); m_bDoubleBufferingToken = false; } void GR_Painter::suspendDrawing() { m_bSuspendDrawingToken = m_pGr->suspendDrawing(); } void GR_Painter::resumeDrawing() { m_pGr->resumeDrawing(m_bSuspendDrawingToken); m_bSuspendDrawingToken = false; }
tanya-guza/abiword
src/af/gr/xp/gr_Painter.cpp
C++
gpl-2.0
4,306
"""Copyright (c) 2017 abhishek-sehgal954 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ import sys import os import re import subprocess import math import numpy as np import inkex import simpletransform from PIL import Image, ImageStat, ImageDraw import simplestyle inkex.localize() class ordered_dithering(inkex.Effect): def __init__(self): """Init the effect library and get options from gui.""" inkex.Effect.__init__(self) self.OptionParser.add_option("-t", "--width", action="store", type="int", dest="width", default=200, help="this variable will be used to resize the original selected image to a width of whatever \ you enter and height proportional to the new width, thus maintaining the aspect ratio") self.OptionParser.add_option("--inkscape_path", action="store", type="string", dest="inkscape_path", default="", help="") self.OptionParser.add_option("--temp_path", action="store", type="string", dest="temp_path", default="", help="") def effect(self): outfile = self.options.temp_path curfile = self.args[-1] self.exportPage(curfile,outfile) def draw_rectangle(self,(x, y), (l,b), color, parent, id_): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} attribs = {'style': simplestyle.formatStyle(style), 'x': str(x), 'y': str(y), 'width': str(l), 'height':str(b)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('rect', 'svg'), attribs) return obj def draw_circle(self,(x, y), r, color, parent, id_): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'r': str(r)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('circle', 'svg'), attribs) return obj def draw_ellipse(self,(x, y), (r1,r2), color, parent, id_,transform): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} if(transform == 1.5): attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} elif(transform == 3): attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} else: attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('ellipse', 'svg'), attribs) return obj def draw_svg(self,output,parent): startu = 0 endu = 0 for i in range(len(output)): for j in range(len(output[i])): if (output[i][j]==0): self.draw_circle((int((startu+startu+1)/2),int((endu+endu+1)/2)),1,'black',parent,'id') #dwg.add(dwg.circle((int((startu+startu+1)/2),int((endu+endu+1)/2)),1,fill='black')) startu = startu+2 endu = endu+2 startu = 0 #dwg.save() def intensity(self,arr): # calcluates intensity of a pixel from 0 to 9 mini = 999 maxi = 0 for i in range(len(arr)): for j in range(len(arr[0])): maxi = max(arr[i][j],maxi) mini = min(arr[i][j],mini) level = float(float(maxi-mini)/float(10)); brr = [[0]*len(arr[0]) for i in range(len(arr))] for i in range(10): l1 = mini+level*i l2 = l1+level for j in range(len(arr)): for k in range(len(arr[0])): if(arr[j][k] >= l1 and arr[j][k] <= l2): brr[j][k]=i return brr def order_dither(self,image): arr = np.asarray(image) brr = self.intensity(arr) crr = [[8, 3, 4], [6, 1, 2], [7, 5, 9]] drr = np.zeros((len(arr),len(arr[0]))) for i in range(len(arr)): for j in range(len(arr[0])): if(brr[i][j] > crr[i%3][j%3]): drr[i][j] = 255 else: drr[i][j] = 0 return drr def dithering(self,node,image): if image: basewidth = self.options.width wpercent = (basewidth/float(image.size[0])) hsize = int((float(image.size[1])*float(wpercent))) image = image.resize((basewidth,hsize), Image.ANTIALIAS) (width, height) = image.size nodeParent = node.getparent() nodeIndex = nodeParent.index(node) pixel2svg_group = inkex.etree.Element(inkex.addNS('g', 'svg')) pixel2svg_group.set('id', "%s_pixel2svg" % node.get('id')) nodeParent.insert(nodeIndex+1, pixel2svg_group) nodeParent.remove(node) image = image.convert("RGBA") pixel_data = image.load() if image.mode == "RGBA": for y in xrange(image.size[1]): for x in xrange(image.size[0]): if pixel_data[x, y][3] < 255: pixel_data[x, y] = (255, 255, 255, 255) image.thumbnail([image.size[0], image.size[1]], Image.ANTIALIAS) image = image.convert('L') self.draw_rectangle((0,0),(width,height),'white',pixel2svg_group,'id') output = self.order_dither(image) self.draw_svg(output,pixel2svg_group) else: inkex.errormsg(_("Bailing out: No supported image file or data found")) sys.exit(1) def exportPage(self, curfile, outfile): command = "%s %s --export-png %s" %(self.options.inkscape_path,curfile,outfile) p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = p.wait() f = p.stdout err = p.stderr img = Image.open(outfile) if (self.options.ids): for node in self.selected.itervalues(): found_image = True self.dithering(node,img) def main(): e = ordered_dithering() e.affect() exit() if __name__=="__main__": main()
abhishek-sehgal954/Inkscape_extensions_for_halftone_filters
SVG_to_SVG/svg_to_svg_ordered_dithering.py
Python
gpl-2.0
7,450
<?php session_start();?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <style type="text/css" media="screen"> @import url( <?php bloginfo('stylesheet_url'); ?> ); </style> <link href="<?php bloginfo('template_directory'); ?>/css/jquery.bxslider.css" rel="stylesheet" /> <!-- ICON --> <link rel="icon" href="<?php bloginfo('template_directory'); ?>/images/favicon.ico" type="image/x-icon"> <!-- FONTS --> <link href='http://fonts.googleapis.com/css?family=Rubik+One' rel='stylesheet' type='text/css'> <title> <?php if (is_home()){ bloginfo('name'); }elseif (is_category()){ single_cat_title(); echo ' - ' ; bloginfo('name'); }elseif (is_single()){ single_post_title(); }elseif (is_page()){ bloginfo('name'); echo ': '; single_post_title(); }else { wp_title('',true); } ?> </title> <?php wp_head(); ?> </head> <body> <div class="cart-list"> <div class="container"> <?php if (isset($_SESSION['cart'])): ?> <p class="col-md-6">Seja bem vindo</p> <div class="pull-right"> <p>Acesse sua <a href="<?php echo get_settings('home'); ?>/pedidos">lista de pedidos <span class="quant-cart glyphicon glyphicon-shopping-cart"></span></a></p> </div> <?php else: ?> <?php $_SESSION['cart']=array(); // Declaring session array?> <?php endif ?> </div> </div> <div id="menu-celular"> <span class='glyphicon glyphicon-menu-hamburger'></span> </div> <header> <div class="container"> <span class="col-md-4 col-md-offset-4"> <img src="<?php bloginfo('template_directory'); ?>/images/logoHeader.png"> </span> <ul class="header-menu"> <li><a href="<?php echo get_settings('home'); ?>">Home</a></li> <li id="menu-quem-somos"><a href="<?php echo get_settings('home'); ?>/#quem-somos">Quem somos</a></li> <?php $id_da_categoria = get_cat_id('produtos'); $link_da_categoria = get_category_link($id_da_categoria); ?> <li id="menu-nossos-produtos"><a href="<?php echo $link_da_categoria;?>">Produtos</a></li> <li id="menu-fale-conosco"><a href="<?php echo get_settings('home'); ?>/#fale-conosco">Fale conosco</a></li> </ul> </div> <!-- SEARCH --> <div class="col-md-6 search-header"> <form role="search" method="get" id="searchform" action="<?php echo get_option('home'); ?>"> <div class="input-group"> <input value="" name="s" id="s" type="text" class="form-control" placeholder="Procurando por..."> <span class="input-group-btn"> <button id="searchsubmit" value="" type="submit" class="btn btn-default" type="button"><i class="glyphicon glyphicon-search"></i></button> </span> </div> </form> </div> </div> </header> <!--FIM DO HEADER -->
redmustachedesign/boloradistribuidora
wp-content/themes/bolora/header.php
PHP
gpl-2.0
3,127
<?php /* * Pharinix Copyright (C) 2017 Pedro Pelaez <aaaaa976@gmail.com> * Sources https://github.com/PSF1/pharinix * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ if (!defined("CMS_VERSION")) { header("HTTP/1.0 404 Not Found"); die(""); } if (!class_exists("commandNodetypeGenerateDriver")) { class commandNodetypeGenerateDriver extends driverCommand { public static function runMe(&$params, $debug = true) { $resp = array("ok" => false); // Default values $params = array_merge(array( 'nodetype' => '', 'moduleslugname' => '', 'debug' => false, ), $params); $resp['ok'] = driverNodes::generateDriver($params['nodetype'], $params['moduleslugname'], $params['debug']); return $resp; } public static function getAccess($ignore = "") { $me = __FILE__; return parent::getAccess($me); } // public static function getAccessFlags() { // return driverUser::PERMISSION_FILE_ALL_EXECUTE; // } public static function getHelp() { return array( "package" => 'core', "description" => __("Generate two drivers, first a general controler and, if not exist, a user controler."), "parameters" => array( "nodetype" => __("Node type to control."), "moduleslugname" => __("Owner module slugname."), "debug" => __("Show generated code and node type definition."), ), "response" => array(), "type" => array( "parameters" => array( "nodetype" => "string", "moduleslugname" => "string", "debug" => "bool", ), "response" => array(), ), "echo" => false ); } } } return new commandNodetypeGenerateDriver();
PSF1/pharinix
bin/node_type/nodetypeGenerateDriver.php
PHP
gpl-2.0
2,853
/* * In The Name Of God * ======================================== * [] File Name : beehive-hello.go * * [] Creation Date : 13-11-2015 * * [] Created By : Parham Alvani (parham.alvani@gmail.com) * ======================================= */ /* * Copyright (c) 2015 Parham Alvani. */ package main import ( "log" bh "github.com/kandoo/beehive" ) const ( helloDict = "HelloDictionary" replicationFactor = 2 ) // Hello represents a message in our hello world example. type Hello struct { Name string // Name is the name of the person saying hello. } // Broad represents a broadcast message in our hello world example. type Broad struct { ID int // ID is the id of the broadcast message } // Rcvf receives the message and the context. func hrcvf(msg bh.Msg, ctx bh.RcvContext) error { // msg is an envelope around the Hello message. // You can retrieve the Hello, using msg.Data() and then // you need to assert that its a Hello. hello := msg.Data().(Hello) // Using ctx.Dict you can get (or create) a dictionary. dict := ctx.Dict(helloDict) // Using Get(), you can get the value associated with // a key in the dictionary. Keys are always string // and values are generic interface{}'s. v, err := dict.Get(hello.Name) // If there is an error, the entry is not in the // dictionary. Otherwise, we set cnt based on // the value we already have in the dictionary // for that name. cnt := 0 if err == nil { cnt = v.(int) } // Now we increment the count. cnt++ // And then we print the hello message. ctx.Printf("hello %s (%d)!\n", hello.Name, cnt) // Finally we update the count stored in the dictionary. return dict.Put(hello.Name, cnt) } func hmapf(msg bh.Msg, ctx bh.MapContext) bh.MappedCells { return bh.MappedCells{ bh.CellKey{ Dict: helloDict, Key: msg.Data().(Hello).Name, }, } } func brcvf(msg bh.Msg, ctx bh.RcvContext) error { ctx.Printf("broad[%v] message %d was received\n", msg.IsBroadCast(), msg.Data().(Broad).ID) return nil } func bmapf(msg bh.Msg, ctx bh.MapContext) bh.MappedCells { return bh.MappedCells{{}} } func main() { // Create the hello world application app := bh.NewApp("hello-world", bh.Persistent(replicationFactor)) // Register the handler for Hello messages. if err := app.HandleFunc(Hello{}, hmapf, hrcvf); err != nil { log.Fatalf("Hello Handle Func: %s", err) } // Register the handler for broad messages. if err := app.HandleFunc(Broad{}, bmapf, brcvf); err != nil { log.Fatalf("Board Handle Func: %s", err) } go bh.Emit(Hello{Name: "Parham Alvani"}) go bh.Emit(Hello{Name: "HamidReza Alvani"}) go bh.Emit(Broad{ID: 1}) if err := bh.Start(); err != nil { log.Fatalf("Start: %s", err) } }
1995parham/Learning
go/beehive-hello/beehive-hello.go
GO
gpl-2.0
2,717
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Area extends Model { public function curso() { return $this->belongsTo('App\Curso'); } public function docentes() { return $this->belongsToMany('App\Docente', 'docente_areas', 'area_id', 'docente_id'); } public function temas($value='') { $this->hasMany('App\Tema'); } }
Hassan93/openTima
app/Area.php
PHP
gpl-2.0
395
<?php /** * @package Joomla.Site * @subpackage Layout * * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; extract($displayData); /** * Layout variables * * @var stdClass $article Article as it comes from joomla models/helpers * @var array $options Array with options. Available options: * 'resolution' : Resolution of the thumbnail * 'force_png' : Convert always to PNG for transparent backgrounds * 'force_rewrite' : Force thumbnail regeneration * 'thumb_method' : Method to use to create the thumbnails. See JImage */ $layoutOptions = empty($options) ? new JInput : new JInput($options); //$images = json_decode($article->images); // Intro image available if (!empty($url)) { $imageUrl = $url; //$imageAlt = $images->image_intro_alt; } // Full text image available /*elseif (!empty($images->image_fulltext)) { $imageUrl = $images->image_fulltext; $imageAlt = $images->image_fulltext_alt; }*/ // Nothing to display else { return; } $resolution = $layoutOptions->get('resolution', '350x250'); // A thumbnail has been required if ($resolution) { $thumbUrl = JLayoutHelper::render( 'image.thumbnail', array( 'imageUrl' => $imageUrl, 'options' => $options ) ); if ($thumbUrl) { $imageUrl = $thumbUrl; } } ?> <?php /* ?><img src="<?php echo $imageUrl; ?>" alt="<?php echo $imageAlt; ?>" /><?php */ ?> <?php print_r($imageUrl); ?>
media-line/hig
templates/hignew/html/layouts/com_content/article/image.php
PHP
gpl-2.0
1,593
/////////////////////////////////////////////////////////////////////////////// // Name: src/aui/framemanager.cpp // Purpose: wxaui: wx advanced user interface - docking window manager // Author: Benjamin I. Williams // Modified by: // Created: 2005-05-17 // RCS-ID: $Id: framemanager.cpp 66980 2011-02-20 10:26:32Z TIK $ // Copyright: (C) Copyright 2005-2006, Kirix Corporation, All Rights Reserved // Licence: wxWindows Library Licence, Version 3.1 /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_AUI #include "wx/aui/framemanager.h" #include "wx/aui/dockart.h" #include "wx/aui/floatpane.h" #include "wx/aui/tabmdi.h" #include "wx/aui/auibar.h" #ifndef WX_PRECOMP #include "wx/panel.h" #include "wx/settings.h" #include "wx/app.h" #include "wx/dcclient.h" #include "wx/dcscreen.h" #include "wx/toolbar.h" #include "wx/mdi.h" #include "wx/image.h" #include "wx/statusbr.h" #endif WX_CHECK_BUILD_OPTIONS("wxAUI") #include "wx/arrimpl.cpp" WX_DECLARE_OBJARRAY(wxRect, wxAuiRectArray); WX_DEFINE_OBJARRAY(wxAuiRectArray) WX_DEFINE_OBJARRAY(wxAuiDockUIPartArray) WX_DEFINE_OBJARRAY(wxAuiDockInfoArray) WX_DEFINE_OBJARRAY(wxAuiPaneButtonArray) WX_DEFINE_OBJARRAY(wxAuiPaneInfoArray) wxAuiPaneInfo wxAuiNullPaneInfo; wxAuiDockInfo wxAuiNullDockInfo; DEFINE_EVENT_TYPE(wxEVT_AUI_PANE_BUTTON) DEFINE_EVENT_TYPE(wxEVT_AUI_PANE_CLOSE) DEFINE_EVENT_TYPE(wxEVT_AUI_PANE_MAXIMIZE) DEFINE_EVENT_TYPE(wxEVT_AUI_PANE_RESTORE) DEFINE_EVENT_TYPE(wxEVT_AUI_RENDER) DEFINE_EVENT_TYPE(wxEVT_AUI_FIND_MANAGER) #ifdef __WXMAC__ // a few defines to avoid nameclashes #define __MAC_OS_X_MEMORY_MANAGER_CLEAN__ 1 #define __AIFF__ #include "wx/mac/private.h" #endif #ifdef __WXMSW__ #include "wx/msw/wrapwin.h" #include "wx/msw/private.h" #endif IMPLEMENT_DYNAMIC_CLASS(wxAuiManagerEvent, wxEvent) IMPLEMENT_CLASS(wxAuiManager, wxEvtHandler) const int auiToolBarLayer = 10; #ifndef __WXGTK20__ class wxPseudoTransparentFrame : public wxFrame { public: wxPseudoTransparentFrame(wxWindow* parent = NULL, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString &name = wxT("frame")) : wxFrame(parent, id, title, pos, size, style | wxFRAME_SHAPED, name) { SetBackgroundStyle(wxBG_STYLE_CUSTOM); m_Amount=0; m_MaxWidth=0; m_MaxHeight=0; m_lastWidth=0; m_lastHeight=0; #ifdef __WXGTK__ m_CanSetShape = false; // have to wait for window create event on GTK #else m_CanSetShape = true; #endif m_Region = wxRegion(0, 0, 0, 0); SetTransparent(0); } virtual bool SetTransparent(wxByte alpha) { if (m_CanSetShape) { int w=100; // some defaults int h=100; GetClientSize(&w, &h); m_MaxWidth = w; m_MaxHeight = h; m_Amount = alpha; m_Region.Clear(); // m_Region.Union(0, 0, 1, m_MaxWidth); if (m_Amount) { for (int y=0; y<m_MaxHeight; y++) { // Reverse the order of the bottom 4 bits int j=((y&8)?1:0)|((y&4)?2:0)|((y&2)?4:0)|((y&1)?8:0); if ((j*16+8)<m_Amount) m_Region.Union(0, y, m_MaxWidth, 1); } } SetShape(m_Region); Refresh(); } return true; } void OnPaint(wxPaintEvent& WXUNUSED(event)) { wxPaintDC dc(this); if (m_Region.IsEmpty()) return; #ifdef __WXMAC__ dc.SetBrush(wxColour(128, 192, 255)); #else dc.SetBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_ACTIVECAPTION)); #endif dc.SetPen(*wxTRANSPARENT_PEN); wxRegionIterator upd(GetUpdateRegion()); // get the update rect list while (upd) { wxRect rect(upd.GetRect()); dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height); upd++; } } #ifdef __WXGTK__ void OnWindowCreate(wxWindowCreateEvent& WXUNUSED(event)) { m_CanSetShape=true; SetTransparent(0); } #endif void OnSize(wxSizeEvent& event) { // We sometimes get surplus size events if ((event.GetSize().GetWidth() == m_lastWidth) && (event.GetSize().GetHeight() == m_lastHeight)) { event.Skip(); return; } m_lastWidth = event.GetSize().GetWidth(); m_lastHeight = event.GetSize().GetHeight(); SetTransparent(m_Amount); m_Region.Intersect(0, 0, event.GetSize().GetWidth(), event.GetSize().GetHeight()); SetShape(m_Region); Refresh(); event.Skip(); } private: wxByte m_Amount; int m_MaxWidth; int m_MaxHeight; bool m_CanSetShape; int m_lastWidth,m_lastHeight; wxRegion m_Region; DECLARE_DYNAMIC_CLASS(wxPseudoTransparentFrame) DECLARE_EVENT_TABLE() }; IMPLEMENT_DYNAMIC_CLASS(wxPseudoTransparentFrame, wxFrame) BEGIN_EVENT_TABLE(wxPseudoTransparentFrame, wxFrame) EVT_PAINT(wxPseudoTransparentFrame::OnPaint) EVT_SIZE(wxPseudoTransparentFrame::OnSize) #ifdef __WXGTK__ EVT_WINDOW_CREATE(wxPseudoTransparentFrame::OnWindowCreate) #endif END_EVENT_TABLE() #else // __WXGTK20__ #include "wx/gtk/private.h" static void gtk_pseudo_window_realized_callback( GtkWidget *m_widget, void *win ) { wxSize disp = wxGetDisplaySize(); int amount = 128; wxRegion region; for (int y=0; y<disp.y; y++) { // Reverse the order of the bottom 4 bits int j=((y&8)?1:0)|((y&4)?2:0)|((y&2)?4:0)|((y&1)?8:0); if ((j*16+8)<amount) region.Union(0, y, disp.x, 1); } gdk_window_shape_combine_region(m_widget->window, region.GetRegion(), 0, 0); } class wxPseudoTransparentFrame: public wxFrame { public: wxPseudoTransparentFrame(wxWindow* parent = NULL, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE, const wxString &name = wxT("frame")) { if (!Create( parent, id, title, pos, size, style, name )) return; m_title = title; m_widget = gtk_window_new( GTK_WINDOW_POPUP ); g_signal_connect( m_widget, "realize", G_CALLBACK (gtk_pseudo_window_realized_callback), this ); GdkColor col; col.red = 128 * 256; col.green = 192 * 256; col.blue = 255 * 256; gtk_widget_modify_bg( m_widget, GTK_STATE_NORMAL, &col ); } bool SetTransparent(wxByte alpha) { return true; } private: DECLARE_DYNAMIC_CLASS(wxPseudoTransparentFrame) }; IMPLEMENT_DYNAMIC_CLASS(wxPseudoTransparentFrame, wxFrame) #endif // __WXGTK20__ // -- static utility functions -- static wxBitmap wxPaneCreateStippleBitmap() { unsigned char data[] = { 0,0,0,192,192,192, 192,192,192,0,0,0 }; wxImage img(2,2,data,true); return wxBitmap(img); } static void DrawResizeHint(wxDC& dc, const wxRect& rect) { wxBitmap stipple = wxPaneCreateStippleBitmap(); wxBrush brush(stipple); dc.SetBrush(brush); #ifdef __WXMSW__ PatBlt(GetHdcOf(dc), rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight(), PATINVERT); #else dc.SetPen(*wxTRANSPARENT_PEN); dc.SetLogicalFunction(wxXOR); dc.DrawRectangle(rect); #endif } // CopyDocksAndPanes() - this utility function creates copies of // the dock and pane info. wxAuiDockInfo's usually contain pointers // to wxAuiPaneInfo classes, thus this function is necessary to reliably // reconstruct that relationship in the new dock info and pane info arrays static void CopyDocksAndPanes(wxAuiDockInfoArray& dest_docks, wxAuiPaneInfoArray& dest_panes, const wxAuiDockInfoArray& src_docks, const wxAuiPaneInfoArray& src_panes) { dest_docks = src_docks; dest_panes = src_panes; int i, j, k, dock_count, pc1, pc2; for (i = 0, dock_count = dest_docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = dest_docks.Item(i); for (j = 0, pc1 = dock.panes.GetCount(); j < pc1; ++j) for (k = 0, pc2 = src_panes.GetCount(); k < pc2; ++k) if (dock.panes.Item(j) == &src_panes.Item(k)) dock.panes.Item(j) = &dest_panes.Item(k); } } // GetMaxLayer() is an internal function which returns // the highest layer inside the specified dock static int GetMaxLayer(const wxAuiDockInfoArray& docks, int dock_direction) { int i, dock_count, max_layer = 0; for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = docks.Item(i); if (dock.dock_direction == dock_direction && dock.dock_layer > max_layer && !dock.fixed) max_layer = dock.dock_layer; } return max_layer; } // GetMaxRow() is an internal function which returns // the highest layer inside the specified dock static int GetMaxRow(const wxAuiPaneInfoArray& panes, int direction, int layer) { int i, pane_count, max_row = 0; for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = panes.Item(i); if (pane.dock_direction == direction && pane.dock_layer == layer && pane.dock_row > max_row) max_row = pane.dock_row; } return max_row; } // DoInsertDockLayer() is an internal function that inserts a new dock // layer by incrementing all existing dock layer values by one static void DoInsertDockLayer(wxAuiPaneInfoArray& panes, int dock_direction, int dock_layer) { int i, pane_count; for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = panes.Item(i); if (!pane.IsFloating() && pane.dock_direction == dock_direction && pane.dock_layer >= dock_layer) pane.dock_layer++; } } // DoInsertDockLayer() is an internal function that inserts a new dock // row by incrementing all existing dock row values by one static void DoInsertDockRow(wxAuiPaneInfoArray& panes, int dock_direction, int dock_layer, int dock_row) { int i, pane_count; for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = panes.Item(i); if (!pane.IsFloating() && pane.dock_direction == dock_direction && pane.dock_layer == dock_layer && pane.dock_row >= dock_row) pane.dock_row++; } } // DoInsertDockLayer() is an internal function that inserts a space for // another dock pane by incrementing all existing dock row values by one static void DoInsertPane(wxAuiPaneInfoArray& panes, int dock_direction, int dock_layer, int dock_row, int dock_pos) { int i, pane_count; for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = panes.Item(i); if (!pane.IsFloating() && pane.dock_direction == dock_direction && pane.dock_layer == dock_layer && pane.dock_row == dock_row && pane.dock_pos >= dock_pos) pane.dock_pos++; } } // FindDocks() is an internal function that returns a list of docks which meet // the specified conditions in the parameters and returns a sorted array // (sorted by layer and then row) static void FindDocks(wxAuiDockInfoArray& docks, int dock_direction, int dock_layer, int dock_row, wxAuiDockInfoPtrArray& arr) { int begin_layer = dock_layer; int end_layer = dock_layer; int begin_row = dock_row; int end_row = dock_row; int dock_count = docks.GetCount(); int layer, row, i, max_row = 0, max_layer = 0; // discover the maximum dock layer and the max row for (i = 0; i < dock_count; ++i) { max_row = wxMax(max_row, docks.Item(i).dock_row); max_layer = wxMax(max_layer, docks.Item(i).dock_layer); } // if no dock layer was specified, search all dock layers if (dock_layer == -1) { begin_layer = 0; end_layer = max_layer; } // if no dock row was specified, search all dock row if (dock_row == -1) { begin_row = 0; end_row = max_row; } arr.Clear(); for (layer = begin_layer; layer <= end_layer; ++layer) for (row = begin_row; row <= end_row; ++row) for (i = 0; i < dock_count; ++i) { wxAuiDockInfo& d = docks.Item(i); if (dock_direction == -1 || dock_direction == d.dock_direction) { if (d.dock_layer == layer && d.dock_row == row) arr.Add(&d); } } } // FindPaneInDock() looks up a specified window pointer inside a dock. // If found, the corresponding wxAuiPaneInfo pointer is returned, otherwise NULL. static wxAuiPaneInfo* FindPaneInDock(const wxAuiDockInfo& dock, wxWindow* window) { int i, count = dock.panes.GetCount(); for (i = 0; i < count; ++i) { wxAuiPaneInfo* p = dock.panes.Item(i); if (p->window == window) return p; } return NULL; } // RemovePaneFromDocks() removes a pane window from all docks // with a possible exception specified by parameter "ex_cept" static void RemovePaneFromDocks(wxAuiDockInfoArray& docks, wxAuiPaneInfo& pane, wxAuiDockInfo* ex_cept = NULL ) { int i, dock_count; for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& d = docks.Item(i); if (&d == ex_cept) continue; wxAuiPaneInfo* pi = FindPaneInDock(d, pane.window); if (pi) d.panes.Remove(pi); } } /* // This function works fine, and may be used in the future // RenumberDockRows() takes a dock and assigns sequential numbers // to existing rows. Basically it takes out the gaps; so if a // dock has rows with numbers 0,2,5, they will become 0,1,2 static void RenumberDockRows(wxAuiDockInfoPtrArray& docks) { int i, dock_count; for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = *docks.Item(i); dock.dock_row = i; int j, pane_count; for (j = 0, pane_count = dock.panes.GetCount(); j < pane_count; ++j) dock.panes.Item(j)->dock_row = i; } } */ // SetActivePane() sets the active pane, as well as cycles through // every other pane and makes sure that all others' active flags // are turned off static void SetActivePane(wxAuiPaneInfoArray& panes, wxWindow* active_pane) { int i, pane_count; for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = panes.Item(i); pane.state &= ~wxAuiPaneInfo::optionActive; if (pane.window == active_pane) pane.state |= wxAuiPaneInfo::optionActive; } } // this function is used to sort panes by dock position static int PaneSortFunc(wxAuiPaneInfo** p1, wxAuiPaneInfo** p2) { return ((*p1)->dock_pos < (*p2)->dock_pos) ? -1 : 1; } // -- wxAuiManager class implementation -- BEGIN_EVENT_TABLE(wxAuiManager, wxEvtHandler) EVT_AUI_PANE_BUTTON(wxAuiManager::OnPaneButton) EVT_AUI_RENDER(wxAuiManager::OnRender) EVT_PAINT(wxAuiManager::OnPaint) EVT_ERASE_BACKGROUND(wxAuiManager::OnEraseBackground) EVT_SIZE(wxAuiManager::OnSize) EVT_SET_CURSOR(wxAuiManager::OnSetCursor) EVT_LEFT_DOWN(wxAuiManager::OnLeftDown) EVT_LEFT_UP(wxAuiManager::OnLeftUp) EVT_MOTION(wxAuiManager::OnMotion) EVT_LEAVE_WINDOW(wxAuiManager::OnLeaveWindow) EVT_CHILD_FOCUS(wxAuiManager::OnChildFocus) EVT_AUI_FIND_MANAGER(wxAuiManager::OnFindManager) EVT_TIMER(101, wxAuiManager::OnHintFadeTimer) END_EVENT_TABLE() wxAuiManager::wxAuiManager(wxWindow* managed_wnd, unsigned int flags) { m_action = actionNone; m_action_window = NULL; m_last_mouse_move = wxPoint(); m_hover_button = NULL; m_art = new wxAuiDefaultDockArt; m_hint_wnd = NULL; m_flags = flags; m_skipping = false; m_has_maximized = false; m_frame = NULL; m_dock_constraint_x = 0.3; m_dock_constraint_y = 0.3; m_reserved = NULL; if (managed_wnd) { SetManagedWindow(managed_wnd); } } wxAuiManager::~wxAuiManager() { // NOTE: It's possible that the windows have already been destroyed by the // time this dtor is called, so this loop can result in memory access via // invalid pointers, resulting in a crash. So it will be disabled while // waiting for a better solution. #if 0 for(size_t i = 0; i < m_panes.size(); i++ ) { wxAuiPaneInfo& pinfo = m_panes[i]; if( pinfo.window && !pinfo.window->GetParent() ) delete pinfo.window; } #endif delete m_art; } // creates a floating frame for the windows wxAuiFloatingFrame* wxAuiManager::CreateFloatingFrame(wxWindow* parent, const wxAuiPaneInfo& pane_info) { return new wxAuiFloatingFrame(parent, this, pane_info); } // GetPane() looks up a wxAuiPaneInfo structure based // on the supplied window pointer. Upon failure, GetPane() // returns an empty wxAuiPaneInfo, a condition which can be checked // by calling wxAuiPaneInfo::IsOk(). // // The pane info's structure may then be modified. Once a pane's // info is modified, wxAuiManager::Update() must be called to // realize the changes in the UI. wxAuiPaneInfo& wxAuiManager::GetPane(wxWindow* window) { int i, pane_count; for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.window == window) return p; } return wxAuiNullPaneInfo; } // this version of GetPane() looks up a pane based on a // 'pane name', see above comment for more info wxAuiPaneInfo& wxAuiManager::GetPane(const wxString& name) { int i, pane_count; for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.name == name) return p; } return wxAuiNullPaneInfo; } // GetAllPanes() returns a reference to all the pane info structures wxAuiPaneInfoArray& wxAuiManager::GetAllPanes() { return m_panes; } // HitTest() is an internal function which determines // which UI item the specified coordinates are over // (x,y) specify a position in client coordinates wxAuiDockUIPart* wxAuiManager::HitTest(int x, int y) { wxAuiDockUIPart* result = NULL; int i, part_count; for (i = 0, part_count = m_uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart* item = &m_uiparts.Item(i); // we are not interested in typeDock, because this space // isn't used to draw anything, just for measurements; // besides, the entire dock area is covered with other // rectangles, which we are interested in. if (item->type == wxAuiDockUIPart::typeDock) continue; // if we already have a hit on a more specific item, we are not // interested in a pane hit. If, however, we don't already have // a hit, returning a pane hit is necessary for some operations if ((item->type == wxAuiDockUIPart::typePane || item->type == wxAuiDockUIPart::typePaneBorder) && result) continue; // if the point is inside the rectangle, we have a hit if (item->rect.Contains(x,y)) result = item; } return result; } // SetFlags() and GetFlags() allow the owner to set various // options which are global to wxAuiManager void wxAuiManager::SetFlags(unsigned int flags) { // find out if we have to call UpdateHintWindowConfig() bool update_hint_wnd = false; unsigned int hint_mask = wxAUI_MGR_TRANSPARENT_HINT | wxAUI_MGR_VENETIAN_BLINDS_HINT | wxAUI_MGR_RECTANGLE_HINT; if ((flags & hint_mask) != (m_flags & hint_mask)) update_hint_wnd = true; // set the new flags m_flags = flags; if (update_hint_wnd) { UpdateHintWindowConfig(); } } unsigned int wxAuiManager::GetFlags() const { return m_flags; } // Convenience function bool wxAuiManager_HasLiveResize(wxAuiManager& manager) { // With Core Graphics on Mac, it's not possible to show sash feedback, // so we'll always use live update instead. #if defined(__WXMAC__) && wxMAC_USE_CORE_GRAPHICS return true; #else return (manager.GetFlags() & wxAUI_MGR_LIVE_RESIZE) == wxAUI_MGR_LIVE_RESIZE; #endif } // don't use these anymore as they are deprecated // use Set/GetManagedFrame() instead void wxAuiManager::SetFrame(wxFrame* frame) { SetManagedWindow((wxWindow*)frame); } wxFrame* wxAuiManager::GetFrame() const { return (wxFrame*)m_frame; } // this function will return the aui manager for a given // window. The |window| parameter should be any child window // or grand-child window (and so on) of the frame/window // managed by wxAuiManager. The |window| parameter does not // need to be managed by the manager itself. wxAuiManager* wxAuiManager::GetManager(wxWindow* window) { wxAuiManagerEvent evt(wxEVT_AUI_FIND_MANAGER); evt.SetManager(NULL); evt.ResumePropagation(wxEVENT_PROPAGATE_MAX); if (!window->ProcessEvent(evt)) return NULL; return evt.GetManager(); } void wxAuiManager::UpdateHintWindowConfig() { // find out if the the system can do transparent frames bool can_do_transparent = false; wxWindow* w = m_frame; while (w) { if (w->IsKindOf(CLASSINFO(wxFrame))) { wxFrame* f = wx_static_cast(wxFrame*, w); can_do_transparent = f->CanSetTransparent(); break; } w = w->GetParent(); } // if there is an existing hint window, delete it if (m_hint_wnd) { m_hint_wnd->Destroy(); m_hint_wnd = NULL; } m_hint_fademax = 50; m_hint_wnd = NULL; if ((m_flags & wxAUI_MGR_TRANSPARENT_HINT) && can_do_transparent) { // Make a window to use for a transparent hint #if defined(__WXMSW__) || defined(__WXGTK__) m_hint_wnd = new wxFrame(m_frame, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(1,1), wxFRAME_TOOL_WINDOW | wxFRAME_FLOAT_ON_PARENT | wxFRAME_NO_TASKBAR | wxNO_BORDER); m_hint_wnd->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_ACTIVECAPTION)); #elif defined(__WXMAC__) // Using a miniframe with float and tool styles keeps the parent // frame activated and highlighted as such... m_hint_wnd = new wxMiniFrame(m_frame, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(1,1), wxFRAME_FLOAT_ON_PARENT | wxFRAME_TOOL_WINDOW ); // Can't set the bg colour of a Frame in wxMac wxPanel* p = new wxPanel(m_hint_wnd); // The default wxSYS_COLOUR_ACTIVECAPTION colour is a light silver // color that is really hard to see, especially transparent. // Until a better system color is decided upon we'll just use // blue. p->SetBackgroundColour(*wxBLUE); #endif } else { if ((m_flags & wxAUI_MGR_TRANSPARENT_HINT) != 0 || (m_flags & wxAUI_MGR_VENETIAN_BLINDS_HINT) != 0) { // system can't support transparent fade, or the venetian // blinds effect was explicitly requested m_hint_wnd = new wxPseudoTransparentFrame(m_frame, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(1,1), wxFRAME_TOOL_WINDOW | wxFRAME_FLOAT_ON_PARENT | wxFRAME_NO_TASKBAR | wxNO_BORDER); m_hint_fademax = 128; } } } // SetManagedWindow() is usually called once when the frame // manager class is being initialized. "frame" specifies // the frame which should be managed by the frame mananger void wxAuiManager::SetManagedWindow(wxWindow* wnd) { wxASSERT_MSG(wnd, wxT("specified window must be non-NULL")); m_frame = wnd; m_frame->PushEventHandler(this); #if wxUSE_MDI // if the owner is going to manage an MDI parent frame, // we need to add the MDI client window as the default // center pane if (m_frame->IsKindOf(CLASSINFO(wxMDIParentFrame))) { wxMDIParentFrame* mdi_frame = (wxMDIParentFrame*)m_frame; wxWindow* client_window = mdi_frame->GetClientWindow(); wxASSERT_MSG(client_window, wxT("Client window is NULL!")); AddPane(client_window, wxAuiPaneInfo().Name(wxT("mdiclient")). CenterPane().PaneBorder(false)); } else if (m_frame->IsKindOf(CLASSINFO(wxAuiMDIParentFrame))) { wxAuiMDIParentFrame* mdi_frame = (wxAuiMDIParentFrame*)m_frame; wxAuiMDIClientWindow* client_window = mdi_frame->GetClientWindow(); wxASSERT_MSG(client_window, wxT("Client window is NULL!")); AddPane(client_window, wxAuiPaneInfo().Name(wxT("mdiclient")). CenterPane().PaneBorder(false)); } #endif UpdateHintWindowConfig(); } // UnInit() must be called, usually in the destructor // of the frame class. If it is not called, usually this // will result in a crash upon program exit void wxAuiManager::UnInit() { if (m_frame) { m_frame->RemoveEventHandler(this); } } // GetManagedWindow() returns the window pointer being managed wxWindow* wxAuiManager::GetManagedWindow() const { return m_frame; } wxAuiDockArt* wxAuiManager::GetArtProvider() const { return m_art; } void wxAuiManager::ProcessMgrEvent(wxAuiManagerEvent& event) { // first, give the owner frame a chance to override if (m_frame) { if (m_frame->ProcessEvent(event)) return; } ProcessEvent(event); } // SetArtProvider() instructs wxAuiManager to use the // specified art provider for all drawing calls. This allows // plugable look-and-feel features. The pointer that is // passed to this method subsequently belongs to wxAuiManager, // and is deleted in the frame manager destructor void wxAuiManager::SetArtProvider(wxAuiDockArt* art_provider) { // delete the last art provider, if any delete m_art; // assign the new art provider m_art = art_provider; } bool wxAuiManager::AddPane(wxWindow* window, const wxAuiPaneInfo& pane_info) { wxASSERT_MSG(window, wxT("NULL window ptrs are not allowed")); // check if the pane has a valid window if (!window) return false; // check if the window is already managed by us if (GetPane(pane_info.window).IsOk()) return false; // check if the pane name already exists, this could reveal a // bug in the library user's application bool already_exists = false; if (!pane_info.name.empty() && GetPane(pane_info.name).IsOk()) { wxFAIL_MSG(wxT("A pane with that name already exists in the manager!")); already_exists = true; } // if the new pane is docked then we should undo maximize if (pane_info.IsDocked()) RestoreMaximizedPane(); m_panes.Add(pane_info); wxAuiPaneInfo& pinfo = m_panes.Last(); // set the pane window pinfo.window = window; // if the pane's name identifier is blank, create a random string if (pinfo.name.empty() || already_exists) { pinfo.name.Printf(wxT("%08lx%08x%08x%08lx"), ((unsigned long)pinfo.window) & 0xffffffff, (unsigned int)time(NULL), #ifdef __WXWINCE__ (unsigned int)GetTickCount(), #else (unsigned int)clock(), #endif (unsigned long)m_panes.GetCount()); } // set initial proportion (if not already set) if (pinfo.dock_proportion == 0) pinfo.dock_proportion = 100000; if (pinfo.HasMaximizeButton()) { wxAuiPaneButton button; button.button_id = wxAUI_BUTTON_MAXIMIZE_RESTORE; pinfo.buttons.Add(button); } if (pinfo.HasPinButton()) { wxAuiPaneButton button; button.button_id = wxAUI_BUTTON_PIN; pinfo.buttons.Add(button); } if (pinfo.HasCloseButton()) { wxAuiPaneButton button; button.button_id = wxAUI_BUTTON_CLOSE; pinfo.buttons.Add(button); } if (pinfo.HasGripper()) { if (pinfo.window->IsKindOf(CLASSINFO(wxAuiToolBar))) { // prevent duplicate gripper -- both wxAuiManager and wxAuiToolBar // have a gripper control. The toolbar's built-in gripper // meshes better with the look and feel of the control than ours, // so turn wxAuiManager's gripper off, and the toolbar's on. wxAuiToolBar* tb = wx_static_cast(wxAuiToolBar*, pinfo.window); pinfo.SetFlag(wxAuiPaneInfo::optionGripper, false); tb->SetGripperVisible(true); } } if (pinfo.best_size == wxDefaultSize && pinfo.window) { pinfo.best_size = pinfo.window->GetClientSize(); if (pinfo.window->IsKindOf(CLASSINFO(wxToolBar))) { // GetClientSize() doesn't get the best size for // a toolbar under some newer versions of wxWidgets, // so use GetBestSize() pinfo.best_size = pinfo.window->GetBestSize(); // for some reason, wxToolBar::GetBestSize() is returning // a size that is a pixel shy of the correct amount. // I believe this to be the correct action, until // wxToolBar::GetBestSize() is fixed. Is this assumption // correct? // commented out by JACS 2007-9-08 after having added a pixel in wxMSW's wxToolBar::DoGetBestSize() // pinfo.best_size.y++; } if (pinfo.min_size != wxDefaultSize) { if (pinfo.best_size.x < pinfo.min_size.x) pinfo.best_size.x = pinfo.min_size.x; if (pinfo.best_size.y < pinfo.min_size.y) pinfo.best_size.y = pinfo.min_size.y; } } return true; } bool wxAuiManager::AddPane(wxWindow* window, int direction, const wxString& caption) { wxAuiPaneInfo pinfo; pinfo.Caption(caption); switch (direction) { case wxTOP: pinfo.Top(); break; case wxBOTTOM: pinfo.Bottom(); break; case wxLEFT: pinfo.Left(); break; case wxRIGHT: pinfo.Right(); break; case wxCENTER: pinfo.CenterPane(); break; } return AddPane(window, pinfo); } bool wxAuiManager::AddPane(wxWindow* window, const wxAuiPaneInfo& pane_info, const wxPoint& drop_pos) { if (!AddPane(window, pane_info)) return false; wxAuiPaneInfo& pane = GetPane(window); DoDrop(m_docks, m_panes, pane, drop_pos, wxPoint(0,0)); return true; } bool wxAuiManager::InsertPane(wxWindow* window, const wxAuiPaneInfo& pane_info, int insert_level) { wxASSERT_MSG(window, wxT("NULL window ptrs are not allowed")); // shift the panes around, depending on the insert level switch (insert_level) { case wxAUI_INSERT_PANE: DoInsertPane(m_panes, pane_info.dock_direction, pane_info.dock_layer, pane_info.dock_row, pane_info.dock_pos); break; case wxAUI_INSERT_ROW: DoInsertDockRow(m_panes, pane_info.dock_direction, pane_info.dock_layer, pane_info.dock_row); break; case wxAUI_INSERT_DOCK: DoInsertDockLayer(m_panes, pane_info.dock_direction, pane_info.dock_layer); break; } // if the window already exists, we are basically just moving/inserting the // existing window. If it doesn't exist, we need to add it and insert it wxAuiPaneInfo& existing_pane = GetPane(window); if (!existing_pane.IsOk()) { return AddPane(window, pane_info); } else { if (pane_info.IsFloating()) { existing_pane.Float(); if (pane_info.floating_pos != wxDefaultPosition) existing_pane.FloatingPosition(pane_info.floating_pos); if (pane_info.floating_size != wxDefaultSize) existing_pane.FloatingSize(pane_info.floating_size); } else { // if the new pane is docked then we should undo maximize RestoreMaximizedPane(); existing_pane.Direction(pane_info.dock_direction); existing_pane.Layer(pane_info.dock_layer); existing_pane.Row(pane_info.dock_row); existing_pane.Position(pane_info.dock_pos); } } return true; } // DetachPane() removes a pane from the frame manager. This // method will not destroy the window that is removed. bool wxAuiManager::DetachPane(wxWindow* window) { wxASSERT_MSG(window, wxT("NULL window ptrs are not allowed")); int i, count; for (i = 0, count = m_panes.GetCount(); i < count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.window == window) { if (p.frame) { // we have a floating frame which is being detached. We need to // reparent it to m_frame and destroy the floating frame // reduce flicker p.window->SetSize(1,1); if (p.frame->IsShown()) p.frame->Show(false); // reparent to m_frame and destroy the pane if (m_action_window == p.frame) { m_action_window = NULL; } p.window->Reparent(m_frame); p.frame->SetSizer(NULL); p.frame->Destroy(); p.frame = NULL; } // make sure there are no references to this pane in our uiparts, // just in case the caller doesn't call Update() immediately after // the DetachPane() call. This prevets obscure crashes which would // happen at window repaint if the caller forgets to call Update() int pi, part_count; for (pi = 0, part_count = (int)m_uiparts.GetCount(); pi < part_count; ++pi) { wxAuiDockUIPart& part = m_uiparts.Item(pi); if (part.pane == &p) { m_uiparts.RemoveAt(pi); part_count--; pi--; continue; } } m_panes.RemoveAt(i); return true; } } return false; } // ClosePane() destroys or hides the pane depending on its flags void wxAuiManager::ClosePane(wxAuiPaneInfo& pane_info) { // if we were maximized, restore if (pane_info.IsMaximized()) { RestorePane(pane_info); } // first, hide the window if (pane_info.window && pane_info.window->IsShown()) { pane_info.window->Show(false); } // make sure that we are the parent of this window if (pane_info.window && pane_info.window->GetParent() != m_frame) { pane_info.window->Reparent(m_frame); } // if we have a frame, destroy it if (pane_info.frame) { pane_info.frame->Destroy(); pane_info.frame = NULL; } // now we need to either destroy or hide the pane if (pane_info.IsDestroyOnClose()) { wxWindow * window = pane_info.window; DetachPane(window); if (window) { window->Destroy(); } } else { pane_info.Hide(); } } void wxAuiManager::MaximizePane(wxAuiPaneInfo& pane_info) { int i, pane_count; // un-maximize and hide all other panes for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (!p.IsToolbar() && !p.IsFloating()) { p.Restore(); // save hidden state p.SetFlag(wxAuiPaneInfo::savedHiddenState, p.HasFlag(wxAuiPaneInfo::optionHidden)); // hide the pane, because only the newly // maximized pane should show p.Hide(); } } // mark ourselves maximized pane_info.Maximize(); pane_info.Show(); m_has_maximized = true; // last, show the window if (pane_info.window && !pane_info.window->IsShown()) { pane_info.window->Show(true); } } void wxAuiManager::RestorePane(wxAuiPaneInfo& pane_info) { int i, pane_count; // restore all the panes for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (!p.IsToolbar() && !p.IsFloating()) { p.SetFlag(wxAuiPaneInfo::optionHidden, p.HasFlag(wxAuiPaneInfo::savedHiddenState)); } } // mark ourselves non-maximized pane_info.Restore(); m_has_maximized = false; // last, show the window if (pane_info.window && !pane_info.window->IsShown()) { pane_info.window->Show(true); } } void wxAuiManager::RestoreMaximizedPane() { int i, pane_count; // restore all the panes for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.IsMaximized()) { RestorePane(p); break; } } } // EscapeDelimiters() changes ";" into "\;" and "|" into "\|" // in the input string. This is an internal functions which is // used for saving perspectives static wxString EscapeDelimiters(const wxString& s) { wxString result; result.Alloc(s.length()); const wxChar* ch = s.c_str(); while (*ch) { if (*ch == wxT(';') || *ch == wxT('|')) result += wxT('\\'); result += *ch; ++ch; } return result; } wxString wxAuiManager::SavePaneInfo(wxAuiPaneInfo& pane) { wxString result = wxT("name="); result += EscapeDelimiters(pane.name); result += wxT(";"); result += wxT("caption="); result += EscapeDelimiters(pane.caption); result += wxT(";"); result += wxString::Format(wxT("state=%u;"), pane.state); result += wxString::Format(wxT("dir=%d;"), pane.dock_direction); result += wxString::Format(wxT("layer=%d;"), pane.dock_layer); result += wxString::Format(wxT("row=%d;"), pane.dock_row); result += wxString::Format(wxT("pos=%d;"), pane.dock_pos); result += wxString::Format(wxT("prop=%d;"), pane.dock_proportion); result += wxString::Format(wxT("bestw=%d;"), pane.best_size.x); result += wxString::Format(wxT("besth=%d;"), pane.best_size.y); result += wxString::Format(wxT("minw=%d;"), pane.min_size.x); result += wxString::Format(wxT("minh=%d;"), pane.min_size.y); result += wxString::Format(wxT("maxw=%d;"), pane.max_size.x); result += wxString::Format(wxT("maxh=%d;"), pane.max_size.y); result += wxString::Format(wxT("floatx=%d;"), pane.floating_pos.x); result += wxString::Format(wxT("floaty=%d;"), pane.floating_pos.y); result += wxString::Format(wxT("floatw=%d;"), pane.floating_size.x); result += wxString::Format(wxT("floath=%d"), pane.floating_size.y); return result; } // Load a "pane" with the pane infor settings in pane_part void wxAuiManager::LoadPaneInfo(wxString pane_part, wxAuiPaneInfo &pane) { // replace escaped characters so we can // split up the string easily pane_part.Replace(wxT("\\|"), wxT("\a")); pane_part.Replace(wxT("\\;"), wxT("\b")); while(1) { wxString val_part = pane_part.BeforeFirst(wxT(';')); pane_part = pane_part.AfterFirst(wxT(';')); wxString val_name = val_part.BeforeFirst(wxT('=')); wxString value = val_part.AfterFirst(wxT('=')); val_name.MakeLower(); val_name.Trim(true); val_name.Trim(false); value.Trim(true); value.Trim(false); if (val_name.empty()) break; if (val_name == wxT("name")) pane.name = value; else if (val_name == wxT("caption")) pane.caption = value; else if (val_name == wxT("state")) pane.state = (unsigned int)wxAtoi(value.c_str()); else if (val_name == wxT("dir")) pane.dock_direction = wxAtoi(value.c_str()); else if (val_name == wxT("layer")) pane.dock_layer = wxAtoi(value.c_str()); else if (val_name == wxT("row")) pane.dock_row = wxAtoi(value.c_str()); else if (val_name == wxT("pos")) pane.dock_pos = wxAtoi(value.c_str()); else if (val_name == wxT("prop")) pane.dock_proportion = wxAtoi(value.c_str()); else if (val_name == wxT("bestw")) pane.best_size.x = wxAtoi(value.c_str()); else if (val_name == wxT("besth")) pane.best_size.y = wxAtoi(value.c_str()); else if (val_name == wxT("minw")) pane.min_size.x = wxAtoi(value.c_str()); else if (val_name == wxT("minh")) pane.min_size.y = wxAtoi(value.c_str()); else if (val_name == wxT("maxw")) pane.max_size.x = wxAtoi(value.c_str()); else if (val_name == wxT("maxh")) pane.max_size.y = wxAtoi(value.c_str()); else if (val_name == wxT("floatx")) pane.floating_pos.x = wxAtoi(value.c_str()); else if (val_name == wxT("floaty")) pane.floating_pos.y = wxAtoi(value.c_str()); else if (val_name == wxT("floatw")) pane.floating_size.x = wxAtoi(value.c_str()); else if (val_name == wxT("floath")) pane.floating_size.y = wxAtoi(value.c_str()); else { wxFAIL_MSG(wxT("Bad Perspective String")); } } // replace escaped characters so we can // split up the string easily pane.name.Replace(wxT("\a"), wxT("|")); pane.name.Replace(wxT("\b"), wxT(";")); pane.caption.Replace(wxT("\a"), wxT("|")); pane.caption.Replace(wxT("\b"), wxT(";")); pane_part.Replace(wxT("\a"), wxT("|")); pane_part.Replace(wxT("\b"), wxT(";")); return; } // SavePerspective() saves all pane information as a single string. // This string may later be fed into LoadPerspective() to restore // all pane settings. This save and load mechanism allows an // exact pane configuration to be saved and restored at a later time wxString wxAuiManager::SavePerspective() { wxString result; result.Alloc(500); result = wxT("layout2|"); int pane_i, pane_count = m_panes.GetCount(); for (pane_i = 0; pane_i < pane_count; ++pane_i) { wxAuiPaneInfo& pane = m_panes.Item(pane_i); result += SavePaneInfo(pane)+wxT("|"); } int dock_i, dock_count = m_docks.GetCount(); for (dock_i = 0; dock_i < dock_count; ++dock_i) { wxAuiDockInfo& dock = m_docks.Item(dock_i); result += wxString::Format(wxT("dock_size(%d,%d,%d)=%d|"), dock.dock_direction, dock.dock_layer, dock.dock_row, dock.size); } return result; } // LoadPerspective() loads a layout which was saved with SavePerspective() // If the "update" flag parameter is true, the GUI will immediately be updated bool wxAuiManager::LoadPerspective(const wxString& layout, bool update) { wxString input = layout; wxString part; // check layout string version // 'layout1' = wxAUI 0.9.0 - wxAUI 0.9.2 // 'layout2' = wxAUI 0.9.2 (wxWidgets 2.8) part = input.BeforeFirst(wxT('|')); input = input.AfterFirst(wxT('|')); part.Trim(true); part.Trim(false); if (part != wxT("layout2")) return false; // mark all panes currently managed as docked and hidden int pane_i, pane_count = m_panes.GetCount(); for (pane_i = 0; pane_i < pane_count; ++pane_i) m_panes.Item(pane_i).Dock().Hide(); // clear out the dock array; this will be reconstructed m_docks.Clear(); // replace escaped characters so we can // split up the string easily input.Replace(wxT("\\|"), wxT("\a")); input.Replace(wxT("\\;"), wxT("\b")); while (1) { wxAuiPaneInfo pane; wxString pane_part = input.BeforeFirst(wxT('|')); input = input.AfterFirst(wxT('|')); pane_part.Trim(true); // if the string is empty, we're done parsing if (pane_part.empty()) break; if (pane_part.Left(9) == wxT("dock_size")) { wxString val_name = pane_part.BeforeFirst(wxT('=')); wxString value = pane_part.AfterFirst(wxT('=')); long dir, layer, row, size; wxString piece = val_name.AfterFirst(wxT('(')); piece = piece.BeforeLast(wxT(')')); piece.BeforeFirst(wxT(',')).ToLong(&dir); piece = piece.AfterFirst(wxT(',')); piece.BeforeFirst(wxT(',')).ToLong(&layer); piece.AfterFirst(wxT(',')).ToLong(&row); value.ToLong(&size); wxAuiDockInfo dock; dock.dock_direction = dir; dock.dock_layer = layer; dock.dock_row = row; dock.size = size; m_docks.Add(dock); continue; } // Undo our escaping as LoadPaneInfo needs to take an unescaped // name so it can be called by external callers pane_part.Replace(wxT("\a"), wxT("|")); pane_part.Replace(wxT("\b"), wxT(";")); LoadPaneInfo(pane_part, pane); wxAuiPaneInfo& p = GetPane(pane.name); if (!p.IsOk()) { // the pane window couldn't be found // in the existing layout -- skip it continue; } p.SafeSet(pane); } if (update) Update(); return true; } void wxAuiManager::GetPanePositionsAndSizes(wxAuiDockInfo& dock, wxArrayInt& positions, wxArrayInt& sizes) { int caption_size = m_art->GetMetric(wxAUI_DOCKART_CAPTION_SIZE); int pane_border_size = m_art->GetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE); int gripper_size = m_art->GetMetric(wxAUI_DOCKART_GRIPPER_SIZE); positions.Empty(); sizes.Empty(); int offset, action_pane = -1; int pane_i, pane_count = dock.panes.GetCount(); // find the pane marked as our action pane for (pane_i = 0; pane_i < pane_count; ++pane_i) { wxAuiPaneInfo& pane = *(dock.panes.Item(pane_i)); if (pane.state & wxAuiPaneInfo::actionPane) { wxASSERT_MSG(action_pane==-1, wxT("Too many fixed action panes")); action_pane = pane_i; } } // set up each panes default position, and // determine the size (width or height, depending // on the dock's orientation) of each pane for (pane_i = 0; pane_i < pane_count; ++pane_i) { wxAuiPaneInfo& pane = *(dock.panes.Item(pane_i)); positions.Add(pane.dock_pos); int size = 0; if (pane.HasBorder()) size += (pane_border_size*2); if (dock.IsHorizontal()) { if (pane.HasGripper() && !pane.HasGripperTop()) size += gripper_size; size += pane.best_size.x; } else { if (pane.HasGripper() && pane.HasGripperTop()) size += gripper_size; if (pane.HasCaption()) size += caption_size; size += pane.best_size.y; } sizes.Add(size); } // if there is no action pane, just return the default // positions (as specified in pane.pane_pos) if (action_pane == -1) return; offset = 0; for (pane_i = action_pane-1; pane_i >= 0; --pane_i) { int amount = positions[pane_i+1] - (positions[pane_i] + sizes[pane_i]); if (amount >= 0) offset += amount; else positions[pane_i] -= -amount; offset += sizes[pane_i]; } // if the dock mode is fixed, make sure none of the panes // overlap; we will bump panes that overlap offset = 0; for (pane_i = action_pane; pane_i < pane_count; ++pane_i) { int amount = positions[pane_i] - offset; if (amount >= 0) offset += amount; else positions[pane_i] += -amount; offset += sizes[pane_i]; } } void wxAuiManager::LayoutAddPane(wxSizer* cont, wxAuiDockInfo& dock, wxAuiPaneInfo& pane, wxAuiDockUIPartArray& uiparts, bool spacer_only) { wxAuiDockUIPart part; wxSizerItem* sizer_item; int caption_size = m_art->GetMetric(wxAUI_DOCKART_CAPTION_SIZE); int gripper_size = m_art->GetMetric(wxAUI_DOCKART_GRIPPER_SIZE); int pane_border_size = m_art->GetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE); int pane_button_size = m_art->GetMetric(wxAUI_DOCKART_PANE_BUTTON_SIZE); // find out the orientation of the item (orientation for panes // is the same as the dock's orientation) int orientation; if (dock.IsHorizontal()) orientation = wxHORIZONTAL; else orientation = wxVERTICAL; // this variable will store the proportion // value that the pane will receive int pane_proportion = pane.dock_proportion; wxBoxSizer* horz_pane_sizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* vert_pane_sizer = new wxBoxSizer(wxVERTICAL); if (pane.HasGripper()) { if (pane.HasGripperTop()) sizer_item = vert_pane_sizer ->Add(1, gripper_size, 0, wxEXPAND); else sizer_item = horz_pane_sizer ->Add(gripper_size, 1, 0, wxEXPAND); part.type = wxAuiDockUIPart::typeGripper; part.dock = &dock; part.pane = &pane; part.button = NULL; part.orientation = orientation; part.cont_sizer = horz_pane_sizer; part.sizer_item = sizer_item; uiparts.Add(part); } if (pane.HasCaption()) { // create the caption sizer wxBoxSizer* caption_sizer = new wxBoxSizer(wxHORIZONTAL); sizer_item = caption_sizer->Add(1, caption_size, 1, wxEXPAND); part.type = wxAuiDockUIPart::typeCaption; part.dock = &dock; part.pane = &pane; part.button = NULL; part.orientation = orientation; part.cont_sizer = vert_pane_sizer; part.sizer_item = sizer_item; int caption_part_idx = uiparts.GetCount(); uiparts.Add(part); // add pane buttons to the caption int i, button_count; for (i = 0, button_count = pane.buttons.GetCount(); i < button_count; ++i) { wxAuiPaneButton& button = pane.buttons.Item(i); sizer_item = caption_sizer->Add(pane_button_size, caption_size, 0, wxEXPAND); part.type = wxAuiDockUIPart::typePaneButton; part.dock = &dock; part.pane = &pane; part.button = &button; part.orientation = orientation; part.cont_sizer = caption_sizer; part.sizer_item = sizer_item; uiparts.Add(part); } // if we have buttons, add a little space to the right // of them to ease visual crowding if (button_count >= 1) { caption_sizer->Add(3,1); } // add the caption sizer sizer_item = vert_pane_sizer->Add(caption_sizer, 0, wxEXPAND); uiparts.Item(caption_part_idx).sizer_item = sizer_item; } // add the pane window itself if (spacer_only) { sizer_item = vert_pane_sizer->Add(1, 1, 1, wxEXPAND); } else { sizer_item = vert_pane_sizer->Add(pane.window, 1, wxEXPAND); // Don't do this because it breaks the pane size in floating windows // BIW: Right now commenting this out is causing problems with // an mdi client window as the center pane. vert_pane_sizer->SetItemMinSize(pane.window, 1, 1); } part.type = wxAuiDockUIPart::typePane; part.dock = &dock; part.pane = &pane; part.button = NULL; part.orientation = orientation; part.cont_sizer = vert_pane_sizer; part.sizer_item = sizer_item; uiparts.Add(part); // determine if the pane should have a minimum size; if the pane is // non-resizable (fixed) then we must set a minimum size. Alternatively, // if the pane.min_size is set, we must use that value as well wxSize min_size = pane.min_size; if (pane.IsFixed()) { if (min_size == wxDefaultSize) { min_size = pane.best_size; pane_proportion = 0; } } if (min_size != wxDefaultSize) { vert_pane_sizer->SetItemMinSize( vert_pane_sizer->GetChildren().GetCount()-1, min_size.x, min_size.y); } // add the verticle sizer (caption, pane window) to the // horizontal sizer (gripper, verticle sizer) horz_pane_sizer->Add(vert_pane_sizer, 1, wxEXPAND); // finally, add the pane sizer to the dock sizer if (pane.HasBorder()) { // allowing space for the pane's border sizer_item = cont->Add(horz_pane_sizer, pane_proportion, wxEXPAND | wxALL, pane_border_size); part.type = wxAuiDockUIPart::typePaneBorder; part.dock = &dock; part.pane = &pane; part.button = NULL; part.orientation = orientation; part.cont_sizer = cont; part.sizer_item = sizer_item; uiparts.Add(part); } else { sizer_item = cont->Add(horz_pane_sizer, pane_proportion, wxEXPAND); } } void wxAuiManager::LayoutAddDock(wxSizer* cont, wxAuiDockInfo& dock, wxAuiDockUIPartArray& uiparts, bool spacer_only) { wxSizerItem* sizer_item; wxAuiDockUIPart part; int sash_size = m_art->GetMetric(wxAUI_DOCKART_SASH_SIZE); int orientation = dock.IsHorizontal() ? wxHORIZONTAL : wxVERTICAL; // resizable bottom and right docks have a sash before them if (!m_has_maximized && !dock.fixed && (dock.dock_direction == wxAUI_DOCK_BOTTOM || dock.dock_direction == wxAUI_DOCK_RIGHT)) { sizer_item = cont->Add(sash_size, sash_size, 0, wxEXPAND); part.type = wxAuiDockUIPart::typeDockSizer; part.orientation = orientation; part.dock = &dock; part.pane = NULL; part.button = NULL; part.cont_sizer = cont; part.sizer_item = sizer_item; uiparts.Add(part); } // create the sizer for the dock wxSizer* dock_sizer = new wxBoxSizer(orientation); // add each pane to the dock bool has_maximized_pane = false; int pane_i, pane_count = dock.panes.GetCount(); if (dock.fixed) { wxArrayInt pane_positions, pane_sizes; // figure out the real pane positions we will // use, without modifying the each pane's pane_pos member GetPanePositionsAndSizes(dock, pane_positions, pane_sizes); int offset = 0; for (pane_i = 0; pane_i < pane_count; ++pane_i) { wxAuiPaneInfo& pane = *(dock.panes.Item(pane_i)); int pane_pos = pane_positions.Item(pane_i); if (pane.IsMaximized()) has_maximized_pane = true; int amount = pane_pos - offset; if (amount > 0) { if (dock.IsVertical()) sizer_item = dock_sizer->Add(1, amount, 0, wxEXPAND); else sizer_item = dock_sizer->Add(amount, 1, 0, wxEXPAND); part.type = wxAuiDockUIPart::typeBackground; part.dock = &dock; part.pane = NULL; part.button = NULL; part.orientation = (orientation==wxHORIZONTAL) ? wxVERTICAL:wxHORIZONTAL; part.cont_sizer = dock_sizer; part.sizer_item = sizer_item; uiparts.Add(part); offset += amount; } LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only); offset += pane_sizes.Item(pane_i); } // at the end add a very small stretchable background area sizer_item = dock_sizer->Add(0,0, 1, wxEXPAND); part.type = wxAuiDockUIPart::typeBackground; part.dock = &dock; part.pane = NULL; part.button = NULL; part.orientation = orientation; part.cont_sizer = dock_sizer; part.sizer_item = sizer_item; uiparts.Add(part); } else { for (pane_i = 0; pane_i < pane_count; ++pane_i) { wxAuiPaneInfo& pane = *(dock.panes.Item(pane_i)); if (pane.IsMaximized()) has_maximized_pane = true; // if this is not the first pane being added, // we need to add a pane sizer if (!m_has_maximized && pane_i > 0) { sizer_item = dock_sizer->Add(sash_size, sash_size, 0, wxEXPAND); part.type = wxAuiDockUIPart::typePaneSizer; part.dock = &dock; part.pane = dock.panes.Item(pane_i-1); part.button = NULL; part.orientation = (orientation==wxHORIZONTAL) ? wxVERTICAL:wxHORIZONTAL; part.cont_sizer = dock_sizer; part.sizer_item = sizer_item; uiparts.Add(part); } LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only); } } if (dock.dock_direction == wxAUI_DOCK_CENTER || has_maximized_pane) sizer_item = cont->Add(dock_sizer, 1, wxEXPAND); else sizer_item = cont->Add(dock_sizer, 0, wxEXPAND); part.type = wxAuiDockUIPart::typeDock; part.dock = &dock; part.pane = NULL; part.button = NULL; part.orientation = orientation; part.cont_sizer = cont; part.sizer_item = sizer_item; uiparts.Add(part); if (dock.IsHorizontal()) cont->SetItemMinSize(dock_sizer, 0, dock.size); else cont->SetItemMinSize(dock_sizer, dock.size, 0); // top and left docks have a sash after them if (!m_has_maximized && !dock.fixed && (dock.dock_direction == wxAUI_DOCK_TOP || dock.dock_direction == wxAUI_DOCK_LEFT)) { sizer_item = cont->Add(sash_size, sash_size, 0, wxEXPAND); part.type = wxAuiDockUIPart::typeDockSizer; part.dock = &dock; part.pane = NULL; part.button = NULL; part.orientation = orientation; part.cont_sizer = cont; part.sizer_item = sizer_item; uiparts.Add(part); } } wxSizer* wxAuiManager::LayoutAll(wxAuiPaneInfoArray& panes, wxAuiDockInfoArray& docks, wxAuiDockUIPartArray& uiparts, bool spacer_only) { wxBoxSizer* container = new wxBoxSizer(wxVERTICAL); int pane_border_size = m_art->GetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE); int caption_size = m_art->GetMetric(wxAUI_DOCKART_CAPTION_SIZE); wxSize cli_size = m_frame->GetClientSize(); int i, dock_count, pane_count; // empty all docks out for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = docks.Item(i); // empty out all panes, as they will be readded below dock.panes.Empty(); if (dock.fixed) { // always reset fixed docks' sizes, because // the contained windows may have been resized dock.size = 0; } } // iterate through all known panes, filing each // of them into the appropriate dock. If the // pane does not exist in the dock, add it for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& p = panes.Item(i); // find any docks with the same dock direction, dock layer, and // dock row as the pane we are working on wxAuiDockInfo* dock; wxAuiDockInfoPtrArray arr; FindDocks(docks, p.dock_direction, p.dock_layer, p.dock_row, arr); if (arr.GetCount() > 0) { // found the right dock dock = arr.Item(0); } else { // dock was not found, so we need to create a new one wxAuiDockInfo d; d.dock_direction = p.dock_direction; d.dock_layer = p.dock_layer; d.dock_row = p.dock_row; docks.Add(d); dock = &docks.Last(); } if (p.IsDocked() && p.IsShown()) { // remove the pane from any existing docks except this one RemovePaneFromDocks(docks, p, dock); // pane needs to be added to the dock, // if it doesn't already exist if (!FindPaneInDock(*dock, p.window)) dock->panes.Add(&p); } else { // remove the pane from any existing docks RemovePaneFromDocks(docks, p); } } // remove any empty docks for (i = docks.GetCount()-1; i >= 0; --i) { if (docks.Item(i).panes.GetCount() == 0) docks.RemoveAt(i); } // configure the docks further for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = docks.Item(i); int j, dock_pane_count = dock.panes.GetCount(); // sort the dock pane array by the pane's // dock position (dock_pos), in ascending order dock.panes.Sort(PaneSortFunc); // for newly created docks, set up their initial size if (dock.size == 0) { int size = 0; for (j = 0; j < dock_pane_count; ++j) { wxAuiPaneInfo& pane = *dock.panes.Item(j); wxSize pane_size = pane.best_size; if (pane_size == wxDefaultSize) pane_size = pane.min_size; if (pane_size == wxDefaultSize) pane_size = pane.window->GetSize(); if (dock.IsHorizontal()) size = wxMax(pane_size.y, size); else size = wxMax(pane_size.x, size); } // add space for the border (two times), but only // if at least one pane inside the dock has a pane border for (j = 0; j < dock_pane_count; ++j) { if (dock.panes.Item(j)->HasBorder()) { size += (pane_border_size*2); break; } } // if pane is on the top or bottom, add the caption height, // but only if at least one pane inside the dock has a caption if (dock.IsHorizontal()) { for (j = 0; j < dock_pane_count; ++j) { if (dock.panes.Item(j)->HasCaption()) { size += caption_size; break; } } } // new dock's size may not be more than the dock constraint // parameter specifies. See SetDockSizeConstraint() int max_dock_x_size = (int)(m_dock_constraint_x * ((double)cli_size.x)); int max_dock_y_size = (int)(m_dock_constraint_y * ((double)cli_size.y)); if (dock.IsHorizontal()) size = wxMin(size, max_dock_y_size); else size = wxMin(size, max_dock_x_size); // absolute minimum size for a dock is 10 pixels if (size < 10) size = 10; dock.size = size; } // determine the dock's minimum size bool plus_border = false; bool plus_caption = false; int dock_min_size = 0; for (j = 0; j < dock_pane_count; ++j) { wxAuiPaneInfo& pane = *dock.panes.Item(j); if (pane.min_size != wxDefaultSize) { if (pane.HasBorder()) plus_border = true; if (pane.HasCaption()) plus_caption = true; if (dock.IsHorizontal()) { if (pane.min_size.y > dock_min_size) dock_min_size = pane.min_size.y; } else { if (pane.min_size.x > dock_min_size) dock_min_size = pane.min_size.x; } } } if (plus_border) dock_min_size += (pane_border_size*2); if (plus_caption && dock.IsHorizontal()) dock_min_size += (caption_size); dock.min_size = dock_min_size; // if the pane's current size is less than it's // minimum, increase the dock's size to it's minimum if (dock.size < dock.min_size) dock.size = dock.min_size; // determine the dock's mode (fixed or proportional); // determine whether the dock has only toolbars bool action_pane_marked = false; dock.fixed = true; dock.toolbar = true; for (j = 0; j < dock_pane_count; ++j) { wxAuiPaneInfo& pane = *dock.panes.Item(j); if (!pane.IsFixed()) dock.fixed = false; if (!pane.IsToolbar()) dock.toolbar = false; if (pane.HasFlag(wxAuiPaneInfo::optionDockFixed)) dock.fixed = true; if (pane.state & wxAuiPaneInfo::actionPane) action_pane_marked = true; } // if the dock mode is proportional and not fixed-pixel, // reassign the dock_pos to the sequential 0, 1, 2, 3; // e.g. remove gaps like 1, 2, 30, 500 if (!dock.fixed) { for (j = 0; j < dock_pane_count; ++j) { wxAuiPaneInfo& pane = *dock.panes.Item(j); pane.dock_pos = j; } } // if the dock mode is fixed, and none of the panes // are being moved right now, make sure the panes // do not overlap each other. If they do, we will // adjust the positions of the panes if (dock.fixed && !action_pane_marked) { wxArrayInt pane_positions, pane_sizes; GetPanePositionsAndSizes(dock, pane_positions, pane_sizes); int offset = 0; for (j = 0; j < dock_pane_count; ++j) { wxAuiPaneInfo& pane = *(dock.panes.Item(j)); pane.dock_pos = pane_positions[j]; int amount = pane.dock_pos - offset; if (amount >= 0) offset += amount; else pane.dock_pos += -amount; offset += pane_sizes[j]; } } } // discover the maximum dock layer int max_layer = 0; for (i = 0; i < dock_count; ++i) max_layer = wxMax(max_layer, docks.Item(i).dock_layer); // clear out uiparts uiparts.Empty(); // create a bunch of box sizers, // from the innermost level outwards. wxSizer* cont = NULL; wxSizer* middle = NULL; int layer = 0; int row, row_count; for (layer = 0; layer <= max_layer; ++layer) { wxAuiDockInfoPtrArray arr; // find any docks in this layer FindDocks(docks, -1, layer, -1, arr); // if there aren't any, skip to the next layer if (arr.IsEmpty()) continue; wxSizer* old_cont = cont; // create a container which will hold this layer's // docks (top, bottom, left, right) cont = new wxBoxSizer(wxVERTICAL); // find any top docks in this layer FindDocks(docks, wxAUI_DOCK_TOP, layer, -1, arr); if (!arr.IsEmpty()) { for (row = 0, row_count = arr.GetCount(); row < row_count; ++row) LayoutAddDock(cont, *arr.Item(row), uiparts, spacer_only); } // fill out the middle layer (which consists // of left docks, content area and right docks) middle = new wxBoxSizer(wxHORIZONTAL); // find any left docks in this layer FindDocks(docks, wxAUI_DOCK_LEFT, layer, -1, arr); if (!arr.IsEmpty()) { for (row = 0, row_count = arr.GetCount(); row < row_count; ++row) LayoutAddDock(middle, *arr.Item(row), uiparts, spacer_only); } // add content dock (or previous layer's sizer // to the middle if (!old_cont) { // find any center docks FindDocks(docks, wxAUI_DOCK_CENTER, -1, -1, arr); if (!arr.IsEmpty()) { for (row = 0,row_count = arr.GetCount(); row<row_count; ++row) LayoutAddDock(middle, *arr.Item(row), uiparts, spacer_only); } else if (!m_has_maximized) { // there are no center docks, add a background area wxSizerItem* sizer_item = middle->Add(1,1, 1, wxEXPAND); wxAuiDockUIPart part; part.type = wxAuiDockUIPart::typeBackground; part.pane = NULL; part.dock = NULL; part.button = NULL; part.cont_sizer = middle; part.sizer_item = sizer_item; uiparts.Add(part); } } else { middle->Add(old_cont, 1, wxEXPAND); } // find any right docks in this layer FindDocks(docks, wxAUI_DOCK_RIGHT, layer, -1, arr); if (!arr.IsEmpty()) { for (row = arr.GetCount()-1; row >= 0; --row) LayoutAddDock(middle, *arr.Item(row), uiparts, spacer_only); } if (middle->GetChildren().GetCount() > 0) cont->Add(middle, 1, wxEXPAND); else delete middle; // find any bottom docks in this layer FindDocks(docks, wxAUI_DOCK_BOTTOM, layer, -1, arr); if (!arr.IsEmpty()) { for (row = arr.GetCount()-1; row >= 0; --row) LayoutAddDock(cont, *arr.Item(row), uiparts, spacer_only); } } if (!cont) { // no sizer available, because there are no docks, // therefore we will create a simple background area cont = new wxBoxSizer(wxVERTICAL); wxSizerItem* sizer_item = cont->Add(1,1, 1, wxEXPAND); wxAuiDockUIPart part; part.type = wxAuiDockUIPart::typeBackground; part.pane = NULL; part.dock = NULL; part.button = NULL; part.cont_sizer = middle; part.sizer_item = sizer_item; uiparts.Add(part); } container->Add(cont, 1, wxEXPAND); return container; } // SetDockSizeConstraint() allows the dock constraints to be set. For example, // specifying values of 0.5, 0.5 will mean that upon dock creation, a dock may // not be larger than half of the window's size void wxAuiManager::SetDockSizeConstraint(double width_pct, double height_pct) { m_dock_constraint_x = wxMax(0.0, wxMin(1.0, width_pct)); m_dock_constraint_y = wxMax(0.0, wxMin(1.0, height_pct)); } void wxAuiManager::GetDockSizeConstraint(double* width_pct, double* height_pct) const { if (width_pct) *width_pct = m_dock_constraint_x; if (height_pct) *height_pct = m_dock_constraint_y; } // Update() updates the layout. Whenever changes are made to // one or more panes, this function should be called. It is the // external entry point for running the layout engine. void wxAuiManager::Update() { m_hover_button = NULL; m_action_part = NULL; wxSizer* sizer; int i, pane_count = m_panes.GetCount(); // destroy floating panes which have been // redocked or are becoming non-floating for (i = 0; i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (!p.IsFloating() && p.frame) { // because the pane is no longer in a floating, we need to // reparent it to m_frame and destroy the floating frame // reduce flicker p.window->SetSize(1,1); // the following block is a workaround for bug #1531361 // (see wxWidgets sourceforge page). On wxGTK (only), when // a frame is shown/hidden, a move event unfortunately // also gets fired. Because we may be dragging around // a pane, we need to cancel that action here to prevent // a spurious crash. if (m_action_window == p.frame) { if (wxWindow::GetCapture() == m_frame) m_frame->ReleaseMouse(); m_action = actionNone; m_action_window = NULL; } // hide the frame if (p.frame->IsShown()) p.frame->Show(false); // reparent to m_frame and destroy the pane if (m_action_window == p.frame) { m_action_window = NULL; } p.window->Reparent(m_frame); p.frame->SetSizer(NULL); p.frame->Destroy(); p.frame = NULL; } } // delete old sizer first m_frame->SetSizer(NULL); // create a layout for all of the panes sizer = LayoutAll(m_panes, m_docks, m_uiparts, false); // hide or show panes as necessary, // and float panes as necessary for (i = 0; i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.IsFloating()) { if (p.frame == NULL) { // we need to create a frame for this // pane, which has recently been floated wxAuiFloatingFrame* frame = CreateFloatingFrame(m_frame, p); // on MSW and Mac, if the owner desires transparent dragging, and // the dragging is happening right now, then the floating // window should have this style by default if (m_action == actionDragFloatingPane && (m_flags & wxAUI_MGR_TRANSPARENT_DRAG)) frame->SetTransparent(150); frame->SetPaneWindow(p); p.frame = frame; if (p.IsShown() && !frame->IsShown()) frame->Show(); } else { // frame already exists, make sure it's position // and size reflect the information in wxAuiPaneInfo if ((p.frame->GetPosition() != p.floating_pos) || (p.frame->GetSize() != p.floating_size)) { p.frame->SetSize(p.floating_pos.x, p.floating_pos.y, p.floating_size.x, p.floating_size.y, wxSIZE_USE_EXISTING); /* p.frame->SetSize(p.floating_pos.x, p.floating_pos.y, wxDefaultCoord, wxDefaultCoord, wxSIZE_USE_EXISTING); //p.frame->Move(p.floating_pos.x, p.floating_pos.y); */ } if (p.frame->IsShown() != p.IsShown()) p.frame->Show(p.IsShown()); } } else { if (p.window->IsShown() != p.IsShown()) p.window->Show(p.IsShown()); } // if "active panes" are no longer allowed, clear // any optionActive values from the pane states if ((m_flags & wxAUI_MGR_ALLOW_ACTIVE_PANE) == 0) { p.state &= ~wxAuiPaneInfo::optionActive; } } // keep track of the old window rectangles so we can // refresh those windows whose rect has changed wxAuiRectArray old_pane_rects; for (i = 0; i < pane_count; ++i) { wxRect r; wxAuiPaneInfo& p = m_panes.Item(i); if (p.window && p.IsShown() && p.IsDocked()) r = p.rect; old_pane_rects.Add(r); } // apply the new sizer m_frame->SetSizer(sizer); m_frame->SetAutoLayout(false); DoFrameLayout(); // now that the frame layout is done, we need to check // the new pane rectangles against the old rectangles that // we saved a few lines above here. If the rectangles have // changed, the corresponding panes must also be updated for (i = 0; i < pane_count; ++i) { wxAuiPaneInfo& p = m_panes.Item(i); if (p.window && p.window->IsShown() && p.IsDocked()) { if (p.rect != old_pane_rects[i]) { p.window->Refresh(); p.window->Update(); } } } Repaint(); // set frame's minimum size /* // N.B. More work needs to be done on frame minimum sizes; // this is some intresting code that imposes the minimum size, // but we may want to include a more flexible mechanism or // options for multiple minimum-size modes, e.g. strict or lax wxSize min_size = sizer->GetMinSize(); wxSize frame_size = m_frame->GetSize(); wxSize client_size = m_frame->GetClientSize(); wxSize minframe_size(min_size.x+frame_size.x-client_size.x, min_size.y+frame_size.y-client_size.y ); m_frame->SetMinSize(minframe_size); if (frame_size.x < minframe_size.x || frame_size.y < minframe_size.y) sizer->Fit(m_frame); */ } // DoFrameLayout() is an internal function which invokes wxSizer::Layout // on the frame's main sizer, then measures all the various UI items // and updates their internal rectangles. This should always be called // instead of calling m_frame->Layout() directly void wxAuiManager::DoFrameLayout() { m_frame->Layout(); int i, part_count; for (i = 0, part_count = m_uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = m_uiparts.Item(i); // get the rectangle of the UI part // originally, this code looked like this: // part.rect = wxRect(part.sizer_item->GetPosition(), // part.sizer_item->GetSize()); // this worked quite well, with one exception: the mdi // client window had a "deferred" size variable // that returned the wrong size. It looks like // a bug in wx, because the former size of the window // was being returned. So, we will retrieve the part's // rectangle via other means part.rect = part.sizer_item->GetRect(); int flag = part.sizer_item->GetFlag(); int border = part.sizer_item->GetBorder(); if (flag & wxTOP) { part.rect.y -= border; part.rect.height += border; } if (flag & wxLEFT) { part.rect.x -= border; part.rect.width += border; } if (flag & wxBOTTOM) part.rect.height += border; if (flag & wxRIGHT) part.rect.width += border; if (part.type == wxAuiDockUIPart::typeDock) part.dock->rect = part.rect; if (part.type == wxAuiDockUIPart::typePane) part.pane->rect = part.rect; } } // GetPanePart() looks up the pane the pane border UI part (or the regular // pane part if there is no border). This allows the caller to get the exact // rectangle of the pane in question, including decorations like // caption and border (if any). wxAuiDockUIPart* wxAuiManager::GetPanePart(wxWindow* wnd) { int i, part_count; for (i = 0, part_count = m_uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = m_uiparts.Item(i); if (part.type == wxAuiDockUIPart::typePaneBorder && part.pane && part.pane->window == wnd) return &part; } for (i = 0, part_count = m_uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = m_uiparts.Item(i); if (part.type == wxAuiDockUIPart::typePane && part.pane && part.pane->window == wnd) return &part; } return NULL; } // GetDockPixelOffset() is an internal function which returns // a dock's offset in pixels from the left side of the window // (for horizontal docks) or from the top of the window (for // vertical docks). This value is necessary for calculating // fixel-pane/toolbar offsets when they are dragged. int wxAuiManager::GetDockPixelOffset(wxAuiPaneInfo& test) { // the only way to accurately calculate the dock's // offset is to actually run a theoretical layout int i, part_count, dock_count; wxAuiDockInfoArray docks; wxAuiPaneInfoArray panes; wxAuiDockUIPartArray uiparts; CopyDocksAndPanes(docks, panes, m_docks, m_panes); panes.Add(test); wxSizer* sizer = LayoutAll(panes, docks, uiparts, true); wxSize client_size = m_frame->GetClientSize(); sizer->SetDimension(0, 0, client_size.x, client_size.y); sizer->Layout(); for (i = 0, part_count = uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = uiparts.Item(i); part.rect = wxRect(part.sizer_item->GetPosition(), part.sizer_item->GetSize()); if (part.type == wxAuiDockUIPart::typeDock) part.dock->rect = part.rect; } delete sizer; for (i = 0, dock_count = docks.GetCount(); i < dock_count; ++i) { wxAuiDockInfo& dock = docks.Item(i); if (test.dock_direction == dock.dock_direction && test.dock_layer==dock.dock_layer && test.dock_row==dock.dock_row) { if (dock.IsVertical()) return dock.rect.y; else return dock.rect.x; } } return 0; } // ProcessDockResult() is a utility function used by DoDrop() - it checks // if a dock operation is allowed, the new dock position is copied into // the target info. If the operation was allowed, the function returns true. bool wxAuiManager::ProcessDockResult(wxAuiPaneInfo& target, const wxAuiPaneInfo& new_pos) { bool allowed = false; switch (new_pos.dock_direction) { case wxAUI_DOCK_TOP: allowed = target.IsTopDockable(); break; case wxAUI_DOCK_BOTTOM: allowed = target.IsBottomDockable(); break; case wxAUI_DOCK_LEFT: allowed = target.IsLeftDockable(); break; case wxAUI_DOCK_RIGHT: allowed = target.IsRightDockable(); break; } if (allowed) target = new_pos; return allowed; } // DoDrop() is an important function. It basically takes a mouse position, // and determines where the pane's new position would be. If the pane is to be // dropped, it performs the drop operation using the specified dock and pane // arrays. By specifying copied dock and pane arrays when calling, a "what-if" // scenario can be performed, giving precise coordinates for drop hints. // If, however, wxAuiManager:m_docks and wxAuiManager::m_panes are specified // as parameters, the changes will be made to the main state arrays const int auiInsertRowPixels = 10; const int auiNewRowPixels = 40; const int auiLayerInsertPixels = 40; const int auiLayerInsertOffset = 5; bool wxAuiManager::DoDrop(wxAuiDockInfoArray& docks, wxAuiPaneInfoArray& panes, wxAuiPaneInfo& target, const wxPoint& pt, const wxPoint& offset) { wxSize cli_size = m_frame->GetClientSize(); wxAuiPaneInfo drop = target; // The result should always be shown drop.Show(); // Check to see if the pane has been dragged outside of the window // (or near to the outside of the window), if so, dock it along the edge int layer_insert_offset = auiLayerInsertOffset; if (drop.IsToolbar()) layer_insert_offset = 0; if (pt.x < layer_insert_offset && pt.x > layer_insert_offset-auiLayerInsertPixels) { int new_layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_LEFT), GetMaxLayer(docks, wxAUI_DOCK_BOTTOM)), GetMaxLayer(docks, wxAUI_DOCK_TOP)) + 1; if (drop.IsToolbar()) new_layer = auiToolBarLayer; drop.Dock().Left(). Layer(new_layer). Row(0). Position(pt.y - GetDockPixelOffset(drop) - offset.y); return ProcessDockResult(target, drop); } else if (pt.y < layer_insert_offset && pt.y > layer_insert_offset-auiLayerInsertPixels) { int new_layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_TOP), GetMaxLayer(docks, wxAUI_DOCK_LEFT)), GetMaxLayer(docks, wxAUI_DOCK_RIGHT)) + 1; if (drop.IsToolbar()) new_layer = auiToolBarLayer; drop.Dock().Top(). Layer(new_layer). Row(0). Position(pt.x - GetDockPixelOffset(drop) - offset.x); return ProcessDockResult(target, drop); } else if (pt.x >= cli_size.x - layer_insert_offset && pt.x < cli_size.x - layer_insert_offset + auiLayerInsertPixels) { int new_layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_RIGHT), GetMaxLayer(docks, wxAUI_DOCK_TOP)), GetMaxLayer(docks, wxAUI_DOCK_BOTTOM)) + 1; if (drop.IsToolbar()) new_layer = auiToolBarLayer; drop.Dock().Right(). Layer(new_layer). Row(0). Position(pt.y - GetDockPixelOffset(drop) - offset.y); return ProcessDockResult(target, drop); } else if (pt.y >= cli_size.y - layer_insert_offset && pt.y < cli_size.y - layer_insert_offset + auiLayerInsertPixels) { int new_layer = wxMax( wxMax( GetMaxLayer(docks, wxAUI_DOCK_BOTTOM), GetMaxLayer(docks, wxAUI_DOCK_LEFT)), GetMaxLayer(docks, wxAUI_DOCK_RIGHT)) + 1; if (drop.IsToolbar()) new_layer = auiToolBarLayer; drop.Dock().Bottom(). Layer(new_layer). Row(0). Position(pt.x - GetDockPixelOffset(drop) - offset.x); return ProcessDockResult(target, drop); } wxAuiDockUIPart* part = HitTest(pt.x, pt.y); if (drop.IsToolbar()) { if (!part || !part->dock) return false; // calculate the offset from where the dock begins // to the point where the user dropped the pane int dock_drop_offset = 0; if (part->dock->IsHorizontal()) dock_drop_offset = pt.x - part->dock->rect.x - offset.x; else dock_drop_offset = pt.y - part->dock->rect.y - offset.y; // toolbars may only be moved in and to fixed-pane docks, // otherwise we will try to float the pane. Also, the pane // should float if being dragged over center pane windows if (!part->dock->fixed || part->dock->dock_direction == wxAUI_DOCK_CENTER || pt.x >= cli_size.x || pt.x <= 0 || pt.y >= cli_size.y || pt.y <= 0) { if (m_last_rect.IsEmpty() || m_last_rect.Contains(pt.x, pt.y )) { m_skipping = true; } else { if ((m_flags & wxAUI_MGR_ALLOW_FLOATING) && drop.IsFloatable()) { drop.Float(); } m_skipping = false; return ProcessDockResult(target, drop); } drop.Position(pt.x - GetDockPixelOffset(drop) - offset.x); return ProcessDockResult(target, drop); } else { m_skipping = false; } if (!m_skipping) { m_last_rect = part->dock->rect; m_last_rect.Inflate( 15, 15 ); } drop.Dock(). Direction(part->dock->dock_direction). Layer(part->dock->dock_layer). Row(part->dock->dock_row). Position(dock_drop_offset); if (( ((pt.y < part->dock->rect.y + 1) && part->dock->IsHorizontal()) || ((pt.x < part->dock->rect.x + 1) && part->dock->IsVertical()) ) && part->dock->panes.GetCount() > 1) { if ((part->dock->dock_direction == wxAUI_DOCK_TOP) || (part->dock->dock_direction == wxAUI_DOCK_LEFT)) { int row = drop.dock_row; DoInsertDockRow(panes, part->dock->dock_direction, part->dock->dock_layer, part->dock->dock_row); drop.dock_row = row; } else { DoInsertDockRow(panes, part->dock->dock_direction, part->dock->dock_layer, part->dock->dock_row+1); drop.dock_row = part->dock->dock_row+1; } } if (( ((pt.y > part->dock->rect.y + part->dock->rect.height - 2 ) && part->dock->IsHorizontal()) || ((pt.x > part->dock->rect.x + part->dock->rect.width - 2 ) && part->dock->IsVertical()) ) && part->dock->panes.GetCount() > 1) { if ((part->dock->dock_direction == wxAUI_DOCK_TOP) || (part->dock->dock_direction == wxAUI_DOCK_LEFT)) { DoInsertDockRow(panes, part->dock->dock_direction, part->dock->dock_layer, part->dock->dock_row+1); drop.dock_row = part->dock->dock_row+1; } else { int row = drop.dock_row; DoInsertDockRow(panes, part->dock->dock_direction, part->dock->dock_layer, part->dock->dock_row); drop.dock_row = row; } } return ProcessDockResult(target, drop); } if (!part) return false; if (part->type == wxAuiDockUIPart::typePaneBorder || part->type == wxAuiDockUIPart::typeCaption || part->type == wxAuiDockUIPart::typeGripper || part->type == wxAuiDockUIPart::typePaneButton || part->type == wxAuiDockUIPart::typePane || part->type == wxAuiDockUIPart::typePaneSizer || part->type == wxAuiDockUIPart::typeDockSizer || part->type == wxAuiDockUIPart::typeBackground) { if (part->type == wxAuiDockUIPart::typeDockSizer) { if (part->dock->panes.GetCount() != 1) return false; part = GetPanePart(part->dock->panes.Item(0)->window); if (!part) return false; } // If a normal frame is being dragged over a toolbar, insert it // along the edge under the toolbar, but over all other panes. // (this could be done much better, but somehow factoring this // calculation with the one at the beginning of this function) if (part->dock && part->dock->toolbar) { int layer = 0; switch (part->dock->dock_direction) { case wxAUI_DOCK_LEFT: layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_LEFT), GetMaxLayer(docks, wxAUI_DOCK_BOTTOM)), GetMaxLayer(docks, wxAUI_DOCK_TOP)); break; case wxAUI_DOCK_TOP: layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_TOP), GetMaxLayer(docks, wxAUI_DOCK_LEFT)), GetMaxLayer(docks, wxAUI_DOCK_RIGHT)); break; case wxAUI_DOCK_RIGHT: layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_RIGHT), GetMaxLayer(docks, wxAUI_DOCK_TOP)), GetMaxLayer(docks, wxAUI_DOCK_BOTTOM)); break; case wxAUI_DOCK_BOTTOM: layer = wxMax(wxMax(GetMaxLayer(docks, wxAUI_DOCK_BOTTOM), GetMaxLayer(docks, wxAUI_DOCK_LEFT)), GetMaxLayer(docks, wxAUI_DOCK_RIGHT)); break; } DoInsertDockRow(panes, part->dock->dock_direction, layer, 0); drop.Dock(). Direction(part->dock->dock_direction). Layer(layer).Row(0).Position(0); return ProcessDockResult(target, drop); } if (!part->pane) return false; part = GetPanePart(part->pane->window); if (!part) return false; bool insert_dock_row = false; int insert_row = part->pane->dock_row; int insert_dir = part->pane->dock_direction; int insert_layer = part->pane->dock_layer; switch (part->pane->dock_direction) { case wxAUI_DOCK_TOP: if (pt.y >= part->rect.y && pt.y < part->rect.y+auiInsertRowPixels) insert_dock_row = true; break; case wxAUI_DOCK_BOTTOM: if (pt.y > part->rect.y+part->rect.height-auiInsertRowPixels && pt.y <= part->rect.y + part->rect.height) insert_dock_row = true; break; case wxAUI_DOCK_LEFT: if (pt.x >= part->rect.x && pt.x < part->rect.x+auiInsertRowPixels) insert_dock_row = true; break; case wxAUI_DOCK_RIGHT: if (pt.x > part->rect.x+part->rect.width-auiInsertRowPixels && pt.x <= part->rect.x+part->rect.width) insert_dock_row = true; break; case wxAUI_DOCK_CENTER: { // "new row pixels" will be set to the default, but // must never exceed 20% of the window size int new_row_pixels_x = auiNewRowPixels; int new_row_pixels_y = auiNewRowPixels; if (new_row_pixels_x > (part->rect.width*20)/100) new_row_pixels_x = (part->rect.width*20)/100; if (new_row_pixels_y > (part->rect.height*20)/100) new_row_pixels_y = (part->rect.height*20)/100; // determine if the mouse pointer is in a location that // will cause a new row to be inserted. The hot spot positions // are along the borders of the center pane insert_layer = 0; insert_dock_row = true; if (pt.x >= part->rect.x && pt.x < part->rect.x+new_row_pixels_x) insert_dir = wxAUI_DOCK_LEFT; else if (pt.y >= part->rect.y && pt.y < part->rect.y+new_row_pixels_y) insert_dir = wxAUI_DOCK_TOP; else if (pt.x >= part->rect.x + part->rect.width-new_row_pixels_x && pt.x < part->rect.x + part->rect.width) insert_dir = wxAUI_DOCK_RIGHT; else if (pt.y >= part->rect.y+ part->rect.height-new_row_pixels_y && pt.y < part->rect.y + part->rect.height) insert_dir = wxAUI_DOCK_BOTTOM; else return false; insert_row = GetMaxRow(panes, insert_dir, insert_layer) + 1; } } if (insert_dock_row) { DoInsertDockRow(panes, insert_dir, insert_layer, insert_row); drop.Dock().Direction(insert_dir). Layer(insert_layer). Row(insert_row). Position(0); return ProcessDockResult(target, drop); } // determine the mouse offset and the pane size, both in the // direction of the dock itself, and perpendicular to the dock int offset, size; if (part->orientation == wxVERTICAL) { offset = pt.y - part->rect.y; size = part->rect.GetHeight(); } else { offset = pt.x - part->rect.x; size = part->rect.GetWidth(); } int drop_position = part->pane->dock_pos; // if we are in the top/left part of the pane, // insert the pane before the pane being hovered over if (offset <= size/2) { drop_position = part->pane->dock_pos; DoInsertPane(panes, part->pane->dock_direction, part->pane->dock_layer, part->pane->dock_row, part->pane->dock_pos); } // if we are in the bottom/right part of the pane, // insert the pane before the pane being hovered over if (offset > size/2) { drop_position = part->pane->dock_pos+1; DoInsertPane(panes, part->pane->dock_direction, part->pane->dock_layer, part->pane->dock_row, part->pane->dock_pos+1); } drop.Dock(). Direction(part->dock->dock_direction). Layer(part->dock->dock_layer). Row(part->dock->dock_row). Position(drop_position); return ProcessDockResult(target, drop); } return false; } void wxAuiManager::OnHintFadeTimer(wxTimerEvent& WXUNUSED(event)) { if (!m_hint_wnd || m_hint_fadeamt >= m_hint_fademax) { m_hint_fadetimer.Stop(); return; } m_hint_fadeamt += 4; m_hint_wnd->SetTransparent(m_hint_fadeamt); } void wxAuiManager::ShowHint(const wxRect& rect) { if (m_hint_wnd) { // if the hint rect is the same as last time, don't do anything if (m_last_hint == rect) return; m_last_hint = rect; m_hint_fadeamt = m_hint_fademax; if ((m_flags & wxAUI_MGR_HINT_FADE) && !((m_hint_wnd->IsKindOf(CLASSINFO(wxPseudoTransparentFrame))) && (m_flags & wxAUI_MGR_NO_VENETIAN_BLINDS_FADE)) ) m_hint_fadeamt = 0; m_hint_wnd->SetSize(rect); m_hint_wnd->SetTransparent(m_hint_fadeamt); if (!m_hint_wnd->IsShown()) m_hint_wnd->Show(); // if we are dragging a floating pane, set the focus // back to that floating pane (otherwise it becomes unfocused) if (m_action == actionDragFloatingPane && m_action_window) m_action_window->SetFocus(); m_hint_wnd->Raise(); if (m_hint_fadeamt != m_hint_fademax) // Only fade if we need to { // start fade in timer m_hint_fadetimer.SetOwner(this, 101); m_hint_fadetimer.Start(5); } } else // Not using a transparent hint window... { if (!(m_flags & wxAUI_MGR_RECTANGLE_HINT)) return; if (m_last_hint != rect) { // remove the last hint rectangle m_last_hint = rect; m_frame->Refresh(); m_frame->Update(); } wxScreenDC screendc; wxRegion clip(1, 1, 10000, 10000); // clip all floating windows, so we don't draw over them int i, pane_count; for (i = 0, pane_count = m_panes.GetCount(); i < pane_count; ++i) { wxAuiPaneInfo& pane = m_panes.Item(i); if (pane.IsFloating() && pane.frame->IsShown()) { wxRect rect = pane.frame->GetRect(); #ifdef __WXGTK__ // wxGTK returns the client size, not the whole frame size rect.width += 15; rect.height += 35; rect.Inflate(5); #endif clip.Subtract(rect); } } // As we can only hide the hint by redrawing the managed window, we // need to clip the region to the managed window too or we get // nasty redrawn problems. clip.Intersect(m_frame->GetRect()); screendc.SetClippingRegion(clip); wxBitmap stipple = wxPaneCreateStippleBitmap(); wxBrush brush(stipple); screendc.SetBrush(brush); screendc.SetPen(*wxTRANSPARENT_PEN); screendc.DrawRectangle(rect.x, rect.y, 5, rect.height); screendc.DrawRectangle(rect.x+5, rect.y, rect.width-10, 5); screendc.DrawRectangle(rect.x+rect.width-5, rect.y, 5, rect.height); screendc.DrawRectangle(rect.x+5, rect.y+rect.height-5, rect.width-10, 5); } } void wxAuiManager::HideHint() { // hides a transparent window hint, if there is one if (m_hint_wnd) { if (m_hint_wnd->IsShown()) m_hint_wnd->Show(false); m_hint_wnd->SetTransparent(0); m_hint_fadetimer.Stop(); m_last_hint = wxRect(); return; } // hides a painted hint by redrawing the frame window if (!m_last_hint.IsEmpty()) { m_frame->Refresh(); m_frame->Update(); m_last_hint = wxRect(); } } void wxAuiManager::StartPaneDrag(wxWindow* pane_window, const wxPoint& offset) { wxAuiPaneInfo& pane = GetPane(pane_window); if (!pane.IsOk()) return; if (pane.IsToolbar()) { m_action = actionDragToolbarPane; } else { m_action = actionDragFloatingPane; } m_action_window = pane_window; m_action_offset = offset; m_frame->CaptureMouse(); } // CalculateHintRect() calculates the drop hint rectangle. The method // first calls DoDrop() to determine the exact position the pane would // be at were if dropped. If the pane would indeed become docked at the // specified drop point, the the rectangle hint will be returned in // screen coordinates. Otherwise, an empty rectangle is returned. // |pane_window| is the window pointer of the pane being dragged, |pt| is // the mouse position, in client coordinates. |offset| describes the offset // that the mouse is from the upper-left corner of the item being dragged wxRect wxAuiManager::CalculateHintRect(wxWindow* pane_window, const wxPoint& pt, const wxPoint& offset) { wxRect rect; // we need to paint a hint rectangle; to find out the exact hint rectangle, // we will create a new temporary layout and then measure the resulting // rectangle; we will create a copy of the docking structures (m_dock) // so that we don't modify the real thing on screen int i, pane_count, part_count; wxAuiDockInfoArray docks; wxAuiPaneInfoArray panes; wxAuiDockUIPartArray uiparts; wxAuiPaneInfo hint = GetPane(pane_window); hint.name = wxT("__HINT__"); hint.PaneBorder(true); hint.Show(); if (!hint.IsOk()) return rect; CopyDocksAndPanes(docks, panes, m_docks, m_panes); // remove any pane already there which bears the same window; // this happens when you are moving a pane around in a dock for (i = 0, pane_count = panes.GetCount(); i < pane_count; ++i) { if (panes.Item(i).window == pane_window) { RemovePaneFromDocks(docks, panes.Item(i)); panes.RemoveAt(i); break; } } // find out where the new pane would be if (!DoDrop(docks, panes, hint, pt, offset)) { return rect; } panes.Add(hint); wxSizer* sizer = LayoutAll(panes, docks, uiparts, true); wxSize client_size = m_frame->GetClientSize(); sizer->SetDimension(0, 0, client_size.x, client_size.y); sizer->Layout(); for (i = 0, part_count = uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = uiparts.Item(i); if (part.type == wxAuiDockUIPart::typePaneBorder && part.pane && part.pane->name == wxT("__HINT__")) { rect = wxRect(part.sizer_item->GetPosition(), part.sizer_item->GetSize()); break; } } delete sizer; if (rect.IsEmpty()) { return rect; } // actually show the hint rectangle on the screen m_frame->ClientToScreen(&rect.x, &rect.y); if ( m_frame->GetLayoutDirection() == wxLayout_RightToLeft ) { // Mirror rectangle in RTL mode rect.x -= rect.GetWidth(); } return rect; } // DrawHintRect() calculates the hint rectangle by calling // CalculateHintRect(). If there is a rectangle, it shows it // by calling ShowHint(), otherwise it hides any hint // rectangle currently shown void wxAuiManager::DrawHintRect(wxWindow* pane_window, const wxPoint& pt, const wxPoint& offset) { wxRect rect = CalculateHintRect(pane_window, pt, offset); if (rect.IsEmpty()) { HideHint(); } else { ShowHint(rect); } } void wxAuiManager::OnFloatingPaneMoveStart(wxWindow* wnd) { // try to find the pane wxAuiPaneInfo& pane = GetPane(wnd); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); if(!pane.frame) return; if (m_flags & wxAUI_MGR_TRANSPARENT_DRAG) pane.frame->SetTransparent(150); } void wxAuiManager::OnFloatingPaneMoving(wxWindow* wnd, wxDirection dir) { // try to find the pane wxAuiPaneInfo& pane = GetPane(wnd); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); if(!pane.frame) return; wxPoint pt = ::wxGetMousePosition(); #if 0 // Adapt pt to direction if (dir == wxNORTH) { // move to pane's upper border wxPoint pos( 0,0 ); pos = wnd->ClientToScreen( pos ); pt.y = pos.y; // and some more pixels for the title bar pt.y -= 5; } else if (dir == wxWEST) { // move to pane's left border wxPoint pos( 0,0 ); pos = wnd->ClientToScreen( pos ); pt.x = pos.x; } else if (dir == wxEAST) { // move to pane's right border wxPoint pos( wnd->GetSize().x, 0 ); pos = wnd->ClientToScreen( pos ); pt.x = pos.x; } else if (dir == wxSOUTH) { // move to pane's bottom border wxPoint pos( 0, wnd->GetSize().y ); pos = wnd->ClientToScreen( pos ); pt.y = pos.y; } #else wxUnusedVar(dir); #endif wxPoint client_pt = m_frame->ScreenToClient(pt); // calculate the offset from the upper left-hand corner // of the frame to the mouse pointer wxPoint frame_pos = pane.frame->GetPosition(); wxPoint action_offset(pt.x-frame_pos.x, pt.y-frame_pos.y); // no hint for toolbar floating windows if (pane.IsToolbar() && m_action == actionDragFloatingPane) { if (m_action == actionDragFloatingPane) { wxAuiDockInfoArray docks; wxAuiPaneInfoArray panes; wxAuiDockUIPartArray uiparts; wxAuiPaneInfo hint = pane; CopyDocksAndPanes(docks, panes, m_docks, m_panes); // find out where the new pane would be if (!DoDrop(docks, panes, hint, client_pt)) return; if (hint.IsFloating()) return; pane = hint; m_action = actionDragToolbarPane; m_action_window = pane.window; Update(); } return; } // if a key modifier is pressed while dragging the frame, // don't dock the window if (wxGetKeyState(WXK_CONTROL) || wxGetKeyState(WXK_ALT)) { HideHint(); return; } DrawHintRect(wnd, client_pt, action_offset); #ifdef __WXGTK__ // this cleans up some screen artifacts that are caused on GTK because // we aren't getting the exact size of the window (see comment // in DrawHintRect) //Refresh(); #endif // reduces flicker m_frame->Update(); } void wxAuiManager::OnFloatingPaneMoved(wxWindow* wnd, wxDirection dir) { // try to find the pane wxAuiPaneInfo& pane = GetPane(wnd); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); if(!pane.frame) return; wxPoint pt = ::wxGetMousePosition(); #if 0 // Adapt pt to direction if (dir == wxNORTH) { // move to pane's upper border wxPoint pos( 0,0 ); pos = wnd->ClientToScreen( pos ); pt.y = pos.y; // and some more pixels for the title bar pt.y -= 10; } else if (dir == wxWEST) { // move to pane's left border wxPoint pos( 0,0 ); pos = wnd->ClientToScreen( pos ); pt.x = pos.x; } else if (dir == wxEAST) { // move to pane's right border wxPoint pos( wnd->GetSize().x, 0 ); pos = wnd->ClientToScreen( pos ); pt.x = pos.x; } else if (dir == wxSOUTH) { // move to pane's bottom border wxPoint pos( 0, wnd->GetSize().y ); pos = wnd->ClientToScreen( pos ); pt.y = pos.y; } #else wxUnusedVar(dir); #endif wxPoint client_pt = m_frame->ScreenToClient(pt); // calculate the offset from the upper left-hand corner // of the frame to the mouse pointer wxPoint frame_pos = pane.frame->GetPosition(); wxPoint action_offset(pt.x-frame_pos.x, pt.y-frame_pos.y); // if a key modifier is pressed while dragging the frame, // don't dock the window if (!wxGetKeyState(WXK_CONTROL) && !wxGetKeyState(WXK_ALT)) { // do the drop calculation DoDrop(m_docks, m_panes, pane, client_pt, action_offset); } // if the pane is still floating, update it's floating // position (that we store) if (pane.IsFloating()) { pane.floating_pos = pane.frame->GetPosition(); if (m_flags & wxAUI_MGR_TRANSPARENT_DRAG) pane.frame->SetTransparent(255); } else if (m_has_maximized) { RestoreMaximizedPane(); } Update(); HideHint(); } void wxAuiManager::OnFloatingPaneResized(wxWindow* wnd, const wxSize& size) { // try to find the pane wxAuiPaneInfo& pane = GetPane(wnd); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); pane.floating_size = size; } void wxAuiManager::OnFloatingPaneClosed(wxWindow* wnd, wxCloseEvent& evt) { // try to find the pane wxAuiPaneInfo& pane = GetPane(wnd); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); // fire pane close event wxAuiManagerEvent e(wxEVT_AUI_PANE_CLOSE); e.SetPane(&pane); e.SetCanVeto(evt.CanVeto()); ProcessMgrEvent(e); if (e.GetVeto()) { evt.Veto(); return; } else { // close the pane, but check that it // still exists in our pane array first // (the event handler above might have removed it) wxAuiPaneInfo& check = GetPane(wnd); if (check.IsOk()) { ClosePane(pane); } } } void wxAuiManager::OnFloatingPaneActivated(wxWindow* wnd) { if ((GetFlags() & wxAUI_MGR_ALLOW_ACTIVE_PANE) && GetPane(wnd).IsOk()) { SetActivePane(m_panes, wnd); Repaint(); } } // OnRender() draws all of the pane captions, sashes, // backgrounds, captions, grippers, pane borders and buttons. // It renders the entire user interface. void wxAuiManager::OnRender(wxAuiManagerEvent& evt) { // if the frame is about to be deleted, don't bother if (!m_frame || wxPendingDelete.Member(m_frame)) return; wxDC* dc = evt.GetDC(); #ifdef __WXMAC__ dc->Clear() ; #endif int i, part_count; for (i = 0, part_count = m_uiparts.GetCount(); i < part_count; ++i) { wxAuiDockUIPart& part = m_uiparts.Item(i); // don't draw hidden pane items or items that aren't windows if (part.sizer_item && ((!part.sizer_item->IsWindow() && !part.sizer_item->IsSpacer() && !part.sizer_item->IsSizer()) || !part.sizer_item->IsShown())) continue; switch (part.type) { case wxAuiDockUIPart::typeDockSizer: case wxAuiDockUIPart::typePaneSizer: m_art->DrawSash(*dc, m_frame, part.orientation, part.rect); break; case wxAuiDockUIPart::typeBackground: m_art->DrawBackground(*dc, m_frame, part.orientation, part.rect); break; case wxAuiDockUIPart::typeCaption: m_art->DrawCaption(*dc, m_frame, part.pane->caption, part.rect, *part.pane); break; case wxAuiDockUIPart::typeGripper: m_art->DrawGripper(*dc, m_frame, part.rect, *part.pane); break; case wxAuiDockUIPart::typePaneBorder: m_art->DrawBorder(*dc, m_frame, part.rect, *part.pane); break; case wxAuiDockUIPart::typePaneButton: m_art->DrawPaneButton(*dc, m_frame, part.button->button_id, wxAUI_BUTTON_STATE_NORMAL, part.rect, *part.pane); break; } } } // Render() fire a render event, which is normally handled by // wxAuiManager::OnRender(). This allows the render function to // be overridden via the render event. This can be useful for paintin // custom graphics in the main window. Default behavior can be // invoked in the overridden function by calling OnRender() void wxAuiManager::Render(wxDC* dc) { wxAuiManagerEvent e(wxEVT_AUI_RENDER); e.SetManager(this); e.SetDC(dc); ProcessMgrEvent(e); } void wxAuiManager::Repaint(wxDC* dc) { #ifdef __WXMAC__ if ( dc == NULL ) { m_frame->Refresh() ; m_frame->Update() ; return ; } #endif int w, h; m_frame->GetClientSize(&w, &h); // figure out which dc to use; if one // has been specified, use it, otherwise // make a client dc wxClientDC* client_dc = NULL; if (!dc) { client_dc = new wxClientDC(m_frame); dc = client_dc; } // if the frame has a toolbar, the client area // origin will not be (0,0). wxPoint pt = m_frame->GetClientAreaOrigin(); if (pt.x != 0 || pt.y != 0) dc->SetDeviceOrigin(pt.x, pt.y); // render all the items Render(dc); // if we created a client_dc, delete it if (client_dc) delete client_dc; } void wxAuiManager::OnPaint(wxPaintEvent& WXUNUSED(event)) { wxPaintDC dc(m_frame); Repaint(&dc); } void wxAuiManager::OnEraseBackground(wxEraseEvent& event) { #ifdef __WXMAC__ event.Skip() ; #else wxUnusedVar(event); #endif } void wxAuiManager::OnSize(wxSizeEvent& event) { if (m_frame) { DoFrameLayout(); Repaint(); #if wxUSE_MDI if (m_frame->IsKindOf(CLASSINFO(wxMDIParentFrame))) { // for MDI parent frames, this event must not // be "skipped". In other words, the parent frame // must not be allowed to resize the client window // after we are finished processing sizing changes return; } #endif } event.Skip(); } void wxAuiManager::OnFindManager(wxAuiManagerEvent& evt) { // get the window we are managing, if none, return NULL wxWindow* window = GetManagedWindow(); if (!window) { evt.SetManager(NULL); return; } // if we are managing a child frame, get the 'real' manager if (window->IsKindOf(CLASSINFO(wxAuiFloatingFrame))) { wxAuiFloatingFrame* float_frame = wx_static_cast(wxAuiFloatingFrame*, window); evt.SetManager(float_frame->GetOwnerManager()); return; } // return pointer to ourself evt.SetManager(this); } void wxAuiManager::OnSetCursor(wxSetCursorEvent& event) { // determine cursor wxAuiDockUIPart* part = HitTest(event.GetX(), event.GetY()); wxCursor cursor = wxNullCursor; if (part) { if (part->type == wxAuiDockUIPart::typeDockSizer || part->type == wxAuiDockUIPart::typePaneSizer) { // a dock may not be resized if it has a single // pane which is not resizable if (part->type == wxAuiDockUIPart::typeDockSizer && part->dock && part->dock->panes.GetCount() == 1 && part->dock->panes.Item(0)->IsFixed()) return; // panes that may not be resized do not get a sizing cursor if (part->pane && part->pane->IsFixed()) return; if (part->orientation == wxVERTICAL) cursor = wxCursor(wxCURSOR_SIZEWE); else cursor = wxCursor(wxCURSOR_SIZENS); } else if (part->type == wxAuiDockUIPart::typeGripper) { cursor = wxCursor(wxCURSOR_SIZING); } } event.SetCursor(cursor); } void wxAuiManager::UpdateButtonOnScreen(wxAuiDockUIPart* button_ui_part, const wxMouseEvent& event) { wxAuiDockUIPart* hit_test = HitTest(event.GetX(), event.GetY()); if (!hit_test || !button_ui_part) return; int state = wxAUI_BUTTON_STATE_NORMAL; if (hit_test == button_ui_part) { if (event.LeftDown()) state = wxAUI_BUTTON_STATE_PRESSED; else state = wxAUI_BUTTON_STATE_HOVER; } else { if (event.LeftDown()) state = wxAUI_BUTTON_STATE_HOVER; } // now repaint the button with hover state wxClientDC cdc(m_frame); // if the frame has a toolbar, the client area // origin will not be (0,0). wxPoint pt = m_frame->GetClientAreaOrigin(); if (pt.x != 0 || pt.y != 0) cdc.SetDeviceOrigin(pt.x, pt.y); if (hit_test->pane) { m_art->DrawPaneButton(cdc, m_frame, button_ui_part->button->button_id, state, button_ui_part->rect, *hit_test->pane); } } static int gs_CurrentDragItem = -1; void wxAuiManager::OnLeftDown(wxMouseEvent& event) { gs_CurrentDragItem = -1; wxAuiDockUIPart* part = HitTest(event.GetX(), event.GetY()); if (part) { if (part->type == wxAuiDockUIPart::typeDockSizer || part->type == wxAuiDockUIPart::typePaneSizer) { // Removing this restriction so that a centre pane can be resized //if (part->dock && part->dock->dock_direction == wxAUI_DOCK_CENTER) // return; // a dock may not be resized if it has a single // pane which is not resizable if (part->type == wxAuiDockUIPart::typeDockSizer && part->dock && part->dock->panes.GetCount() == 1 && part->dock->panes.Item(0)->IsFixed()) return; // panes that may not be resized should be ignored here if (part->pane && part->pane->IsFixed()) return; m_action = actionResize; m_action_part = part; m_action_hintrect = wxRect(); m_action_start = wxPoint(event.m_x, event.m_y); m_action_offset = wxPoint(event.m_x - part->rect.x, event.m_y - part->rect.y); m_frame->CaptureMouse(); } else if (part->type == wxAuiDockUIPart::typePaneButton) { m_action = actionClickButton; m_action_part = part; m_action_start = wxPoint(event.m_x, event.m_y); m_frame->CaptureMouse(); UpdateButtonOnScreen(part, event); } else if (part->type == wxAuiDockUIPart::typeCaption || part->type == wxAuiDockUIPart::typeGripper) { // if we are managing a wxAuiFloatingFrame window, then // we are an embedded wxAuiManager inside the wxAuiFloatingFrame. // We want to initiate a toolbar drag in our owner manager wxWindow* managed_wnd = GetManagedWindow(); if (part->pane && part->pane->window && managed_wnd && managed_wnd->IsKindOf(CLASSINFO(wxAuiFloatingFrame))) { wxAuiFloatingFrame* floating_frame = (wxAuiFloatingFrame*)managed_wnd; wxAuiManager* owner_mgr = floating_frame->GetOwnerManager(); owner_mgr->StartPaneDrag(part->pane->window, wxPoint(event.m_x - part->rect.x, event.m_y - part->rect.y)); return; } if (GetFlags() & wxAUI_MGR_ALLOW_ACTIVE_PANE) { // set the caption as active SetActivePane(m_panes, part->pane->window); Repaint(); } if (part->dock && part->dock->dock_direction == wxAUI_DOCK_CENTER) return; m_action = actionClickCaption; m_action_part = part; m_action_start = wxPoint(event.m_x, event.m_y); m_action_offset = wxPoint(event.m_x - part->rect.x, event.m_y - part->rect.y); m_frame->CaptureMouse(); } #ifdef __WXMAC__ else { event.Skip(); } #endif } #ifdef __WXMAC__ else { event.Skip(); } #else event.Skip(); #endif } /// Ends a resize action, or for live update, resizes the sash bool wxAuiManager::DoEndResizeAction(wxMouseEvent& event) { // resize the dock or the pane if (m_action_part && m_action_part->type==wxAuiDockUIPart::typeDockSizer) { // first, we must calculate the maximum size the dock may be int sash_size = m_art->GetMetric(wxAUI_DOCKART_SASH_SIZE); int used_width = 0, used_height = 0; wxSize client_size = m_frame->GetClientSize(); size_t dock_i, dock_count = m_docks.GetCount(); for (dock_i = 0; dock_i < dock_count; ++dock_i) { wxAuiDockInfo& dock = m_docks.Item(dock_i); if (dock.dock_direction == wxAUI_DOCK_TOP || dock.dock_direction == wxAUI_DOCK_BOTTOM) { used_height += dock.size; } if (dock.dock_direction == wxAUI_DOCK_LEFT || dock.dock_direction == wxAUI_DOCK_RIGHT) { used_width += dock.size; } if (dock.resizable) used_width += sash_size; } int available_width = client_size.GetWidth() - used_width; int available_height = client_size.GetHeight() - used_height; #if wxUSE_STATUSBAR // if there's a status control, the available // height decreases accordingly if (m_frame && m_frame->IsKindOf(CLASSINFO(wxFrame))) { wxFrame* frame = static_cast<wxFrame*>(m_frame); wxStatusBar* status = frame->GetStatusBar(); if (status) { wxSize status_client_size = status->GetClientSize(); available_height -= status_client_size.GetHeight(); } } #endif wxRect& rect = m_action_part->dock->rect; wxPoint new_pos(event.m_x - m_action_offset.x, event.m_y - m_action_offset.y); int new_size, old_size = m_action_part->dock->size; switch (m_action_part->dock->dock_direction) { case wxAUI_DOCK_LEFT: new_size = new_pos.x - rect.x; if (new_size-old_size > available_width) new_size = old_size+available_width; m_action_part->dock->size = new_size; break; case wxAUI_DOCK_TOP: new_size = new_pos.y - rect.y; if (new_size-old_size > available_height) new_size = old_size+available_height; m_action_part->dock->size = new_size; break; case wxAUI_DOCK_RIGHT: new_size = rect.x + rect.width - new_pos.x - m_action_part->rect.GetWidth(); if (new_size-old_size > available_width) new_size = old_size+available_width; m_action_part->dock->size = new_size; break; case wxAUI_DOCK_BOTTOM: new_size = rect.y + rect.height - new_pos.y - m_action_part->rect.GetHeight(); if (new_size-old_size > available_height) new_size = old_size+available_height; m_action_part->dock->size = new_size; break; } Update(); Repaint(NULL); } else if (m_action_part && m_action_part->type == wxAuiDockUIPart::typePaneSizer) { wxAuiDockInfo& dock = *m_action_part->dock; wxAuiPaneInfo& pane = *m_action_part->pane; int total_proportion = 0; int dock_pixels = 0; int new_pixsize = 0; int caption_size = m_art->GetMetric(wxAUI_DOCKART_CAPTION_SIZE); int pane_border_size = m_art->GetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE); int sash_size = m_art->GetMetric(wxAUI_DOCKART_SASH_SIZE); wxPoint new_pos(event.m_x - m_action_offset.x, event.m_y - m_action_offset.y); // determine the pane rectangle by getting the pane part wxAuiDockUIPart* pane_part = GetPanePart(pane.window); wxASSERT_MSG(pane_part, wxT("Pane border part not found -- shouldn't happen")); // determine the new pixel size that the user wants; // this will help us recalculate the pane's proportion if (dock.IsHorizontal()) new_pixsize = new_pos.x - pane_part->rect.x; else new_pixsize = new_pos.y - pane_part->rect.y; // determine the size of the dock, based on orientation if (dock.IsHorizontal()) dock_pixels = dock.rect.GetWidth(); else dock_pixels = dock.rect.GetHeight(); // determine the total proportion of all resizable panes, // and the total size of the dock minus the size of all // the fixed panes int i, dock_pane_count = dock.panes.GetCount(); int pane_position = -1; for (i = 0; i < dock_pane_count; ++i) { wxAuiPaneInfo& p = *dock.panes.Item(i); if (p.window == pane.window) pane_position = i; // while we're at it, subtract the pane sash // width from the dock width, because this would // skew our proportion calculations if (i > 0) dock_pixels -= sash_size; // also, the whole size (including decorations) of // all fixed panes must also be subtracted, because they // are not part of the proportion calculation if (p.IsFixed()) { if (dock.IsHorizontal()) dock_pixels -= p.best_size.x; else dock_pixels -= p.best_size.y; } else { total_proportion += p.dock_proportion; } } // new size can never be more than the number of dock pixels if (new_pixsize > dock_pixels) new_pixsize = dock_pixels; // find a pane in our dock to 'steal' space from or to 'give' // space to -- this is essentially what is done when a pane is // resized; the pane should usually be the first non-fixed pane // to the right of the action pane int borrow_pane = -1; for (i = pane_position+1; i < dock_pane_count; ++i) { wxAuiPaneInfo& p = *dock.panes.Item(i); if (!p.IsFixed()) { borrow_pane = i; break; } } // demand that the pane being resized is found in this dock // (this assert really never should be raised) wxASSERT_MSG(pane_position != -1, wxT("Pane not found in dock")); // prevent division by zero if (dock_pixels == 0 || total_proportion == 0 || borrow_pane == -1) { m_action = actionNone; return false; } // calculate the new proportion of the pane int new_proportion = (new_pixsize*total_proportion)/dock_pixels; // default minimum size int min_size = 0; // check against the pane's minimum size, if specified. please note // that this is not enough to ensure that the minimum size will // not be violated, because the whole frame might later be shrunk, // causing the size of the pane to violate it's minimum size if (pane.min_size.IsFullySpecified()) { min_size = 0; if (pane.HasBorder()) min_size += (pane_border_size*2); // calculate minimum size with decorations (border,caption) if (pane_part->orientation == wxVERTICAL) { min_size += pane.min_size.y; if (pane.HasCaption()) min_size += caption_size; } else { min_size += pane.min_size.x; } } // for some reason, an arithmatic error somewhere is causing // the proportion calculations to always be off by 1 pixel; // for now we will add the 1 pixel on, but we really should // determine what's causing this. min_size++; int min_proportion = (min_size*total_proportion)/dock_pixels; if (new_proportion < min_proportion) new_proportion = min_proportion; int prop_diff = new_proportion - pane.dock_proportion; // borrow the space from our neighbor pane to the // right or bottom (depending on orientation); // also make sure we don't make the neighbor too small int prop_borrow = dock.panes.Item(borrow_pane)->dock_proportion; if (prop_borrow - prop_diff < 0) { // borrowing from other pane would make it too small, // so cancel the resize operation prop_borrow = min_proportion; } else { prop_borrow -= prop_diff; } dock.panes.Item(borrow_pane)->dock_proportion = prop_borrow; pane.dock_proportion = new_proportion; // repaint Update(); Repaint(NULL); } return true; } void wxAuiManager::OnLeftUp(wxMouseEvent& event) { if (m_action == actionResize) { m_frame->ReleaseMouse(); // get rid of the hint rectangle // On non-CG Mac we use a wxClientDC since when compiling and running on Leopard, // we can get the dreaded _SetDstBlits32BGRA crash (but not in the AUI sample). // In CG mode we always use live resize since DrawResizeHint doesn't work. if (!wxAuiManager_HasLiveResize(*this)) { // get rid of the hint rectangle #if defined(__WXMAC__) && !wxMAC_USE_CORE_GRAPHICS wxClientDC dc(m_frame); #else wxScreenDC dc; #endif DrawResizeHint(dc, m_action_hintrect); } if (gs_CurrentDragItem != -1 && wxAuiManager_HasLiveResize(*this)) m_action_part = & (m_uiparts.Item(gs_CurrentDragItem)); DoEndResizeAction(event); gs_CurrentDragItem = -1; } else if (m_action == actionClickButton) { m_hover_button = NULL; m_frame->ReleaseMouse(); if (m_action_part) { UpdateButtonOnScreen(m_action_part, event); // make sure we're still over the item that was originally clicked if (m_action_part == HitTest(event.GetX(), event.GetY())) { // fire button-click event wxAuiManagerEvent e(wxEVT_AUI_PANE_BUTTON); e.SetManager(this); e.SetPane(m_action_part->pane); e.SetButton(m_action_part->button->button_id); ProcessMgrEvent(e); } } } else if (m_action == actionClickCaption) { m_frame->ReleaseMouse(); } else if (m_action == actionDragFloatingPane) { m_frame->ReleaseMouse(); } else if (m_action == actionDragToolbarPane) { m_frame->ReleaseMouse(); wxAuiPaneInfo& pane = GetPane(m_action_window); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); // save the new positions wxAuiDockInfoPtrArray docks; FindDocks(m_docks, pane.dock_direction, pane.dock_layer, pane.dock_row, docks); if (docks.GetCount() == 1) { wxAuiDockInfo& dock = *docks.Item(0); wxArrayInt pane_positions, pane_sizes; GetPanePositionsAndSizes(dock, pane_positions, pane_sizes); int i, dock_pane_count = dock.panes.GetCount(); for (i = 0; i < dock_pane_count; ++i) dock.panes.Item(i)->dock_pos = pane_positions[i]; } pane.state &= ~wxAuiPaneInfo::actionPane; Update(); } else { event.Skip(); } m_action = actionNone; m_last_mouse_move = wxPoint(); // see comment in OnMotion() } void wxAuiManager::OnMotion(wxMouseEvent& event) { // sometimes when Update() is called from inside this method, // a spurious mouse move event is generated; this check will make // sure that only real mouse moves will get anywhere in this method; // this appears to be a bug somewhere, and I don't know where the // mouse move event is being generated. only verified on MSW wxPoint mouse_pos = event.GetPosition(); if (m_last_mouse_move == mouse_pos) return; m_last_mouse_move = mouse_pos; if (m_action == actionResize) { // It's necessary to reset m_action_part since it destroyed // by the Update within DoEndResizeAction. if (gs_CurrentDragItem != -1) m_action_part = & (m_uiparts.Item(gs_CurrentDragItem)); else gs_CurrentDragItem = m_uiparts.Index(* m_action_part); if (m_action_part) { wxPoint pos = m_action_part->rect.GetPosition(); if (m_action_part->orientation == wxHORIZONTAL) pos.y = wxMax(0, event.m_y - m_action_offset.y); else pos.x = wxMax(0, event.m_x - m_action_offset.x); if (wxAuiManager_HasLiveResize(*this)) { m_frame->ReleaseMouse(); DoEndResizeAction(event); m_frame->CaptureMouse(); } else { #if defined(__WXMAC__) && !wxMAC_USE_CORE_GRAPHICS wxRect rect(pos, m_action_part->rect.GetSize()); wxClientDC dc(m_frame); #else wxRect rect(m_frame->ClientToScreen(pos), m_action_part->rect.GetSize()); wxScreenDC dc; #endif if (!m_action_hintrect.IsEmpty()) { // remove old resize hint DrawResizeHint(dc, m_action_hintrect); m_action_hintrect = wxRect(); } // draw new resize hint, if it's inside the managed frame wxRect frame_screen_rect = m_frame->GetScreenRect(); if (frame_screen_rect.Contains(rect)) { DrawResizeHint(dc, rect); m_action_hintrect = rect; } } } } else if (m_action == actionClickCaption) { int drag_x_threshold = wxSystemSettings::GetMetric(wxSYS_DRAG_X); int drag_y_threshold = wxSystemSettings::GetMetric(wxSYS_DRAG_Y); // caption has been clicked. we need to check if the mouse // is now being dragged. if it is, we need to change the // mouse action to 'drag' if (m_action_part && (abs(event.m_x - m_action_start.x) > drag_x_threshold || abs(event.m_y - m_action_start.y) > drag_y_threshold)) { wxAuiPaneInfo* pane_info = m_action_part->pane; if (!pane_info->IsToolbar()) { if ((m_flags & wxAUI_MGR_ALLOW_FLOATING) && pane_info->IsFloatable()) { m_action = actionDragFloatingPane; // set initial float position wxPoint pt = m_frame->ClientToScreen(event.GetPosition()); pane_info->floating_pos = wxPoint(pt.x - m_action_offset.x, pt.y - m_action_offset.y); // float the window if (pane_info->IsMaximized()) RestorePane(*pane_info); pane_info->Float(); Update(); m_action_window = pane_info->frame; // action offset is used here to make it feel "natural" to the user // to drag a docked pane and suddenly have it become a floating frame. // Sometimes, however, the offset where the user clicked on the docked // caption is bigger than the width of the floating frame itself, so // in that case we need to set the action offset to a sensible value wxSize frame_size = m_action_window->GetSize(); if (frame_size.x <= m_action_offset.x) m_action_offset.x = 30; } } else { m_action = actionDragToolbarPane; m_action_window = pane_info->window; } } } else if (m_action == actionDragFloatingPane) { if (m_action_window) { wxPoint pt = m_frame->ClientToScreen(event.GetPosition()); m_action_window->Move(pt.x - m_action_offset.x, pt.y - m_action_offset.y); } } else if (m_action == actionDragToolbarPane) { wxAuiPaneInfo& pane = GetPane(m_action_window); wxASSERT_MSG(pane.IsOk(), wxT("Pane window not found")); pane.state |= wxAuiPaneInfo::actionPane; wxPoint pt = event.GetPosition(); DoDrop(m_docks, m_panes, pane, pt, m_action_offset); // if DoDrop() decided to float the pane, set up // the floating pane's initial position if (pane.IsFloating()) { wxPoint pt = m_frame->ClientToScreen(event.GetPosition()); pane.floating_pos = wxPoint(pt.x - m_action_offset.x, pt.y - m_action_offset.y); } // this will do the actiual move operation; // in the case that the pane has been floated, // this call will create the floating pane // and do the reparenting Update(); // if the pane has been floated, change the mouse // action actionDragFloatingPane so that subsequent // EVT_MOTION() events will move the floating pane if (pane.IsFloating()) { pane.state &= ~wxAuiPaneInfo::actionPane; m_action = actionDragFloatingPane; m_action_window = pane.frame; } } else { wxAuiDockUIPart* part = HitTest(event.GetX(), event.GetY()); if (part && part->type == wxAuiDockUIPart::typePaneButton) { if (part != m_hover_button) { // make the old button normal if (m_hover_button) { UpdateButtonOnScreen(m_hover_button, event); Repaint(); } // mouse is over a button, so repaint the // button in hover mode UpdateButtonOnScreen(part, event); m_hover_button = part; } } else { if (m_hover_button) { m_hover_button = NULL; Repaint(); } else { event.Skip(); } } } } void wxAuiManager::OnLeaveWindow(wxMouseEvent& WXUNUSED(event)) { if (m_hover_button) { m_hover_button = NULL; Repaint(); } } void wxAuiManager::OnChildFocus(wxChildFocusEvent& event) { // when a child pane has it's focus set, we should change the // pane's active state to reflect this. (this is only true if // active panes are allowed by the owner) if (GetFlags() & wxAUI_MGR_ALLOW_ACTIVE_PANE) { wxAuiPaneInfo& pane = GetPane(event.GetWindow()); if (pane.IsOk() && (pane.state & wxAuiPaneInfo::optionActive) == 0) { SetActivePane(m_panes, event.GetWindow()); m_frame->Refresh(); } } event.Skip(); } // OnPaneButton() is an event handler that is called // when a pane button has been pressed. void wxAuiManager::OnPaneButton(wxAuiManagerEvent& evt) { wxASSERT_MSG(evt.pane, wxT("Pane Info passed to wxAuiManager::OnPaneButton must be non-null")); wxAuiPaneInfo& pane = *(evt.pane); if (evt.button == wxAUI_BUTTON_CLOSE) { // fire pane close event wxAuiManagerEvent e(wxEVT_AUI_PANE_CLOSE); e.SetManager(this); e.SetPane(evt.pane); ProcessMgrEvent(e); if (!e.GetVeto()) { // close the pane, but check that it // still exists in our pane array first // (the event handler above might have removed it) wxAuiPaneInfo& check = GetPane(pane.window); if (check.IsOk()) { ClosePane(pane); } Update(); } } else if (evt.button == wxAUI_BUTTON_MAXIMIZE_RESTORE && !pane.IsMaximized()) { // fire pane close event wxAuiManagerEvent e(wxEVT_AUI_PANE_MAXIMIZE); e.SetManager(this); e.SetPane(evt.pane); ProcessMgrEvent(e); if (!e.GetVeto()) { MaximizePane(pane); Update(); } } else if (evt.button == wxAUI_BUTTON_MAXIMIZE_RESTORE && pane.IsMaximized()) { // fire pane close event wxAuiManagerEvent e(wxEVT_AUI_PANE_RESTORE); e.SetManager(this); e.SetPane(evt.pane); ProcessMgrEvent(e); if (!e.GetVeto()) { RestorePane(pane); Update(); } } else if (evt.button == wxAUI_BUTTON_PIN) { if ((m_flags & wxAUI_MGR_ALLOW_FLOATING) && pane.IsFloatable()) pane.Float(); Update(); } } #endif // wxUSE_AUI
hajuuk/R7000
ap/gpl/amule/wxWidgets-2.8.12/src/aui/framemanager.cpp
C++
gpl-2.0
147,103
public class ReferralCallback { // Constructors public ReferralCallback() {} // Methods public Type GetType() {} public virtual string ToString() {} public virtual bool Equals(object obj) {} public virtual int GetHashCode() {} // Properties public QueryForConnectionCallback QueryForConnection { get{} set{} } public NotifyOfNewConnectionCallback NotifyNewConnection { get{} set{} } public DereferenceConnectionCallback DereferenceConnection { get{} set{} } }
Pengfei-Gao/source-Insight-3-for-centos7
SourceInsight3/NetFramework/ReferralCallback.cs
C#
gpl-2.0
475
/* * USE - UML based specification environment * Copyright (C) 1999-2004 Mark Richters, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // $Id: DiamondNode.java 5953 2016-05-11 14:00:02Z fhilken $ package org.tzi.use.gui.views.diagrams.elements; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.tzi.use.gui.util.PersistHelper; import org.tzi.use.gui.views.diagrams.DiagramOptions; import org.tzi.use.gui.views.diagrams.elements.edges.AssociationOrLinkPartEdge; import org.tzi.use.gui.views.diagrams.elements.edges.EdgeBase; import org.tzi.use.gui.views.diagrams.elements.positioning.StrategyFixed; import org.tzi.use.gui.views.diagrams.elements.positioning.StrategyInBetween; import org.tzi.use.gui.xmlparser.LayoutTags; import org.tzi.use.uml.mm.MAssociation; import org.tzi.use.uml.mm.MAssociationClass; import org.tzi.use.uml.mm.MClass; import org.tzi.use.uml.sys.MLink; import org.tzi.use.uml.sys.MObject; import org.w3c.dom.Element; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * A pseude-node representing a diamond in an n-ary association. * * @version $ProjectVersion: 0.393 $ * @author Fabian Gutsche */ public class DiamondNode extends PlaceableNode { private final DiagramOptions fOpt; private final MAssociation fAssoc; private MLink fLink; private AssociationName fAssocName; private final List<String> fConnectedNodes; private final String fName; private List<EdgeBase> fHalfEdges; // participating edges public DiamondNode( MAssociation assoc, DiagramOptions opt ) { fAssoc = assoc; fName = assoc.name(); fOpt = opt; fConnectedNodes = new ArrayList<String>(); Set<MClass> classes = fAssoc.associatedClasses(); for (MClass cls : classes) { fConnectedNodes.add( cls.name() ); } if (!(assoc instanceof MAssociationClass)) { instanciateAssocName(false); } } public DiamondNode( MLink link, DiagramOptions opt ) { fAssoc = link.association(); fLink = link; fName = fAssoc.name(); fOpt = opt; fConnectedNodes = new ArrayList<String>(); List<MObject> objects = link.linkedObjects(); for (MObject obj : objects) { fConnectedNodes.add( obj.name() ); } if (!(fAssoc instanceof MAssociationClass)) { instanciateAssocName(true); } } private void instanciateAssocName(boolean isLink) { fAssocName = new AssociationName( getId() + "::AssociationName", fName, fOpt, this, fAssoc, fLink ); } public MAssociation association() { return fAssoc; } public MLink link() { return fLink; } @Override public String getId() { return fAssoc.name() + "::DiamondNode"; } @Override public String name() { return fAssoc.name(); } public void setHalfEdges( List<EdgeBase> edges, List<String> edgeIds) { fHalfEdges = edges; Set<PlaceableNode> related = new HashSet<PlaceableNode>(); for (int i = 0; i < edges.size(); ++i) { EdgeBase e = edges.get(i); related.add(e.target()); e.setIdSuffix("::" + edgeIds.get(i)); } if (related.size() > 1) this.setStrategy(new StrategyInBetween(this, related.toArray(new PlaceableNode[0]), 0, 0)); } /** * Draws a diamond with an underlined label in the object diagram. */ @Override public void onDraw( Graphics2D g ) { if ( isSelected() ) { g.setColor( fOpt.getNODE_SELECTED_COLOR() ); } else { g.setColor( fOpt.getDIAMONDNODE_COLOR() ); } Shape ourShape = getShape(); g.fill( ourShape ); g.setColor( fOpt.getDIAMONDNODE_FRAME_COLOR() ); g.draw( ourShape ); if ( isSelected() ) { g.setColor( fOpt.getEDGE_SELECTED_COLOR() ); } else { g.setColor( fOpt.getEDGE_LABEL_COLOR() ); } if ( fAssocName != null && fOpt.isShowAssocNames() ) { g.setColor( fOpt.getEDGE_LABEL_COLOR() ); fAssocName.draw( g ); } g.setColor( fOpt.getDIAMONDNODE_COLOR() ); } @Override public Shape getShape() { Path2D.Double path = new Path2D.Double(); Rectangle2D bounds = getBounds(); path.moveTo(bounds.getX(), bounds.getCenterY()); path.lineTo(bounds.getCenterX(), bounds.getMinY()); path.lineTo(bounds.getMaxX(), bounds.getCenterY()); path.lineTo(bounds.getCenterX(), bounds.getMaxY()); path.closePath(); return path; } @Override public void setDraggedPosition(double deltaX, double deltaY) { // The first dragging of a diamond node switches its // positioning strategy to "fixed". if (this.getStrategy() instanceof StrategyInBetween) this.setStrategy(StrategyFixed.instance); super.setDraggedPosition(deltaX, deltaY); } public void resetPositionStrategy(){ Set<PlaceableNode> related = new HashSet<PlaceableNode>(); for (EdgeBase edgeBase : fHalfEdges) { related.add(edgeBase.target()); } if(related.size() > 1){ this.setStrategy(new StrategyInBetween(this, related.toArray(new PlaceableNode[0]), 0, 0)); } } @Override public PlaceableNode getRelatedNode(double x, double y) { if (fAssocName != null && fAssocName.occupies(x, y)) return fAssocName; return super.getRelatedNode(x, y); } @Override public void doCalculateSize( Graphics2D g ) { setExactWidth(40); setExactHeight(20); if (fAssocName != null) fAssocName.calculateSize(g); } @Override public String getStoreType() { return "DiamondNode"; } @Override public String getStoreKind() { return (fLink != null ? "link" : "association"); } @Override public void storeAdditionalInfo( PersistHelper helper, Element nodeElement, boolean hidden ) { for(String nodeName : fConnectedNodes ) { helper.appendChild( nodeElement, LayoutTags.CON_NODE, nodeName); } if (fAssocName != null) { fAssocName.storePlacementInfo( helper, nodeElement, hidden ); } if ( fHalfEdges != null ) { for (EdgeBase e : fHalfEdges) { e.storePlacementInfo( helper, nodeElement, hidden); } } } @Override public void restoreAdditionalInfo( PersistHelper helper, int version ) { // Restore association name if (fAssocName != null) { helper.toFirstChild(LayoutTags.EDGEPROPERTY); fAssocName.restorePlacementInfo(helper, version); helper.toParent(); } if ( fHalfEdges != null ) { for (EdgeBase e : fHalfEdges) { if (e instanceof AssociationOrLinkPartEdge) { AssociationOrLinkPartEdge partEdge = (AssociationOrLinkPartEdge)e; String xpathExpr = "./edge[@type='" + LayoutTags.HALFEDGE + "' and name='" + partEdge.getName() + "']"; helper.getNav().push(); AutoPilot ap = new AutoPilot(helper.getNav()); try { ap.selectXPath(xpathExpr); try { if (ap.evalXPath() != -1) e.restorePlacementInfo(helper, version); } catch (XPathEvalException ex) { helper.getLog().append(ex.getMessage()); } catch (NavException ex) { helper.getLog().append(ex.getMessage()); } } catch (XPathParseException ex) { helper.getLog().append(ex.getMessage()); } finally { helper.getNav().pop(); } } } } } }
classicwuhao/maxuse
src/gui/org/tzi/use/gui/views/diagrams/elements/DiamondNode.java
Java
gpl-2.0
8,728
// pinout #define SCLK_PIN 13 #define SIN_PIN 14 #define PCLK_PIN 15 // only to selected board, others are high uint8_t update_required=0; uint16_t switches[48]; void setup() { pinMode(SCLK_PIN, OUTPUT); pinMode(SIN_PIN, OUTPUT); digitalWrite(PCLK_PIN, HIGH); pinMode(PCLK_PIN, OUTPUT); } void loop() { } /////////////////////////////////////////////////////////////////////// // // AD75019 Switch Matrix Control // /////////////////////////////////////////////////////////////////////// // connect a Teensy pin (0 to 48) to a bus signal (0 to 15) void connect(uint8_t pin, uint8_t signal) { uint8_t chip; if (pin < 16) chip = 32; else if (pin < 32) chip = 16; else if (pin < 48) chip = 0; else return; if (signal >= 16) return; switches[chip + (15 - signal)] |= (1 << (pin & 15)); update_required = 1; } void disconnectAll(void) { memset(switches, 0, sizeof(switches)); update_required = 1; } void update(void) { uint8_t i; uint16_t n, mask; for (i=0; i < 48; i++) { n = switches[i]; for (mask = 0x8000; mask; mask >>= 1) { digitalWrite(SIN_PIN, (n & mask) ? HIGH : LOW); // 20ns setup required asm("nop"); asm("nop"); digitalWrite(SCLK_PIN, HIGH); asm("nop"); // sclk pulse width, 100 ns minimum asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); digitalWrite(SCLK_PIN, LOW); asm("nop"); // 40ns hold time required } } asm("nop"); // 65ns setup required asm("nop"); asm("nop"); asm("nop"); digitalWrite(PCLK_PIN, LOW); asm("nop"); // pclk pulse width 65ns minimum asm("nop"); asm("nop"); asm("nop"); digitalWrite(PCLK_PIN, HIGH); update_required = 0; } /* The first bit loaded via SIN, the serial data input, controls the switch at the intersection of row Y15 and column X15. The next bits control the remaining columns (down to X0) of row Y15, and are followed by the bits for row Y14, and so on down to the data for the switch at the intersec- tion of row Y0 and column X0. The shift register is dynamic, so there is a minimum clock rate, specified as 20 kHz. Teensy pins connected to X0-X15 - signal are Y0-Y15 */
gratefulfrog/ArduGuitar
Ardu3/DraftDevt/Arduino/DorkboxCode.cpp
C++
gpl-2.0
2,118
<?php /** * MailChimp notifier notifications * * A set of functions to send notifications * * @author rtweedie * @package nth mailchimp * @since 1.2 * @version 1.5 */ include_once( NTHMAILCHIMPPATH . 'classes/nth-mailchimp-core.php' ); include_once( NTHMAILCHIMPPATH . 'vendor/mailchimp-api/src/Mailchimp.php' ); class NthMailChimpNotification{ static $test_mode = false; // The notifications will only static $test_domains = array( '.dev', '.local', 'drewlondon', 'duefriday' ); static function new_post_notification( $post, $post_id = null ){ self::send_notification($post, $post_id ); } static function post_notification( $post_id, $post = null ){ self::send_notification($post, $post_id ); } /** * Check if it is ok to send the notification * * @param integer $post_id The post ID * @param object WP_post $post The WP Post * * @return false || integer */ static function ok_to_send_notifications( $post_id, $post ) { $send_notification = $notification_sent = null; // We only want to send the notifications for blog posts being published. // Other content types don't need to send notifications. if( 'post' !== $post->post_type ){ return false; } if ( 'publish' !== $post->post_status ){ return false; } $notification_sent = get_post_meta( $post->ID, 'notification_sent', true ); $send_notification = get_post_meta( $post->ID, '_send_notification', true ); if ( $notification_sent ){ return false; } if ( ! $send_notification ){ return false; } $current_user = wp_get_current_user(); $ignore_user_updates = false; $ignore_user_updates = apply_filters( 'nth_mailchimp_ignore_user_updates', $current_user->data->ID ); if ( true == $ignore_user_updates ){ self::$test_mode = true; return 2; } $domain = $_SERVER['HTTP_HOST']; $test_domains = self::$test_domains; $test_domains = apply_filters( 'nth_mailchimp_test_domains', $test_domains ); foreach( $test_domains AS $the_domain ) { if ( strpos( $domain, $the_domain ) !== false ){ self::$test_mode = true; return 3; } } // We've got this far, so let's send the notification return true; } static function send_notification( $post, $post_id = null ) { if ( ! $post_id ){ $post_id = isset( $_GET['post_id'] ) && !empty( $_GET['post_id'] )? (int)$_GET['post_id'] : 0; } if ( ! $post_id ){ $post_id = $post->ID; } $send_notification = self::ok_to_send_notifications( $post_id, $post ); if ( false == $send_notification ){ return false; } $content_sections = $notification_content = array(); $send_notification = $date_format = $test_mode = false; $the_post = get_post( $post_id ); // We don't want to bombard the users with notifications. $notification_sent = get_post_meta( $post_id, 'notification_sent', true ); if( $notification_sent ){ return false; } // We only want to send notifications if they option is selected $send_notification = get_post_meta( $post_id, '_send_notification', true ); if( 1 != $send_notification ){ return false; } $api_settings = NthMailChimpCore::get_settings('nthmc_api_key', true ); $settings = NthMailChimpCore::get_settings(null, true ); $enabled = isset( $settings['enabled'] ) && 1 == $settings['enabled']? true : false; if ( ! $enabled ) { return false; } if ( isset( $settings['api_token'] ) ){ $api_token = $settings['api_token'].'-'.$settings['api_dc']; } if ( isset( $api_settings['api_key'] ) ){ $api_token = $api_settings['api_key']; } $mailchimp = new Mailchimp( $api_token ); //$campaigns = $mailchimp->campaigns->getList(); $template = $mailchimp->templates->info( $settings['template_id'] ); $list = $mailchimp->lists->getList( array( 'list_id' => $settings['list_id'] ) ); $segments = $mailchimp->lists->segments( $settings['list_id'] ); if ( isset( $template['sections'] ) && !empty( $template['sections'] ) ){ $content_sections = $template['sections']; } $subject = NthMailChimpCore::process_tags( $settings['email_subject'], $the_post ); $html_content = NthMailChimpCore::process_tags( wpautop( $settings['email_content'] ), $the_post ); $text_content = NthMailChimpCore::process_tags( $settings['email_text'], $the_post ); $from_name = $list['data'][0]['default_from_name']; $from_email = $list['data'][0]['default_from_email']; $options = array( 'subject' => $subject, 'template_id' => $settings['template_id'], 'list_id' => $settings['list_id'], 'from_name' => $from_name, 'from_email' => $from_email, ); // Override the main section of the template with the HTML content. $content_sections['main'] = $html_content; $content_sections['std_content'] = $html_content; $content = array( 'html' => $html_content, 'text' => $text_content, 'sections' => $content_sections, ); $segment_opts = array( 'saved_segment_id' => $settings['segment_id'], ); // Let's create the campaign in MailChimp $result = $mailchimp->campaigns->create( 'regular', $options, $content, $segment_opts ); $campaign_id = $result['id']; // Let's save the contents of the notification for future reference $date = new DateTime(); $notification_content = array(); $notification_content['subject'] = $subject; $notification_content['html'] = $html_content; $notification_content['text'] = $text_content; $notification_content['segment_id'] = $settings['segment_id']; $notification_content['date'] = $date->getTimestamp(); $notification_content['campaign_id'] = $result['id']; if ( isset( $settings['test_mode'] ) && 1 == $settings['test_mode'] ){ $test_mode = true; } if ( isset( self::$test_mode ) && true == self::$test_mode ){ $test_mode = true; } // Now we have created a campaign, should we send it? if ( true == $test_mode ){ $email_addresses = explode(',', $settings['test_emails'] ); foreach( $email_addresses AS $key => $address ){ $email_addresses[$key] = str_replace( '&amp;', '&', trim( $address) ); } $test_result = $mailchimp->campaigns->sendTest( $campaign_id, $email_addresses ); return true; } else { $mailchimp->campaigns->send( $campaign_id ); update_post_meta( $post_id, 'notification_sent', true ); update_post_meta( $post_id, 'notification_sent_at', $date->getTimestamp() ); update_post_meta( $post_id, 'notification_content', $notification_content ); return true; } } /** * Filter to test if we should send notifications depending upon the current domain * * @param array $domains * * @return array */ static function test_domains( $domains ){ return $domains; } }
digitales/nth-mailchimp-notifier
classes/nth-mailchimp-notification.php
PHP
gpl-2.0
7,098
(function( window, undefined ) { kendo.cultures["ur-PK"] = { name: "ur-PK", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$n-","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "Rs" } }, calendars: { standard: { days: { names: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"], namesAbbr: ["اتوار","پير","منگل","بدھ","جمعرات","جمعه","هفته"], namesShort: ["ا","پ","م","ب","ج","ج","ه"] }, months: { names: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"], namesAbbr: ["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","ستمبر","اکتوبر","نومبر","دسمبر"] }, AM: ["AM","am","AM"], PM: ["PM","pm","PM"], patterns: { d: "dd/MM/yyyy", D: "dd MMMM, yyyy", F: "dd MMMM, yyyy h:mm:ss tt", g: "dd/MM/yyyy h:mm tt", G: "dd/MM/yyyy h:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this);
cuongnd/test_pro
media/kendo-ui-core-master/src/cultures/kendo.culture.ur-PK.js
JavaScript
gpl-2.0
2,263
<?php namespace Icinga\Module\Director\Dashboard\Dashlet; use Exception; use Icinga\Module\Director\Objects\SyncRule; class SyncDashlet extends Dashlet { protected $icon = 'flapping'; public function getTitle() { return $this->translate('Synchronize'); } public function listCssClasses() { try { return $this->fetchStateClass(); } catch (Exception $e) { return 'state-critical'; } } public function getSummary() { return $this->translate( 'Define how imported data should be synchronized with Icinga' ); } protected function fetchStateClass() { $syncs = SyncRule::loadAll($this->db); if (count($syncs) > 0) { $state = 'state-ok'; } else { $state = null; } foreach ($syncs as $sync) { if ($sync->sync_state !== 'in-sync') { if ($sync->sync_state === 'failing') { $state = 'state-critical'; break; } else { $state = 'state-warning'; } } } return $state; } public function getUrl() { return 'director/list/syncrule'; } public function listRequiredPermissions() { return array('director/admin'); } }
tobiasvdk/icingaweb2-module-director
library/Director/Dashboard/Dashlet/SyncDashlet.php
PHP
gpl-2.0
1,395
/* A RapidNet application. Generated by RapidNet compiler. */ #include "pathvector2.h" #include <cstdlib> #include "ns3/nstime.h" #include "ns3/simulator.h" #include "ns3/type-ids.h" #include "ns3/rapidnet-types.h" #include "ns3/rapidnet-utils.h" #include "ns3/assignor.h" #include "ns3/selector.h" #include "ns3/rapidnet-functions.h" using namespace std; using namespace ns3; using namespace ns3::rapidnet; using namespace ns3::rapidnet::pathvector2; const string Pathvector2::BESTPATH = "bestPath"; const string Pathvector2::LINK = "link"; const string Pathvector2::PATH = "path"; const string Pathvector2::PATHDELETE = "pathDelete"; const string Pathvector2::R2LOCAL1R2LINKZSEND = "r2Local1r2linkZsend"; const string Pathvector2::R2LOCAL2PATHSEND = "r2Local2pathsend"; const string Pathvector2::R2LINKZ = "r2linkZ"; NS_LOG_COMPONENT_DEFINE ("Pathvector2"); NS_OBJECT_ENSURE_REGISTERED (Pathvector2); TypeId Pathvector2::GetTypeId (void) { static TypeId tid = TypeId ("ns3::rapidnet::pathvector2::Pathvector2") .SetParent<Discovery> () .AddConstructor<Pathvector2> () ; return tid; } Pathvector2::Pathvector2() { NS_LOG_FUNCTION_NOARGS (); } Pathvector2::~Pathvector2() { NS_LOG_FUNCTION_NOARGS (); } void Pathvector2::DoDispose (void) { NS_LOG_FUNCTION_NOARGS (); Discovery::DoDispose (); } void Pathvector2::StartApplication (void) { NS_LOG_FUNCTION_NOARGS (); Discovery::StartApplication (); RAPIDNET_LOG_INFO("Pathvector2 Application Started"); } void Pathvector2::StopApplication () { NS_LOG_FUNCTION_NOARGS (); Discovery::StopApplication (); RAPIDNET_LOG_INFO("Pathvector2 Application Stopped"); } void Pathvector2::InitDatabase () { //Discovery::InitDatabase (); AddRelationWithKeys (BESTPATH, attrdeflist ( attrdef ("bestPath_attr2", IPV4))); AddRelationWithKeys (LINK, attrdeflist ( attrdef ("link_attr1", IPV4), attrdef ("link_attr2", IPV4)), Seconds (11)); AddRelationWithKeys (PATH, attrdeflist ( attrdef ("path_attr4", LIST))); AddRelationWithKeys (R2LINKZ, attrdeflist ( attrdef ("r2linkZ_attr1", IPV4), attrdef ("r2linkZ_attr2", IPV4))); m_aggr_bestpathMinC = AggrMin::New (BESTPATH, this, attrdeflist ( attrdeftype ("bestPath_attr1", ANYTYPE), attrdeftype ("bestPath_attr2", ANYTYPE), attrdeftype ("bestPath_attr3", ANYTYPE), attrdeftype ("bestPath_attr4", ANYTYPE)), 3); } void Pathvector2::DemuxRecv (Ptr<Tuple> tuple) { Discovery::DemuxRecv (tuple); if (IsInsertEvent (tuple, LINK)) { R1Eca0Ins (tuple); } if (IsRefreshEvent (tuple, LINK)) { R1Eca0Ref (tuple); } if (IsRecvEvent (tuple, R2LOCAL1R2LINKZSEND)) { R2Local1Eca0RemoteIns (tuple); } if (IsInsertEvent (tuple, LINK)) { R2Local1Eca0Ins (tuple); } if (IsRefreshEvent (tuple, LINK)) { R2Local1Eca0Ref (tuple); } if (IsRecvEvent (tuple, R2LOCAL2PATHSEND)) { R2Local2Eca0RemoteIns (tuple); } if (IsRecvEvent (tuple, PATHDELETE)) { R2Local2Eca0RemoteDel (tuple); } if (IsInsertEvent (tuple, R2LINKZ)) { R2Local2Eca0Ins (tuple); } if (IsDeleteEvent (tuple, R2LINKZ)) { R2Local2Eca0Del (tuple); } if (IsInsertEvent (tuple, BESTPATH)) { R2Local2Eca1Ins (tuple); } if (IsDeleteEvent (tuple, BESTPATH)) { R2Local2Eca1Del (tuple); } if (IsInsertEvent (tuple, PATH)) { R3eca (tuple); } if (IsDeleteEvent (tuple, PATH)) { R3eca2 (tuple); } } void Pathvector2::R1Eca0Ins (Ptr<Tuple> link) { RAPIDNET_LOG_INFO ("R1Eca0Ins triggered"); Ptr<Tuple> result = link; result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("link_attr1")))); result->Assign (Assignor::New ("P2", FAppend::New ( VarExpr::New ("link_attr2")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("P2")))); result = result->Project ( PATH, strlist ("link_attr1", "link_attr2", "link_attr3", "P"), strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4")); Insert (result); } void Pathvector2::R1Eca0Ref (Ptr<Tuple> link) { RAPIDNET_LOG_INFO ("R1Eca0Ref triggered"); Ptr<Tuple> result = link; result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("link_attr1")))); result->Assign (Assignor::New ("P2", FAppend::New ( VarExpr::New ("link_attr2")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("P2")))); result = result->Project ( PATH, strlist ("link_attr1", "link_attr2", "link_attr3", "P"), strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4")); Insert (result); } void Pathvector2::R2Local1Eca0RemoteIns (Ptr<Tuple> r2Local1r2linkZsend) { RAPIDNET_LOG_INFO ("R2Local1Eca0RemoteIns triggered"); Ptr<Tuple> result = r2Local1r2linkZsend; result = result->Project ( R2LINKZ, strlist ("r2Local1r2linkZsend_attr1", "r2Local1r2linkZsend_attr2", "r2Local1r2linkZsend_attr3"), strlist ("r2linkZ_attr1", "r2linkZ_attr2", "r2linkZ_attr3")); Insert (result); } void Pathvector2::R2Local1Eca0Ins (Ptr<Tuple> link) { RAPIDNET_LOG_INFO ("R2Local1Eca0Ins triggered"); Ptr<Tuple> result = link; result = result->Project ( R2LOCAL1R2LINKZSEND, strlist ("link_attr1", "link_attr2", "link_attr3", "link_attr2"), strlist ("r2Local1r2linkZsend_attr1", "r2Local1r2linkZsend_attr2", "r2Local1r2linkZsend_attr3", RN_DEST)); Send (result); } void Pathvector2::R2Local1Eca0Ref (Ptr<Tuple> link) { RAPIDNET_LOG_INFO ("R2Local1Eca0Ref triggered"); Ptr<Tuple> result = link; result = result->Project ( R2LOCAL1R2LINKZSEND, strlist ("link_attr1", "link_attr2", "link_attr3", "link_attr2"), strlist ("r2Local1r2linkZsend_attr1", "r2Local1r2linkZsend_attr2", "r2Local1r2linkZsend_attr3", RN_DEST)); Send (result); } void Pathvector2::R2Local2Eca0RemoteIns (Ptr<Tuple> r2Local2pathsend) { RAPIDNET_LOG_INFO ("R2Local2Eca0RemoteIns triggered"); Ptr<Tuple> result = r2Local2pathsend; result = result->Project ( PATH, strlist ("r2Local2pathsend_attr1", "r2Local2pathsend_attr2", "r2Local2pathsend_attr3", "r2Local2pathsend_attr4"), strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4")); Insert (result); } void Pathvector2::R2Local2Eca0RemoteDel (Ptr<Tuple> pathDelete) { RAPIDNET_LOG_INFO ("R2Local2Eca0RemoteDel triggered"); Ptr<Tuple> result = pathDelete; result = result->Project ( PATH, strlist ("pathDelete_attr1", "pathDelete_attr2", "pathDelete_attr3", "pathDelete_attr4"), strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4")); Delete (result); } void Pathvector2::R2Local2Eca0Ins (Ptr<Tuple> r2linkZ) { RAPIDNET_LOG_INFO ("R2Local2Eca0Ins triggered"); Ptr<RelationBase> result; result = GetRelation (BESTPATH)->Join ( r2linkZ, strlist ("bestPath_attr1"), strlist ("r2linkZ_attr2")); result->Assign (Assignor::New ("C", Operation::New (RN_PLUS, VarExpr::New ("r2linkZ_attr3"), VarExpr::New ("bestPath_attr3")))); result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("r2linkZ_attr1")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("bestPath_attr4")))); result = result->Select (Selector::New ( Operation::New (RN_EQ, FMember::New ( VarExpr::New ("bestPath_attr4"), VarExpr::New ("r2linkZ_attr1")), ValueExpr::New (Int32Value::New (0))))); result = result->Project ( R2LOCAL2PATHSEND, strlist ("r2linkZ_attr1", "bestPath_attr2", "C", "P", "r2linkZ_attr1"), strlist ("r2Local2pathsend_attr1", "r2Local2pathsend_attr2", "r2Local2pathsend_attr3", "r2Local2pathsend_attr4", RN_DEST)); Send (result); } void Pathvector2::R2Local2Eca0Del (Ptr<Tuple> r2linkZ) { RAPIDNET_LOG_INFO ("R2Local2Eca0Del triggered"); Ptr<RelationBase> result; result = GetRelation (BESTPATH)->Join ( r2linkZ, strlist ("bestPath_attr1"), strlist ("r2linkZ_attr2")); result->Assign (Assignor::New ("C", Operation::New (RN_PLUS, VarExpr::New ("r2linkZ_attr3"), VarExpr::New ("bestPath_attr3")))); result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("r2linkZ_attr1")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("bestPath_attr4")))); result = result->Select (Selector::New ( Operation::New (RN_EQ, FMember::New ( VarExpr::New ("bestPath_attr4"), VarExpr::New ("r2linkZ_attr1")), ValueExpr::New (Int32Value::New (0))))); result = result->Project ( PATHDELETE, strlist ("r2linkZ_attr1", "bestPath_attr2", "C", "P", "r2linkZ_attr1"), strlist ("pathDelete_attr1", "pathDelete_attr2", "pathDelete_attr3", "pathDelete_attr4", RN_DEST)); Send (result); } void Pathvector2::R2Local2Eca1Ins (Ptr<Tuple> bestPath) { RAPIDNET_LOG_INFO ("R2Local2Eca1Ins triggered"); Ptr<RelationBase> result; result = GetRelation (R2LINKZ)->Join ( bestPath, strlist ("r2linkZ_attr2"), strlist ("bestPath_attr1")); result->Assign (Assignor::New ("C", Operation::New (RN_PLUS, VarExpr::New ("r2linkZ_attr3"), VarExpr::New ("bestPath_attr3")))); result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("r2linkZ_attr1")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("bestPath_attr4")))); result = result->Select (Selector::New ( Operation::New (RN_EQ, FMember::New ( VarExpr::New ("bestPath_attr4"), VarExpr::New ("r2linkZ_attr1")), ValueExpr::New (Int32Value::New (0))))); result = result->Project ( R2LOCAL2PATHSEND, strlist ("r2linkZ_attr1", "bestPath_attr2", "C", "P", "r2linkZ_attr1"), strlist ("r2Local2pathsend_attr1", "r2Local2pathsend_attr2", "r2Local2pathsend_attr3", "r2Local2pathsend_attr4", RN_DEST)); Send (result); } void Pathvector2::R2Local2Eca1Del (Ptr<Tuple> bestPath) { RAPIDNET_LOG_INFO ("R2Local2Eca1Del triggered"); Ptr<RelationBase> result; result = GetRelation (R2LINKZ)->Join ( bestPath, strlist ("r2linkZ_attr2"), strlist ("bestPath_attr1")); result->Assign (Assignor::New ("C", Operation::New (RN_PLUS, VarExpr::New ("r2linkZ_attr3"), VarExpr::New ("bestPath_attr3")))); result->Assign (Assignor::New ("P1", FAppend::New ( VarExpr::New ("r2linkZ_attr1")))); result->Assign (Assignor::New ("P", FConcat::New ( VarExpr::New ("P1"), VarExpr::New ("bestPath_attr4")))); result = result->Select (Selector::New ( Operation::New (RN_EQ, FMember::New ( VarExpr::New ("bestPath_attr4"), VarExpr::New ("r2linkZ_attr1")), ValueExpr::New (Int32Value::New (0))))); result = result->Project ( PATHDELETE, strlist ("r2linkZ_attr1", "bestPath_attr2", "C", "P", "r2linkZ_attr1"), strlist ("pathDelete_attr1", "pathDelete_attr2", "pathDelete_attr3", "pathDelete_attr4", RN_DEST)); Send (result); } void Pathvector2::R3eca (Ptr<Tuple> path) { RAPIDNET_LOG_INFO ("R3eca triggered"); Ptr<Tuple> result = path; result = result->Project ( BESTPATH, strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4"), strlist ("bestPath_attr1", "bestPath_attr2", "bestPath_attr3", "bestPath_attr4")); m_aggr_bestpathMinC->Insert (result); } void Pathvector2::R3eca2 (Ptr<Tuple> path) { RAPIDNET_LOG_INFO ("R3eca2 triggered"); Ptr<Tuple> result = path; result = result->Project ( BESTPATH, strlist ("path_attr1", "path_attr2", "path_attr3", "path_attr4"), strlist ("bestPath_attr1", "bestPath_attr2", "bestPath_attr3", "bestPath_attr4")); m_aggr_bestpathMinC->Delete (result); }
AliZafar120/NetworkStimulatorSPl3
src/applications/pathvector2/pathvector2.cc
C++
gpl-2.0
12,491
package android.os; import android.os.Looper; import android.os.Message; import android.os.SystemClock; import android.util.Log; import android.util.Printer; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Date; import java.text.SimpleDateFormat; /** * @hide */ public class MessageLogger implements Printer { private static final String TAG = "MessageLogger"; private static boolean mEnableLooperLog; private static LinkedList mMessageHistoryRecord = new LinkedList(); private static LinkedList mLongTimeMessageHistoryRecord = new LinkedList(); private static LinkedList mMessageTimeRecord = new LinkedList(); private static LinkedList mNonSleepMessageTimeRecord = new LinkedList(); private static LinkedList mNonSleepLongTimeRecord = new LinkedList(); private static LinkedList mElapsedLongTimeRecord = new LinkedList(); final static int MESSAGE_SIZE = 20 * 2;// One for dispatching, one for // finished final static int LONGER_TIME_MESSAGE_SIZE = 40 * 2;// One for dispatching, one for // finished final static int LONGER_TIME = 200; //ms final static int FLUSHOUT_SIZE = 1024*2; //ms private static String mLastRecord = null; private static long mLastRecordKernelTime; //Unir: Milli private static long mNonSleepLastRecordKernelTime; //Unit: Milli private static long mLastRecordDateTime; //Unir: Micro private static int mState = 0; private static long mMsgCnt = 0; private static String messageInfo = ""; public MessageLogger() { } public long wallStart; //Unit:Micro public long wallTime; //Unit:Micro public long nonSleepWallStart; //Unit:Milli public long nonSleepWallTime; //Unit:Milli public static void addTimeToList(LinkedList mList, long startTime, long durationTime) { mList.add(startTime); mList.add(durationTime); return; } public void println(String s) { synchronized (mMessageHistoryRecord) { mState++; int size = mMessageHistoryRecord.size(); if (size > MESSAGE_SIZE) { mMessageHistoryRecord.removeFirst(); mMessageTimeRecord.removeFirst(); mNonSleepMessageTimeRecord.removeFirst(); } s = "Msg#:" + mMsgCnt + " " + s; mMsgCnt++; mMessageHistoryRecord.add(s); mLastRecordKernelTime = SystemClock.elapsedRealtime(); mNonSleepLastRecordKernelTime = SystemClock.uptimeMillis(); mLastRecordDateTime = SystemClock.currentTimeMicro(); if( mState%2 == 0) { mState = 0; wallTime = SystemClock.currentTimeMicro() - wallStart; nonSleepWallTime = SystemClock.uptimeMillis() - nonSleepWallStart; addTimeToList(mMessageTimeRecord, wallStart, wallTime); addTimeToList(mNonSleepMessageTimeRecord, nonSleepWallStart, nonSleepWallTime); if(nonSleepWallTime >= LONGER_TIME) { if(mLongTimeMessageHistoryRecord.size() >= LONGER_TIME_MESSAGE_SIZE) { mLongTimeMessageHistoryRecord.removeFirst(); for(int i = 0; i < 2 ;i++) { mNonSleepLongTimeRecord.removeFirst(); mElapsedLongTimeRecord.removeFirst(); } } mLongTimeMessageHistoryRecord.add(s); addTimeToList(mNonSleepLongTimeRecord,wallStart,nonSleepWallTime); addTimeToList(mElapsedLongTimeRecord,wallStart,wallTime); } } else { wallStart = SystemClock.currentTimeMicro(); nonSleepWallStart = SystemClock.uptimeMillis(); /* Test Longer History Code. */ /* if(mMsgCnt%3 == 0 && nonSleepWallStart > 2*LONGER_TIME) { nonSleepWallStart -= 2*LONGER_TIME; } */ /* Test Longer History Code ================================. */ } if (mEnableLooperLog) { if (s.contains(">")) { Log.d(TAG,"Debugging_MessageLogger: " + s + " start"); } else { Log.d(TAG,"Debugging_MessageLogger: " + s + " spent " + wallTime / 1000 + "ms"); } } } } private static int sizeToIndex( int size) { return --size; } private static void flushedOrNot(StringBuilder sb, boolean bl ) { if(sb.length() > FLUSHOUT_SIZE && !bl) { //Log.d(TAG, "After Flushed, Current Size Is:" + sb.length() + ",bool" + bl); sb.append("***Flushing, Current Size Is:" + sb.length() + ",bool" + bl +"***TAIL\n"); bl = true; /// M: Add message history/queue to _exp_main.txt messageInfo = messageInfo + sb.toString(); Log.d(TAG, sb.toString()); //Why New the one, not Clear the one? -> http://stackoverflow.com/questions/5192512/how-to-clear-empty-java-stringbuilder //Performance is better for new object allocation. //sb = new StringBuilder(1024); sb.delete(0,sb.length()); } else if(bl) { bl = false; } /* Test Longer History Code. */ /* sb.append("***Current Size Is:" + sb.length() + "***\n"); */ /* Test Longer History Code. ================ */ } /* Test Longer History Code. */ /* private static int DumpRound = 0; */ /* Test Longer History Code. ================ */ public static String dump() { synchronized (mMessageHistoryRecord) { StringBuilder history = new StringBuilder(1024); /* Test Longer History Code. */ /* history.append("=== DumpRound:" + DumpRound + " ===\n"); DumpRound++; */ /* Test Longer History Code. ================ */ history.append("MSG HISTORY IN MAIN THREAD:\n"); history.append("Current kernel time : " + SystemClock.elapsedRealtime() + "ms\n"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //State = 1 means the current dispatching message has not been finished int sizeForMsgRecord = mMessageHistoryRecord == null ? 0 : mMessageHistoryRecord.size(); if (mState == 1) { Date date = new Date((long)mLastRecordDateTime/1000); long spent = SystemClock.elapsedRealtime() - mLastRecordKernelTime; long nonSleepSpent = SystemClock.uptimeMillis()- mNonSleepLastRecordKernelTime; history.append("Last record : " + mMessageHistoryRecord.getLast()); history.append("\n"); history.append("Last record dispatching elapsedTime:" + spent + " ms/upTime:"+ nonSleepSpent +" ms\n"); history.append("Last record dispatching time : " + simpleDateFormat.format(date)); history.append("\n"); sizeForMsgRecord --; } String msg = null; Long time = null; Long nonSleepTime = null; StringBuilder longerHistory = new StringBuilder(1024); boolean flushed = false; for (;sizeForMsgRecord > 0; sizeForMsgRecord--) { msg = (String)mMessageHistoryRecord.get(sizeToIndex(sizeForMsgRecord)); time = (Long)mMessageTimeRecord.get(sizeToIndex(sizeForMsgRecord)); nonSleepTime = (Long)mNonSleepMessageTimeRecord.get(sizeToIndex(sizeForMsgRecord)); if (msg.contains(">")) { Date date = new Date((long)time.longValue()/1000); history.append(msg + " from " + simpleDateFormat.format(date)); history.append("\n"); } else { history.append(msg + " elapsedTime:" + time/1000 + " ms/upTime:" + nonSleepTime +" ms"); history.append("\n"); } flushedOrNot(history, flushed); } if(!flushed) { /// M: Add message history/queue to _exp_main.txt messageInfo = messageInfo + history.toString(); Log.d(TAG, history.toString()); } /*Dump for LongerTimeMessageRecord*/ flushed = false; longerHistory.append("=== LONGER MSG HISTORY IN MAIN THREAD ===\n"); sizeForMsgRecord = mLongTimeMessageHistoryRecord.size(); int indexForTimeRecord = mNonSleepLongTimeRecord.size() - 1; for ( ;sizeForMsgRecord > 0; sizeForMsgRecord--, indexForTimeRecord-=2) { msg = (String)mLongTimeMessageHistoryRecord.get(sizeToIndex(sizeForMsgRecord)); nonSleepTime = (Long) mNonSleepLongTimeRecord.get(indexForTimeRecord); time = (Long) mNonSleepLongTimeRecord.get(indexForTimeRecord-1); Date date = new Date((long)time.longValue()/1000); longerHistory.append(msg + " from " + simpleDateFormat.format(date) + " elapsedTime:"+ (((Long)(mElapsedLongTimeRecord.get(indexForTimeRecord))).longValue()/1000)+" ms/upTime:" + nonSleepTime +"ms"); longerHistory.append("\n"); flushedOrNot(longerHistory, flushed); } if(!flushed) { /// M: Add message history/queue to _exp_main.txt messageInfo = messageInfo + longerHistory.toString(); Log.d(TAG, longerHistory.toString()); } // Dump message queue } /// M: Add message history/queue to _exp_main.txt String retMessageInfo = messageInfo + Looper.getMainLooper().getQueue().dumpMessageQueue(); messageInfo = ""; return retMessageInfo; } }
rex-xxx/mt6572_x201
mediatek/frameworks-ext/base/core/java/android/os/MessageLogger.java
Java
gpl-2.0
10,671
<?php declare(strict_types=1); /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ namespace TYPO3\CMS\Backend\Controller\ContentElement; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use TYPO3\CMS\Backend\Template\ModuleTemplate; use TYPO3\CMS\Backend\Template\ModuleTemplateFactory; use TYPO3\CMS\Backend\Tree\View\ContentMovingPagePositionMap; use TYPO3\CMS\Backend\Tree\View\PageMovingPagePositionMap; use TYPO3\CMS\Backend\Utility\BackendUtility; use TYPO3\CMS\Core\Authentication\BackendUserAuthentication; use TYPO3\CMS\Core\Http\HtmlResponse; use TYPO3\CMS\Core\Imaging\Icon; use TYPO3\CMS\Core\Imaging\IconFactory; use TYPO3\CMS\Core\Localization\LanguageService; use TYPO3\CMS\Core\Page\PageRenderer; use TYPO3\CMS\Core\Type\Bitmask\Permission; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Fluid\View\StandaloneView; /** * Script Class for rendering the move-element wizard display * @internal This class is a specific Backend controller implementation and is not considered part of the Public TYPO3 API. */ class MoveElementController { protected int $sys_language = 0; protected int $page_id = 0; protected string $table = ''; protected string $R_URI = ''; protected int $moveUid = 0; protected int $makeCopy = 0; protected string $perms_clause = ''; protected ?ModuleTemplate $moduleTemplate = null; protected IconFactory $iconFactory; protected PageRenderer $pageRenderer; protected ModuleTemplateFactory $moduleTemplateFactory; public function __construct( IconFactory $iconFactory, PageRenderer $pageRenderer, ModuleTemplateFactory $moduleTemplateFactory ) { $this->iconFactory = $iconFactory; $this->pageRenderer = $pageRenderer; $this->moduleTemplateFactory = $moduleTemplateFactory; } public function mainAction(ServerRequestInterface $request): ResponseInterface { $this->moduleTemplate = $this->moduleTemplateFactory->create($request); $parsedBody = $request->getParsedBody(); $queryParams = $request->getQueryParams(); $this->sys_language = (int)($parsedBody['sys_language'] ?? $queryParams['sys_language'] ?? 0); $this->page_id = (int)($parsedBody['uid'] ?? $queryParams['uid'] ?? 0); $this->table = (string)($parsedBody['table'] ?? $queryParams['table'] ?? ''); $this->R_URI = GeneralUtility::sanitizeLocalUrl($parsedBody['returnUrl'] ?? $queryParams['returnUrl'] ?? ''); $this->moveUid = (int)(($parsedBody['moveUid'] ?? $queryParams['moveUid'] ?? false) ?: $this->page_id); $this->makeCopy = (int)($parsedBody['makeCopy'] ?? $queryParams['makeCopy'] ?? 0); // Select-pages where clause for read-access $this->perms_clause = $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW); // Setting up the buttons and markers for docheader $this->getButtons(); // Build the <body> for the module $this->moduleTemplate->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:movingElement')); $this->moduleTemplate->setContent($this->renderContent()); return new HtmlResponse($this->moduleTemplate->renderContent()); } /** * Creating the module output. */ protected function renderContent(): string { if (!$this->page_id) { return ''; } $assigns = []; $backendUser = $this->getBackendUser(); $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip'); // Get record for element: $elRow = BackendUtility::getRecordWSOL($this->table, $this->moveUid); // Headerline: Icon, record title: $assigns['table'] = $this->table; $assigns['elRow'] = $elRow; $assigns['recordTooltip'] = BackendUtility::getRecordToolTip($elRow, $this->table); $assigns['recordTitle'] = BackendUtility::getRecordTitle($this->table, $elRow, true); // Make-copy checkbox (clicking this will reload the page with the GET var makeCopy set differently): $assigns['makeCopyChecked'] = (bool)$this->makeCopy; $assigns['makeCopyUrl'] = GeneralUtility::linkThisScript(['makeCopy' => !$this->makeCopy]); // Get page record (if accessible): if ($this->table !== 'pages' && $this->moveUid === $this->page_id) { $this->page_id = (int)$elRow['pid']; } $pageInfo = BackendUtility::readPageAccess($this->page_id, $this->perms_clause); $assigns['pageInfo'] = $pageInfo; if (is_array($pageInfo) && $backendUser->isInWebMount($pageInfo['pid'], $this->perms_clause)) { // Initialize the page position map: $pagePositionMap = GeneralUtility::makeInstance(PageMovingPagePositionMap::class); $pagePositionMap->moveOrCopy = $this->makeCopy ? 'copy' : 'move'; $pagePositionMap->moveUid = $this->moveUid; switch ($this->table) { case 'pages': // Print a "go-up" link IF there is a real parent page (and if the user has read-access to that page). if ($pageInfo['pid']) { $pidPageInfo = BackendUtility::readPageAccess($pageInfo['pid'], $this->perms_clause); if (is_array($pidPageInfo)) { if ($backendUser->isInWebMount($pidPageInfo['pid'], $this->perms_clause)) { $assigns['goUpUrl'] = GeneralUtility::linkThisScript([ 'uid' => (int)$pageInfo['pid'], 'moveUid' => $this->moveUid, ]); } else { $assigns['pidPageInfo'] = $pidPageInfo; } $assigns['pidRecordTitle'] = BackendUtility::getRecordTitle('pages', $pidPageInfo, true); } } // Create the position tree: $assigns['positionTree'] = $pagePositionMap->positionTree($this->page_id, $pageInfo, $this->perms_clause, $this->R_URI); break; case 'tt_content': // Initialize the content position map: $contentPositionMap = GeneralUtility::makeInstance(ContentMovingPagePositionMap::class); $contentPositionMap->copyMode = $this->makeCopy ? 'copy' : 'move'; $contentPositionMap->moveUid = $this->moveUid; $contentPositionMap->cur_sys_language = $this->sys_language; $contentPositionMap->R_URI = $this->R_URI; // Headerline for the parent page: Icon, record title: $assigns['ttContent']['recordTooltip'] = BackendUtility::getRecordToolTip($pageInfo); $assigns['ttContent']['recordTitle'] = BackendUtility::getRecordTitle('pages', $pageInfo, true); // Adding parent page-header and the content element columns from position-map: $assigns['contentElementColumns'] = $contentPositionMap->printContentElementColumns($this->page_id); // Print a "go-up" link IF there is a real parent page (and if the user has read-access to that page). if ($pageInfo['pid'] > 0) { $pidPageInfo = BackendUtility::readPageAccess($pageInfo['pid'], $this->perms_clause); if (is_array($pidPageInfo)) { if ($backendUser->isInWebMount($pidPageInfo['pid'], $this->perms_clause)) { $assigns['goUpUrl'] = GeneralUtility::linkThisScript([ 'uid' => (int)$pageInfo['pid'], 'moveUid' => $this->moveUid, ]); } else { $assigns['pidPageInfo'] = $pidPageInfo; } $assigns['pidRecordTitle'] = BackendUtility::getRecordTitle('pages', $pidPageInfo, true); } } // Create the position tree (for pages) without insert lines: $pagePositionMap->dontPrintPageInsertIcons = 1; $assigns['positionTree'] = $pagePositionMap->positionTree($this->page_id, $pageInfo, $this->perms_clause, $this->R_URI); } } // Rendering of the output via fluid $view = $this->initializeView(); $view->assignMultiple($assigns); return $view->render(); } protected function initializeView(): StandaloneView { $view = GeneralUtility::makeInstance(StandaloneView::class); $view->setTemplateRootPaths(['EXT:backend/Resources/Private/Templates']); $view->setPartialRootPaths(['EXT:backend/Resources/Private/Partials']); $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName( 'EXT:backend/Resources/Private/Templates/ContentElement/MoveElement.html' )); return $view; } /** * Create the panel of buttons for submitting the form or otherwise perform operations. */ protected function getButtons() { $buttonBar = $this->moduleTemplate->getDocHeaderComponent()->getButtonBar(); if ($this->page_id) { if ($this->table === 'pages') { $cshButton = $buttonBar->makeHelpButton() ->setModuleName('xMOD_csh_corebe') ->setFieldName('move_el_pages'); $buttonBar->addButton($cshButton); } elseif ($this->table === 'tt_content') { $cshButton = $buttonBar->makeHelpButton() ->setModuleName('xMOD_csh_corebe') ->setFieldName('move_el_cs'); $buttonBar->addButton($cshButton); } if ($this->R_URI) { $backButton = $buttonBar->makeLinkButton() ->setHref($this->R_URI) ->setShowLabelText(true) ->setTitle($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:goBack')) ->setIcon($this->iconFactory->getIcon('actions-view-go-back', Icon::SIZE_SMALL)); $buttonBar->addButton($backButton); } } } protected function getLanguageService(): LanguageService { return $GLOBALS['LANG']; } protected function getBackendUser(): BackendUserAuthentication { return $GLOBALS['BE_USER']; } }
stweil/TYPO3.CMS
typo3/sysext/backend/Classes/Controller/ContentElement/MoveElementController.php
PHP
gpl-2.0
11,199
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <elad@fedoraproject.org> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. from dnfpluginscore import logger import dnf import os.path class BashCompletionCache(dnf.Plugin): name = 'generate_completion_cache' def __init__(self, base, cli): self.base = base self.available_cache_file = '/var/cache/dnf/available.cache' self.installed_cache_file = '/var/cache/dnf/installed.cache' def _out(self, msg): logger.debug('Completion plugin: %s', msg) def sack(self): ''' Generate cache of available packages ''' # We generate this cache only if the repos were just freshed or if the # cache file doesn't exist fresh = False for repo in self.base.repos.iter_enabled(): if repo.metadata is not None and repo.metadata.fresh: # One fresh repo is enough to cause a regen of the cache fresh = True break if not os.path.exists(self.available_cache_file) or fresh: try: with open(self.available_cache_file, 'w') as cache_file: self._out('Generating completion cache...') available_packages = self.base.sack.query().available() for package in available_packages: cache_file.write(package.name + '\n') except Exception as e: self._out('Can\'t write completion cache: %s' % e) def transaction(self): ''' Generate cache of installed packages ''' try: with open(self.installed_cache_file, 'w') as cache_file: installed_packages = self.base.sack.query().installed() self._out('Generating completion cache...') for package in installed_packages: cache_file.write(package.name + '\n') except Exception as e: self._out('Can\'t write completion cache: %s' % e)
rholy/dnf-plugins-core
plugins/generate_completion_cache.py
Python
gpl-2.0
2,729
from django.conf.urls import * urlpatterns = patterns('foo.views', # Listing URL url(r'^$', view='browse', name='foo.browse'), # Detail URL url(r'^(?P<slug>(?!overview\-)[\w\-\_\.\,]+)/$', view='detail', name='foo.detail'), )
barseghyanartur/django-slim
example/example/foo/urls.py
Python
gpl-2.0
243
/*************************************************************************** qgsgeometry.cpp - Geometry (stored as Open Geospatial Consortium WKB) ------------------------------------------------------------------- Date : 02 May 2005 Copyright : (C) 2005 by Brendan Morley email : morb at ozemail dot com dot au *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <limits> #include <cstdarg> #include <cstdio> #include <cmath> #include "qgis.h" #include "qgsgeometry.h" #include "qgsapplication.h" #include "qgslogger.h" #include "qgsmessagelog.h" #include "qgspoint.h" #include "qgsrectangle.h" #include "qgsmaplayerregistry.h" #include "qgsvectorlayer.h" #include "qgsproject.h" #include "qgsgeometryvalidator.h" #include <QDebug> #ifndef Q_OS_WIN #include <netinet/in.h> #else #include <winsock.h> #endif #define DEFAULT_QUADRANT_SEGMENTS 8 #define CATCH_GEOS(r) \ catch (GEOSException &e) \ { \ QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr("GEOS") ); \ return r; \ } class GEOSException { public: GEOSException( QString theMsg ) { if ( theMsg == "Unknown exception thrown" && lastMsg.isNull() ) { msg = theMsg; } else { msg = theMsg; lastMsg = msg; } } // copy constructor GEOSException( const GEOSException &rhs ) { *this = rhs; } ~GEOSException() { if ( lastMsg == msg ) lastMsg = QString::null; } QString what() { return msg; } private: QString msg; static QString lastMsg; }; QString GEOSException::lastMsg; static void throwGEOSException( const char *fmt, ... ) { va_list ap; char buffer[1024]; va_start( ap, fmt ); vsnprintf( buffer, sizeof buffer, fmt, ap ); va_end( ap ); qWarning() << QString( "GEOS exception: %1" ).arg( buffer ); throw GEOSException( QString::fromUtf8( buffer ) ); } static void printGEOSNotice( const char *fmt, ... ) { #if defined(QGISDEBUG) va_list ap; char buffer[1024]; va_start( ap, fmt ); vsnprintf( buffer, sizeof buffer, fmt, ap ); va_end( ap ); QgsDebugMsg( QString( "GEOS notice: %1" ).arg( QString::fromUtf8( buffer ) ) ); #else Q_UNUSED( fmt ); #endif } class GEOSInit { public: GEOSContextHandle_t ctxt; GEOSInit() { ctxt = initGEOS_r( printGEOSNotice, throwGEOSException ); } ~GEOSInit() { finishGEOS_r( ctxt ); } }; static GEOSInit geosinit; GEOSContextHandle_t QgsGeometry::getGEOSHandler() { return geosinit.ctxt; } QgsGeometry::QgsGeometry() : mGeometry( 0 ) , mGeometrySize( 0 ) , mGeos( 0 ) , mDirtyWkb( false ) , mDirtyGeos( false ) { } QgsGeometry::QgsGeometry( QgsGeometry const & rhs ) : mGeometry( 0 ) , mGeometrySize( rhs.mGeometrySize ) , mDirtyWkb( rhs.mDirtyWkb ) , mDirtyGeos( rhs.mDirtyGeos ) { if ( mGeometrySize && rhs.mGeometry ) { mGeometry = new unsigned char[mGeometrySize]; memcpy( mGeometry, rhs.mGeometry, mGeometrySize ); } // deep-copy the GEOS Geometry if appropriate if ( rhs.mGeos ) mGeos = GEOSGeom_clone_r( geosinit.ctxt, rhs.mGeos ); else mGeos = 0; } //! Destructor QgsGeometry::~QgsGeometry() { if ( mGeometry ) delete [] mGeometry; if ( mGeos ) GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); } static unsigned int getNumGeosPoints( const GEOSGeometry *geom ) { unsigned int n; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, geom ); GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &n ); return n; } static GEOSGeometry *createGeosPoint( const double x, const double y ) { GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosinit.ctxt, 1, 2 ); GEOSCoordSeq_setX_r( geosinit.ctxt, coord, 0, x ); GEOSCoordSeq_setY_r( geosinit.ctxt, coord, 0, y ); return GEOSGeom_createPoint_r( geosinit.ctxt, coord ); } static GEOSGeometry *createGeosPoint( const QgsPoint &point ) { return createGeosPoint( point.x(), point.y() ); } static GEOSCoordSequence *createGeosCoordSequence( const QgsPolyline& points ) { GEOSCoordSequence *coord = 0; try { coord = GEOSCoordSeq_create_r( geosinit.ctxt, points.count(), 2 ); int i; for ( i = 0; i < points.count(); i++ ) { GEOSCoordSeq_setX_r( geosinit.ctxt, coord, i, points[i].x() ); GEOSCoordSeq_setY_r( geosinit.ctxt, coord, i, points[i].y() ); } return coord; } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); /*if ( coord ) GEOSCoordSeq_destroy( coord );*/ throw; } } static GEOSGeometry *createGeosCollection( int typeId, QVector<GEOSGeometry*> geoms ) { GEOSGeometry **geomarr = new GEOSGeometry*[ geoms.size()]; if ( !geomarr ) return 0; for ( int i = 0; i < geoms.size(); i++ ) geomarr[i] = geoms[i]; GEOSGeometry *geom = 0; try { geom = GEOSGeom_createCollection_r( geosinit.ctxt, typeId, geomarr, geoms.size() ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); } delete [] geomarr; return geom; } static GEOSGeometry *createGeosLineString( const QgsPolyline& polyline ) { GEOSCoordSequence *coord = 0; try { coord = createGeosCoordSequence( polyline ); return GEOSGeom_createLineString_r( geosinit.ctxt, coord ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); //MH: for strange reasons, geos3 crashes when removing the coordinate sequence //if ( coord ) //GEOSCoordSeq_destroy( coord ); return 0; } } static GEOSGeometry *createGeosLinearRing( const QgsPolyline& polyline ) { GEOSCoordSequence *coord = 0; if ( polyline.count() <= 2 ) return 0; try { if ( polyline[0] != polyline[polyline.size()-1] ) { // Ring not closed QgsPolyline closed( polyline ); closed << closed[0]; coord = createGeosCoordSequence( closed ); } else { // XXX [MD] this exception should not be silenced! // this is here just because maptopixel simplification can return invalid linear rings if ( polyline.count() == 3 ) //-> Avoid 'GEOS::IllegalArgumentException: Invalid number of points in LinearRing found 3 - must be 0 or >= 4' return 0; coord = createGeosCoordSequence( polyline ); } return GEOSGeom_createLinearRing_r( geosinit.ctxt, coord ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); /* as MH has noticed ^, this crashes geos if ( coord ) GEOSCoordSeq_destroy( coord );*/ return 0; } } static GEOSGeometry *createGeosPolygon( const QVector<GEOSGeometry*> &rings ) { GEOSGeometry *shell; if ( rings.size() == 0 ) { #if defined(GEOS_VERSION_MAJOR) && defined(GEOS_VERSION_MINOR) && \ ((GEOS_VERSION_MAJOR>3) || ((GEOS_VERSION_MAJOR==3) && (GEOS_VERSION_MINOR>=3))) return GEOSGeom_createEmptyPolygon_r( geosinit.ctxt ); #else shell = GEOSGeom_createLinearRing_r( geosinit.ctxt, GEOSCoordSeq_create_r( geosinit.ctxt, 0, 2 ) ); #endif } else { shell = rings[0]; } GEOSGeometry **holes = NULL; int nHoles = 0; if ( rings.size() > 1 ) { nHoles = rings.size() - 1; holes = new GEOSGeometry*[ nHoles ]; if ( !holes ) return 0; for ( int i = 0; i < nHoles; i++ ) holes[i] = rings[i+1]; } GEOSGeometry *geom = GEOSGeom_createPolygon_r( geosinit.ctxt, shell, holes, nHoles ); if ( holes ) delete [] holes; return geom; } static GEOSGeometry *createGeosPolygon( GEOSGeometry *shell ) { return createGeosPolygon( QVector<GEOSGeometry*>() << shell ); } static GEOSGeometry *createGeosPolygon( const QgsPolygon& polygon ) { if ( polygon.count() == 0 ) return 0; QVector<GEOSGeometry *> geoms; try { for ( int i = 0; i < polygon.count(); i++ ) { GEOSGeometry *ring = createGeosLinearRing( polygon[i] ); if ( !ring ) { // something went really wrong - exit for ( int j = 0; j < geoms.count(); j++ ) GEOSGeom_destroy_r( geosinit.ctxt, geoms[j] ); // XXX [MD] we just silently return here - but we shouldn't // this is just because maptopixel simplification can return invalid linear rings return 0; } geoms << ring; } return createGeosPolygon( geoms ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); for ( int i = 0; i < geoms.count(); i++ ) GEOSGeom_destroy_r( geosinit.ctxt, geoms[i] ); return 0; } } static QgsGeometry *fromGeosGeom( GEOSGeometry *geom ) { if ( !geom ) return 0; QgsGeometry *g = new QgsGeometry; g->fromGeos( geom ); return g; } QgsGeometry* QgsGeometry::fromWkt( QString wkt ) { try { GEOSWKTReader *reader = GEOSWKTReader_create_r( geosinit.ctxt ); QgsGeometry *g = fromGeosGeom( GEOSWKTReader_read_r( geosinit.ctxt, reader, wkt.toLocal8Bit().data() ) ); GEOSWKTReader_destroy_r( geosinit.ctxt, reader ); return g; } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); return 0; } } QgsGeometry* QgsGeometry::fromPoint( const QgsPoint& point ) { return fromGeosGeom( createGeosPoint( point ) ); } QgsGeometry* QgsGeometry::fromPolyline( const QgsPolyline& polyline ) { return fromGeosGeom( createGeosLineString( polyline ) ); } QgsGeometry* QgsGeometry::fromPolygon( const QgsPolygon& polygon ) { return fromGeosGeom( createGeosPolygon( polygon ) ); } QgsGeometry* QgsGeometry::fromMultiPoint( const QgsMultiPoint& multipoint ) { QVector<GEOSGeometry *> geoms; try { for ( int i = 0; i < multipoint.size(); ++i ) geoms << createGeosPoint( multipoint[i] ); return fromGeosGeom( createGeosCollection( GEOS_MULTIPOINT, geoms ) ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); for ( int i = 0; i < geoms.size(); ++i ) GEOSGeom_destroy_r( geosinit.ctxt, geoms[i] ); return 0; } } QgsGeometry* QgsGeometry::fromMultiPolyline( const QgsMultiPolyline& multiline ) { QVector<GEOSGeometry *> geoms; try { for ( int i = 0; i < multiline.count(); i++ ) geoms << createGeosLineString( multiline[i] ); return fromGeosGeom( createGeosCollection( GEOS_MULTILINESTRING, geoms ) ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); for ( int i = 0; i < geoms.count(); i++ ) GEOSGeom_destroy_r( geosinit.ctxt, geoms[i] ); return 0; } } QgsGeometry* QgsGeometry::fromMultiPolygon( const QgsMultiPolygon& multipoly ) { if ( multipoly.count() == 0 ) return 0; QVector<GEOSGeometry *> geoms; try { for ( int i = 0; i < multipoly.count(); i++ ) geoms << createGeosPolygon( multipoly[i] ); return fromGeosGeom( createGeosCollection( GEOS_MULTIPOLYGON, geoms ) ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); for ( int i = 0; i < geoms.count(); i++ ) GEOSGeom_destroy_r( geosinit.ctxt, geoms[i] ); return 0; } } QgsGeometry* QgsGeometry::fromRect( const QgsRectangle& rect ) { QgsPolyline ring; ring.append( QgsPoint( rect.xMinimum(), rect.yMinimum() ) ); ring.append( QgsPoint( rect.xMaximum(), rect.yMinimum() ) ); ring.append( QgsPoint( rect.xMaximum(), rect.yMaximum() ) ); ring.append( QgsPoint( rect.xMinimum(), rect.yMaximum() ) ); ring.append( QgsPoint( rect.xMinimum(), rect.yMinimum() ) ); QgsPolygon polygon; polygon.append( ring ); return fromPolygon( polygon ); } QgsGeometry *QgsGeometry::fromQPointF( const QPointF &point ) { return fromGeosGeom( createGeosPoint( point.x(), point.y() ) ); } QgsGeometry *QgsGeometry::fromQPolygonF( const QPolygonF &polygon ) { if ( polygon.isClosed() ) { return QgsGeometry::fromPolygon( createPolygonFromQPolygonF( polygon ) ); } else { return QgsGeometry::fromPolyline( createPolylineFromQPolygonF( polygon ) ); } } QgsPolygon QgsGeometry::createPolygonFromQPolygonF( const QPolygonF &polygon ) { QgsPolygon result; result << createPolylineFromQPolygonF( polygon ); return result; } QgsPolyline QgsGeometry::createPolylineFromQPolygonF( const QPolygonF &polygon ) { QgsPolyline result; QPolygonF::const_iterator it = polygon.constBegin(); for ( ; it != polygon.constEnd(); ++it ) { result.append( QgsPoint( *it ) ); } return result; } QgsGeometry & QgsGeometry::operator=( QgsGeometry const & rhs ) { if ( &rhs == this ) return *this; // remove old geometry if it exists if ( mGeometry ) { delete [] mGeometry; mGeometry = 0; } mGeometrySize = rhs.mGeometrySize; // deep-copy the GEOS Geometry if appropriate GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = rhs.mGeos ? GEOSGeom_clone_r( geosinit.ctxt, rhs.mGeos ) : 0; mDirtyGeos = rhs.mDirtyGeos; mDirtyWkb = rhs.mDirtyWkb; if ( mGeometrySize && rhs.mGeometry ) { mGeometry = new unsigned char[mGeometrySize]; memcpy( mGeometry, rhs.mGeometry, mGeometrySize ); } return *this; } // QgsGeometry::operator=( QgsGeometry const & rhs ) void QgsGeometry::fromWkb( unsigned char *wkb, size_t length ) { // delete any existing WKB geometry before assigning new one if ( mGeometry ) { delete [] mGeometry; mGeometry = 0; } if ( mGeos ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = 0; } mGeometry = wkb; mGeometrySize = length; mDirtyWkb = false; mDirtyGeos = true; } const unsigned char *QgsGeometry::asWkb() const { if ( mDirtyWkb ) exportGeosToWkb(); return mGeometry; } size_t QgsGeometry::wkbSize() const { if ( mDirtyWkb ) exportGeosToWkb(); return mGeometrySize; } const GEOSGeometry* QgsGeometry::asGeos() const { if ( mDirtyGeos ) { if ( !exportWkbToGeos() ) { return 0; } } return mGeos; } QGis::WkbType QgsGeometry::wkbType() const { QgsConstWkbPtr wkbPtr( asWkb() + 1 ); // ensure that wkb representation exists if ( mGeometry && wkbSize() >= 5 ) { QGis::WkbType wkbType; wkbPtr >> wkbType; return wkbType; } else { return QGis::WKBUnknown; } } QGis::GeometryType QgsGeometry::type() const { if ( mDirtyWkb ) exportGeosToWkb(); switch ( wkbType() ) { case QGis::WKBPoint: case QGis::WKBPoint25D: case QGis::WKBMultiPoint: case QGis::WKBMultiPoint25D: return QGis::Point; case QGis::WKBLineString: case QGis::WKBLineString25D: case QGis::WKBMultiLineString: case QGis::WKBMultiLineString25D: return QGis::Line; case QGis::WKBPolygon: case QGis::WKBPolygon25D: case QGis::WKBMultiPolygon: case QGis::WKBMultiPolygon25D: return QGis::Polygon; default: return QGis::UnknownGeometry; } } bool QgsGeometry::isMultipart() const { if ( mDirtyWkb ) exportGeosToWkb(); return QGis::isMultiType( wkbType() ); } void QgsGeometry::fromGeos( GEOSGeometry *geos ) { // TODO - make this more heap-friendly if ( mGeos ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = 0; } if ( mGeometry ) { delete [] mGeometry; mGeometry = 0; } mGeos = geos; mDirtyWkb = true; mDirtyGeos = false; } QgsPoint QgsGeometry::closestVertex( const QgsPoint& point, int& atVertex, int& beforeVertex, int& afterVertex, double& sqrDist ) const { // TODO: implement with GEOS if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return QgsPoint( 0, 0 ); } double actdist = std::numeric_limits<double>::max(); beforeVertex = -1; afterVertex = -1; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; QgsPoint p; bool hasZValue = false; int vertexnr = -1; switch ( wkbType ) { case QGis::WKBPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBPoint: { double x, y; wkbPtr >> x >> y; p.set( x, y ); actdist = point.sqrDist( x, y ); vertexnr = 0; break; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); double dist = point.sqrDist( x, y ); if ( dist < actdist ) { p.set( x, y ); actdist = dist; vertexnr = index; beforeVertex = index - 1; afterVertex = index == nPoints - 1 ? -1 : index + 1; } } break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int index = 0, pointIndex = 0; index < nRings; ++index ) { int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); double dist = point.sqrDist( x, y ); if ( dist < actdist ) { p.set( x, y ); actdist = dist; vertexnr = pointIndex; // assign the rubberband indices if ( index2 == 0 ) { beforeVertex = pointIndex + ( nPoints - 2 ); afterVertex = pointIndex + 1; } else if ( index2 == nPoints - 1 ) { beforeVertex = pointIndex - 1; afterVertex = pointIndex - ( nPoints - 2 ); } else { beforeVertex = pointIndex - 1; afterVertex = pointIndex + 1; } } ++pointIndex; } } break; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) { wkbPtr += 1 + sizeof( int ); // skip endian and point type double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); double dist = point.sqrDist( x, y ); if ( dist < actdist ) { p.set( x, y ); actdist = dist; vertexnr = index; } } break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int index = 0, pointIndex = 0; index < nLines; ++index ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); double dist = point.sqrDist( x, y ); if ( dist < actdist ) { p.set( x, y ); actdist = dist; vertexnr = pointIndex; if ( index2 == 0 )//assign the rubber band indices beforeVertex = -1; else beforeVertex = vertexnr - 1; if ( index2 == nPoints - 1 ) afterVertex = -1; else afterVertex = vertexnr + 1; } ++pointIndex; } } break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolys; wkbPtr >> nPolys; for ( int index = 0, pointIndex = 0; index < nPolys; ++index ) { wkbPtr += 1 + sizeof( int ); //skip endian and polygon type int nRings; wkbPtr >> nRings; for ( int index2 = 0; index2 < nRings; ++index2 ) { int nPoints; wkbPtr >> nPoints; for ( int index3 = 0; index3 < nPoints; ++index3 ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); double dist = point.sqrDist( x, y ); if ( dist < actdist ) { p.set( x, y ); actdist = dist; vertexnr = pointIndex; //assign the rubber band indices if ( index3 == 0 ) { beforeVertex = pointIndex + ( nPoints - 2 ); afterVertex = pointIndex + 1; } else if ( index3 == nPoints - 1 ) { beforeVertex = pointIndex - 1; afterVertex = pointIndex - ( nPoints - 2 ); } else { beforeVertex = pointIndex - 1; afterVertex = pointIndex + 1; } } ++pointIndex; } } } break; } default: break; } sqrDist = actdist; atVertex = vertexnr; return p; } void QgsGeometry::adjacentVertices( int atVertex, int& beforeVertex, int& afterVertex ) const { // TODO: implement with GEOS if ( mDirtyWkb ) exportGeosToWkb(); beforeVertex = -1; afterVertex = -1; if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return; } if ( atVertex < 0 ) return; QGis::WkbType wkbType; bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); wkbPtr >> wkbType; switch ( wkbType ) { case QGis::WKBPoint: { // NOOP - Points do not have adjacent verticies break; } case QGis::WKBLineString25D: case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; if ( atVertex >= nPoints ) return; const int index = atVertex; // assign the rubber band indices beforeVertex = index - 1; if ( index == nPoints - 1 ) afterVertex = -1; else afterVertex = index + 1; break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int index0 = 0, pointIndex = 0; index0 < nRings; ++index0 ) { int nPoints; wkbPtr >> nPoints; for ( int index1 = 0; index1 < nPoints; ++index1 ) { wkbPtr += ( hasZValue ? 3 : 2 ) * sizeof( double ); if ( pointIndex == atVertex ) { if ( index1 == 0 ) { beforeVertex = pointIndex + ( nPoints - 2 ); afterVertex = pointIndex + 1; } else if ( index1 == nPoints - 1 ) { beforeVertex = pointIndex - 1; afterVertex = pointIndex - ( nPoints - 2 ); } else { beforeVertex = pointIndex - 1; afterVertex = pointIndex + 1; } } ++pointIndex; } } break; } case QGis::WKBMultiPoint25D: case QGis::WKBMultiPoint: { // NOOP - Points do not have adjacent verticies break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int index0 = 0, pointIndex = 0; index0 < nLines; ++index0 ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; for ( int index1 = 0; index1 < nPoints; ++index1 ) { wkbPtr += ( hasZValue ? 3 : 2 ) * sizeof( double ); if ( pointIndex == atVertex ) { // Found the vertex of the linestring we were looking for. if ( index1 == 0 ) beforeVertex = -1; else beforeVertex = pointIndex - 1; if ( index1 == nPoints - 1 ) afterVertex = -1; else afterVertex = pointIndex + 1; } ++pointIndex; } } break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolys; wkbPtr >> nPolys; for ( int index0 = 0, pointIndex = 0; index0 < nPolys; ++index0 ) { wkbPtr += 1 + sizeof( int ); //skip endian and polygon type int nRings; wkbPtr >> nRings; for ( int index1 = 0; index1 < nRings; ++index1 ) { int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) { wkbPtr += ( hasZValue ? 3 : 2 ) * sizeof( double ); if ( pointIndex == atVertex ) { // Found the vertex of the linear-ring of the polygon we were looking for. // assign the rubber band indices if ( index2 == 0 ) { beforeVertex = pointIndex + ( nPoints - 2 ); afterVertex = pointIndex + 1; } else if ( index2 == nPoints - 1 ) { beforeVertex = pointIndex - 1; afterVertex = pointIndex - ( nPoints - 2 ); } else { beforeVertex = pointIndex - 1; afterVertex = pointIndex + 1; } } ++pointIndex; } } } break; } default: break; } // switch (wkbType) } bool QgsGeometry::insertVertex( double x, double y, int beforeVertex, const GEOSCoordSequence *old_sequence, GEOSCoordSequence **new_sequence ) { // Bounds checking if ( beforeVertex < 0 ) { *new_sequence = 0; return false; } unsigned int numPoints; GEOSCoordSeq_getSize_r( geosinit.ctxt, old_sequence, &numPoints ); *new_sequence = GEOSCoordSeq_create_r( geosinit.ctxt, numPoints + 1, 2 ); if ( !*new_sequence ) return false; bool inserted = false; for ( unsigned int i = 0, j = 0; i < numPoints; i++, j++ ) { // Do we insert the new vertex here? if ( beforeVertex == static_cast<int>( i ) ) { GEOSCoordSeq_setX_r( geosinit.ctxt, *new_sequence, j, x ); GEOSCoordSeq_setY_r( geosinit.ctxt, *new_sequence, j, y ); j++; inserted = true; } double aX, aY; GEOSCoordSeq_getX_r( geosinit.ctxt, old_sequence, i, &aX ); GEOSCoordSeq_getY_r( geosinit.ctxt, old_sequence, i, &aY ); GEOSCoordSeq_setX_r( geosinit.ctxt, *new_sequence, j, aX ); GEOSCoordSeq_setY_r( geosinit.ctxt, *new_sequence, j, aY ); } if ( !inserted ) { // The beforeVertex is greater than the actual number of vertices // in the geometry - append it. GEOSCoordSeq_setX_r( geosinit.ctxt, *new_sequence, numPoints, x ); GEOSCoordSeq_setY_r( geosinit.ctxt, *new_sequence, numPoints, y ); } // TODO: Check that the sequence is still simple, e.g. with GEOS_GEOM::Geometry->isSimple() return inserted; } bool QgsGeometry::moveVertex( QgsWkbPtr &wkbPtr, const double &x, const double &y, int atVertex, bool hasZValue, int &pointIndex, bool isRing ) { int nPoints; wkbPtr >> nPoints; const int ps = ( hasZValue ? 3 : 2 ) * sizeof( double ); // Not this linestring/ring? if ( atVertex >= pointIndex + nPoints ) { wkbPtr += ps * nPoints; pointIndex += nPoints; return false; } if ( isRing && atVertex == pointIndex + nPoints - 1 ) atVertex = pointIndex; // Goto point in this linestring/ring wkbPtr += ps * ( atVertex - pointIndex ); wkbPtr << x << y; if ( hasZValue ) wkbPtr << 0.0; if ( isRing && atVertex == pointIndex ) { wkbPtr += ps * ( nPoints - 2 ); wkbPtr << x << y; if ( hasZValue ) wkbPtr << 0.0; } return true; } bool QgsGeometry::moveVertex( double x, double y, int atVertex ) { if ( atVertex < 0 ) return false; if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return false; } QGis::WkbType wkbType; bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); wkbPtr >> wkbType; switch ( wkbType ) { case QGis::WKBPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBPoint: { if ( atVertex != 0 ) return false; wkbPtr << x << y; mDirtyGeos = true; return true; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int pointIndex = 0; if ( moveVertex( wkbPtr, x, y, atVertex, hasZValue, pointIndex, false ) ) { mDirtyGeos = true; return true; } return false; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; if ( atVertex < nPoints ) { wkbPtr += atVertex * ( 1 + sizeof( int ) + ( hasZValue ? 3 : 2 ) * sizeof( double ) ) + 1 + sizeof( int ); wkbPtr << x << y; if ( hasZValue ) wkbPtr << 0.0; mDirtyGeos = true; return true; } else { return false; } } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { wkbPtr += 1 + sizeof( int ); if ( moveVertex( wkbPtr, x, y, atVertex, hasZValue, pointIndex, false ) ) { mDirtyGeos = true; return true; } } return false; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nLines; wkbPtr >> nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { if ( moveVertex( wkbPtr, x, y, atVertex, hasZValue, pointIndex, true ) ) { mDirtyGeos = true; return true; } } return false; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolygons; wkbPtr >> nPolygons; for ( int polynr = 0, pointIndex = 0; polynr < nPolygons; ++polynr ) { wkbPtr += 1 + sizeof( int ); // skip endian and polygon type int nRings; wkbPtr >> nRings; for ( int ringnr = 0; ringnr < nRings; ++ringnr ) { if ( moveVertex( wkbPtr, x, y, atVertex, hasZValue, pointIndex, true ) ) { mDirtyGeos = true; return true; } } } return false; } default: return false; } } // copy vertices from srcPtr to dstPtr and skip/delete one vertex // @param srcPtr ring/part starting with number of points (adjusted in each call) // @param dstPtr ring/part to copy to (adjusted in each call) // @param atVertex index of vertex to skip // @param hasZValue points have 3 elements // @param pointIndex reference to index of first ring/part vertex in overall object (adjusted in each call) // @param isRing srcPtr points to a ring // @param lastItem last ring/part, atVertex after this one must be wrong // @return // 0 no delete was done // 1 "normal" delete was done // 2 last element of the ring/part was deleted int QgsGeometry::deleteVertex( QgsConstWkbPtr &srcPtr, QgsWkbPtr &dstPtr, int atVertex, bool hasZValue, int &pointIndex, bool isRing, bool lastItem ) { QgsDebugMsg( QString( "atVertex:%1 hasZValue:%2 pointIndex:%3 isRing:%4" ).arg( atVertex ).arg( hasZValue ).arg( pointIndex ).arg( isRing ) ); const int ps = ( hasZValue ? 3 : 2 ) * sizeof( double ); int nPoints; srcPtr >> nPoints; // copy complete ring/part if vertex is in a following one if ( atVertex < pointIndex || atVertex >= pointIndex + nPoints ) { // atVertex does not exist if ( lastItem && atVertex >= pointIndex + nPoints ) return 0; dstPtr << nPoints; int len = nPoints * ps; memcpy( dstPtr, srcPtr, len ); dstPtr += len; srcPtr += len; pointIndex += nPoints; return 0; } // delete the first vertex of a ring instead of the last if ( isRing && atVertex == pointIndex + nPoints - 1 ) atVertex = pointIndex; if ( nPoints == ( isRing ? 2 : 1 ) ) { // last point of the part/ring is deleted // skip the whole part/ring srcPtr += nPoints * ps; pointIndex += nPoints; return 2; } dstPtr << nPoints - 1; // copy ring before vertex int len = ( atVertex - pointIndex ) * ps; if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); dstPtr += len; srcPtr += len; } // skip deleted vertex srcPtr += ps; // copy reset of ring len = ( pointIndex + nPoints - atVertex - 1 ) * ps; // save position of vertex, if we delete the first vertex of a ring const unsigned char *first = 0; if ( isRing && atVertex == pointIndex ) { len -= ps; first = srcPtr; } if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); dstPtr += len; srcPtr += len; } // copy new first vertex instead of the old last, if we deleted the original first vertex if ( first ) { memcpy( dstPtr, first, ps ); dstPtr += ps; srcPtr += ps; } pointIndex += nPoints; return 1; } bool QgsGeometry::deleteVertex( int atVertex ) { QgsDebugMsg( QString( "atVertex:%1" ).arg( atVertex ) ); if ( atVertex < 0 ) return false; if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return false; } QgsConstWkbPtr srcPtr( mGeometry ); char endianness; QGis::WkbType wkbType; srcPtr >> endianness >> wkbType; bool hasZValue = QGis::wkbDimensions( wkbType ) == 3; int ps = ( hasZValue ? 3 : 2 ) * sizeof( double ); if ( QGis::flatType( wkbType ) == QGis::WKBMultiPoint ) ps += 1 + sizeof( int ); unsigned char *dstBuffer = new unsigned char[mGeometrySize - ps]; QgsWkbPtr dstPtr( dstBuffer ); dstPtr << endianness << wkbType; bool deleted = false; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: break; //cannot remove the only point vertex case QGis::WKBLineString25D: case QGis::WKBLineString: { int pointIndex = 0; int res = deleteVertex( srcPtr, dstPtr, atVertex, hasZValue, pointIndex, false, true ); if ( res == 2 ) { // Linestring with 0 points dstPtr << 0; } deleted = res != 0; break; } case QGis::WKBPolygon25D: case QGis::WKBPolygon: { int nRings; srcPtr >> nRings; QgsWkbPtr ptrN( dstPtr ); dstPtr << nRings; for ( int ringnr = 0, pointIndex = 0; ringnr < nRings; ++ringnr ) { int res = deleteVertex( srcPtr, dstPtr, atVertex, hasZValue, pointIndex, true, ringnr == nRings - 1 ); if ( res == 2 ) ptrN << nRings - 1; deleted |= res != 0; } break; } case QGis::WKBMultiPoint25D: case QGis::WKBMultiPoint: { int nPoints; srcPtr >> nPoints; if ( atVertex < nPoints ) { dstPtr << nPoints - 1; int len = ps * atVertex; if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); srcPtr += len; dstPtr += len; } srcPtr += ps; len = ps * ( nPoints - atVertex - 1 ); if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); srcPtr += len; dstPtr += len; } deleted = true; } break; } case QGis::WKBMultiLineString25D: case QGis::WKBMultiLineString: { int nLines; srcPtr >> nLines; QgsWkbPtr ptrN( dstPtr ); dstPtr << nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { QgsWkbPtr saveDstPtr( dstPtr ); srcPtr >> endianness >> wkbType; dstPtr << endianness << wkbType; int res = deleteVertex( srcPtr, dstPtr, atVertex, hasZValue, pointIndex, false, linenr == nLines - 1 ); if ( res == 2 ) { // line string was completely removed ptrN << nLines - 1; dstPtr = saveDstPtr; } deleted |= res != 0; } break; } case QGis::WKBMultiPolygon25D: case QGis::WKBMultiPolygon: { int nPolys; srcPtr >> nPolys; QgsWkbPtr ptrNPolys( dstPtr ); dstPtr << nPolys; for ( int polynr = 0, pointIndex = 0; polynr < nPolys; ++polynr ) { int nRings; srcPtr >> endianness >> wkbType >> nRings; QgsWkbPtr saveDstPolyPtr( dstPtr ); dstPtr << endianness << wkbType; QgsWkbPtr ptrNRings( dstPtr ); dstPtr << nRings; for ( int ringnr = 0; ringnr < nRings; ++ringnr ) { int res = deleteVertex( srcPtr, dstPtr, atVertex, hasZValue, pointIndex, true, polynr == nPolys - 1 && ringnr == nRings - 1 ); if ( res == 2 ) { // ring was completely removed if ( nRings == 1 ) { // last ring => remove polygon ptrNPolys << nPolys - 1; dstPtr = saveDstPolyPtr; } else { ptrNRings << nRings - 1; } } deleted |= res != 0; } } break; } case QGis::WKBNoGeometry: case QGis::WKBUnknown: break; } if ( deleted ) { delete [] mGeometry; mGeometry = dstBuffer; mGeometrySize -= ps; mDirtyGeos = true; return true; } else { delete [] dstBuffer; return false; } } bool QgsGeometry::insertVertex( QgsConstWkbPtr &srcPtr, QgsWkbPtr &dstPtr, int beforeVertex, const double &x, const double &y, bool hasZValue, int &pointIndex, bool isRing ) { int nPoints; srcPtr >> nPoints; bool insertHere = beforeVertex >= pointIndex && beforeVertex < pointIndex + nPoints; int len; if ( insertHere ) { dstPtr << nPoints + 1; len = ( hasZValue ? 3 : 2 ) * ( beforeVertex - pointIndex ) * sizeof( double ); if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); srcPtr += len; dstPtr += len; } dstPtr << x << y; if ( hasZValue ) dstPtr << 0.0; len = ( hasZValue ? 3 : 2 ) * ( pointIndex + nPoints - beforeVertex ) * sizeof( double ); if ( isRing && beforeVertex == pointIndex ) len -= ( hasZValue ? 3 : 2 ) * sizeof( double ); } else { dstPtr << nPoints; len = ( hasZValue ? 3 : 2 ) * nPoints * sizeof( double ); } memcpy( dstPtr, srcPtr, len ); srcPtr += len; dstPtr += len; if ( isRing && beforeVertex == pointIndex ) { dstPtr << x << y; if ( hasZValue ) dstPtr << 0.0; } pointIndex += nPoints; return insertHere; } bool QgsGeometry::insertVertex( double x, double y, int beforeVertex ) { // TODO: implement with GEOS if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return false; } if ( beforeVertex < 0 ) return false; QgsConstWkbPtr srcPtr( mGeometry ); char endianness; QGis::WkbType wkbType; srcPtr >> endianness >> wkbType; bool hasZValue = QGis::wkbDimensions( wkbType ) == 3; int ps = ( hasZValue ? 3 : 2 ) * sizeof( double ); if ( QGis::flatType( wkbType ) == QGis::WKBMultiPoint ) ps += 1 + sizeof( int ); unsigned char *dstBuffer = new unsigned char[mGeometrySize + ps]; QgsWkbPtr dstPtr( dstBuffer ); dstPtr << endianness << wkbType; bool inserted = false; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: //cannot insert a vertex before another one on point types break; case QGis::WKBLineString25D: case QGis::WKBLineString: { int pointIndex = 0; inserted = insertVertex( srcPtr, dstPtr, beforeVertex, x, y, hasZValue, pointIndex, false ); break; } case QGis::WKBPolygon25D: case QGis::WKBPolygon: { int nRings; srcPtr >> nRings; dstPtr << nRings; for ( int ringnr = 0, pointIndex = 0; ringnr < nRings; ++ringnr ) inserted |= insertVertex( srcPtr, dstPtr, beforeVertex, x, y, hasZValue, pointIndex, true ); break; } case QGis::WKBMultiPoint25D: case QGis::WKBMultiPoint: { int nPoints; srcPtr >> nPoints; if ( beforeVertex <= nPoints ) { dstPtr << nPoints + 1; int len = ps * beforeVertex; if ( len > 0 ) { memcpy( dstPtr, srcPtr, len ); srcPtr += len; dstPtr += len; } dstPtr << endianness << ( hasZValue ? QGis::WKBPoint25D : QGis::WKBPoint ) << x << y; if ( hasZValue ) dstPtr << 0.0; len = ps * ( nPoints - beforeVertex ); if ( len > 0 ) memcpy( dstPtr, srcPtr, len ); inserted = true; } break; } case QGis::WKBMultiLineString25D: case QGis::WKBMultiLineString: { int nLines; srcPtr >> nLines; dstPtr << nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { srcPtr >> endianness >> wkbType; dstPtr << endianness << wkbType; inserted |= insertVertex( srcPtr, dstPtr, beforeVertex, x, y, hasZValue, pointIndex, false ); } break; } case QGis::WKBMultiPolygon25D: case QGis::WKBMultiPolygon: { int nPolys; srcPtr >> nPolys; dstPtr << nPolys; for ( int polynr = 0, pointIndex = 0; polynr < nPolys; ++polynr ) { int nRings; srcPtr >> endianness >> wkbType >> nRings; dstPtr << endianness << wkbType << nRings; for ( int ringnr = 0; ringnr < nRings; ++ringnr ) inserted |= insertVertex( srcPtr, dstPtr, beforeVertex, x, y, hasZValue, pointIndex, true ); } break; } case QGis::WKBNoGeometry: case QGis::WKBUnknown: break; } if ( inserted ) { delete [] mGeometry; mGeometry = dstBuffer; mGeometrySize += ps; mDirtyGeos = true; return true; } else { delete [] dstBuffer; return false; } } QgsPoint QgsGeometry::vertexAt( int atVertex ) const { if ( atVertex < 0 ) return QgsPoint( 0, 0 ); if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return QgsPoint( 0, 0 ); } QgsConstWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; bool hasZValue = false; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { if ( atVertex != 0 ) return QgsPoint( 0, 0 ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { // get number of points in the line int nPoints; wkbPtr >> nPoints; if ( atVertex >= nPoints ) return QgsPoint( 0, 0 ); // copy the vertex coordinates wkbPtr += atVertex * ( hasZValue ? 3 : 2 ) * sizeof( double ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int ringnr = 0, pointIndex = 0; ringnr < nRings; ++ringnr ) { int nPoints; wkbPtr >> nPoints; if ( atVertex >= pointIndex + nPoints ) { wkbPtr += nPoints * ( hasZValue ? 3 : 2 ) * sizeof( double ); pointIndex += nPoints; continue; } wkbPtr += ( atVertex - pointIndex ) * ( hasZValue ? 3 : 2 ) * sizeof( double ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } return QgsPoint( 0, 0 ); } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { // get number of points in the line int nPoints; wkbPtr >> nPoints; if ( atVertex >= nPoints ) return QgsPoint( 0, 0 ); wkbPtr += atVertex * ( 1 + sizeof( int ) + ( hasZValue ? 3 : 2 ) * sizeof( double ) ) + 1 + sizeof( int ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; if ( atVertex >= pointIndex + nPoints ) { wkbPtr += nPoints * ( hasZValue ? 3 : 2 ) * sizeof( double ); pointIndex += nPoints; continue; } wkbPtr += ( atVertex - pointIndex ) * ( hasZValue ? 3 : 2 ) * sizeof( double ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } return QgsPoint( 0, 0 ); } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolygons; wkbPtr >> nPolygons; for ( int polynr = 0, pointIndex = 0; polynr < nPolygons; ++polynr ) { wkbPtr += 1 + sizeof( int ); int nRings; wkbPtr >> nRings; for ( int ringnr = 0; ringnr < nRings; ++ringnr ) { int nPoints; wkbPtr >> nPoints; if ( atVertex >= pointIndex + nPoints ) { wkbPtr += nPoints * ( hasZValue ? 3 : 2 ) * sizeof( double ); pointIndex += nPoints; continue; } wkbPtr += ( atVertex - pointIndex ) * ( hasZValue ? 3 : 2 ) * sizeof( double ); double x, y; wkbPtr >> x >> y; return QgsPoint( x, y ); } } return QgsPoint( 0, 0 ); } default: QgsDebugMsg( "error: mGeometry type not recognized" ); return QgsPoint( 0, 0 ); } } double QgsGeometry::sqrDistToVertexAt( QgsPoint& point, int atVertex ) const { QgsPoint pnt = vertexAt( atVertex ); if ( pnt != QgsPoint( 0, 0 ) ) { QgsDebugMsg( "Exiting with distance to " + pnt.toString() ); return point.sqrDist( pnt ); } else { QgsDebugMsg( "Exiting with std::numeric_limits<double>::max()." ); // probably safest to bail out with a very large number return std::numeric_limits<double>::max(); } } double QgsGeometry::closestVertexWithContext( const QgsPoint& point, int& atVertex ) const { double sqrDist = std::numeric_limits<double>::max(); try { // Initialise some stuff int closestVertexIndex = 0; // set up the GEOS geometry if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return -1; const GEOSGeometry *g = GEOSGetExteriorRing_r( geosinit.ctxt, mGeos ); if ( !g ) return -1; const GEOSCoordSequence *sequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, g ); unsigned int n; GEOSCoordSeq_getSize_r( geosinit.ctxt, sequence, &n ); for ( unsigned int i = 0; i < n; i++ ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, sequence, i, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, sequence, i, &y ); double testDist = point.sqrDist( x, y ); if ( testDist < sqrDist ) { closestVertexIndex = i; sqrDist = testDist; } } atVertex = closestVertexIndex; } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); return -1; } return sqrDist; } double QgsGeometry::closestSegmentWithContext( const QgsPoint& point, QgsPoint& minDistPoint, int& afterVertex, double *leftOf, double epsilon ) const { QgsDebugMsgLevel( "Entering.", 3 ); // TODO: implement with GEOS if ( mDirtyWkb ) //convert latest geos to mGeometry exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return -1; } QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; // Initialise some stuff double sqrDist = std::numeric_limits<double>::max(); QgsPoint distPoint; int closestSegmentIndex = 0; bool hasZValue = false; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: case QGis::WKBMultiPoint25D: case QGis::WKBMultiPoint: { // Points have no lines return -1; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; double prevx = 0.0, prevy = 0.0; for ( int index = 0; index < nPoints; ++index ) { double thisx, thisy; wkbPtr >> thisx >> thisy; if ( hasZValue ) wkbPtr += sizeof( double ); if ( index > 0 ) { double testdist = point.sqrDistToSegment( prevx, prevy, thisx, thisy, distPoint, epsilon ); if ( testdist < sqrDist ) { closestSegmentIndex = index; sqrDist = testdist; minDistPoint = distPoint; if ( leftOf ) { *leftOf = QgsGeometry::leftOf( point.x(), point.y(), prevx, prevy, thisx, thisy ); } } } prevx = thisx; prevy = thisy; } afterVertex = closestSegmentIndex; break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int linenr = 0, pointIndex = 0; linenr < nLines; ++linenr ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; double prevx = 0.0, prevy = 0.0; for ( int pointnr = 0; pointnr < nPoints; ++pointnr ) { double thisx, thisy; wkbPtr >> thisx >> thisy; if ( hasZValue ) wkbPtr += sizeof( double ); if ( pointnr > 0 ) { double testdist = point.sqrDistToSegment( prevx, prevy, thisx, thisy, distPoint, epsilon ); if ( testdist < sqrDist ) { closestSegmentIndex = pointIndex; sqrDist = testdist; minDistPoint = distPoint; if ( leftOf ) { *leftOf = QgsGeometry::leftOf( point.x(), point.y(), prevx, prevy, thisx, thisy ); } } } prevx = thisx; prevy = thisy; ++pointIndex; } } afterVertex = closestSegmentIndex; break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int ringnr = 0, pointIndex = 0; ringnr < nRings; ++ringnr )//loop over rings { int nPoints; wkbPtr >> nPoints; double prevx = 0.0, prevy = 0.0; for ( int pointnr = 0; pointnr < nPoints; ++pointnr )//loop over points in a ring { double thisx, thisy; wkbPtr >> thisx >> thisy; if ( hasZValue ) wkbPtr += sizeof( double ); if ( pointnr > 0 ) { double testdist = point.sqrDistToSegment( prevx, prevy, thisx, thisy, distPoint, epsilon ); if ( testdist < sqrDist ) { closestSegmentIndex = pointIndex; sqrDist = testdist; minDistPoint = distPoint; if ( leftOf ) { *leftOf = QgsGeometry::leftOf( point.x(), point.y(), prevx, prevy, thisx, thisy ); } } } prevx = thisx; prevy = thisy; ++pointIndex; } } afterVertex = closestSegmentIndex; break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolygons; wkbPtr >> nPolygons; for ( int polynr = 0, pointIndex = 0; polynr < nPolygons; ++polynr ) { wkbPtr += 1 + sizeof( int ); int nRings; wkbPtr >> nRings; for ( int ringnr = 0; ringnr < nRings; ++ringnr ) { int nPoints; wkbPtr >> nPoints; double prevx = 0.0, prevy = 0.0; for ( int pointnr = 0; pointnr < nPoints; ++pointnr ) { double thisx, thisy; wkbPtr >> thisx >> thisy; if ( hasZValue ) wkbPtr += sizeof( double ); if ( pointnr > 0 ) { double testdist = point.sqrDistToSegment( prevx, prevy, thisx, thisy, distPoint, epsilon ); if ( testdist < sqrDist ) { closestSegmentIndex = pointIndex; sqrDist = testdist; minDistPoint = distPoint; if ( leftOf ) { *leftOf = QgsGeometry::leftOf( point.x(), point.y(), prevx, prevy, thisx, thisy ); } } } prevx = thisx; prevy = thisy; ++pointIndex; } } } afterVertex = closestSegmentIndex; break; } case QGis::WKBUnknown: default: return -1; break; } // switch (wkbType) QgsDebugMsgLevel( QString( "Exiting with nearest point %1, dist %2." ) .arg( point.toString() ).arg( sqrDist ), 3 ); return sqrDist; } int QgsGeometry::addRing( const QList<QgsPoint>& ring ) { //bail out if this geometry is not polygon/multipolygon if ( type() != QGis::Polygon ) return 1; //test for invalid geometries if ( ring.size() < 4 ) return 3; //ring must be closed if ( ring.first() != ring.last() ) return 2; //create geos geometry from wkb if not already there if ( mDirtyGeos ) { exportWkbToGeos(); } if ( !mGeos ) { return 6; } int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); //Fill GEOS Polygons of the feature into list QVector<const GEOSGeometry*> polygonList; if ( wkbType() == QGis::WKBPolygon ) { if ( type != GEOS_POLYGON ) return 1; polygonList << mGeos; } else if ( wkbType() == QGis::WKBMultiPolygon ) { if ( type != GEOS_MULTIPOLYGON ) return 1; for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); ++i ) polygonList << GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); } //create new ring GEOSGeometry *newRing = 0; GEOSGeometry *newRingPolygon = 0; try { newRing = createGeosLinearRing( ring.toVector() ); if ( !GEOSisValid_r( geosinit.ctxt, newRing ) ) { throwGEOSException( "ring is invalid" ); } newRingPolygon = createGeosPolygon( newRing ); if ( !GEOSisValid_r( geosinit.ctxt, newRingPolygon ) ) { throwGEOSException( "ring is invalid" ); } } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); if ( newRingPolygon ) GEOSGeom_destroy_r( geosinit.ctxt, newRingPolygon ); else if ( newRing ) GEOSGeom_destroy_r( geosinit.ctxt, newRing ); return 3; } QVector<GEOSGeometry*> rings; int i; for ( i = 0; i < polygonList.size(); i++ ) { for ( int j = 0; j < rings.size(); j++ ) GEOSGeom_destroy_r( geosinit.ctxt, rings[j] ); rings.clear(); GEOSGeometry *shellRing = 0; GEOSGeometry *shell = 0; try { shellRing = GEOSGeom_clone_r( geosinit.ctxt, GEOSGetExteriorRing_r( geosinit.ctxt, polygonList[i] ) ); shell = createGeosPolygon( shellRing ); if ( !GEOSWithin_r( geosinit.ctxt, newRingPolygon, shell ) ) { GEOSGeom_destroy_r( geosinit.ctxt, shell ); continue; } } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); if ( shell ) GEOSGeom_destroy_r( geosinit.ctxt, shell ); else if ( shellRing ) GEOSGeom_destroy_r( geosinit.ctxt, shellRing ); GEOSGeom_destroy_r( geosinit.ctxt, newRingPolygon ); return 4; } // add outer ring rings << GEOSGeom_clone_r( geosinit.ctxt, shellRing ); GEOSGeom_destroy_r( geosinit.ctxt, shell ); // check inner rings int n = GEOSGetNumInteriorRings_r( geosinit.ctxt, polygonList[i] ); int j; for ( j = 0; j < n; j++ ) { GEOSGeometry *holeRing = 0; GEOSGeometry *hole = 0; try { holeRing = GEOSGeom_clone_r( geosinit.ctxt, GEOSGetInteriorRingN_r( geosinit.ctxt, polygonList[i], j ) ); hole = createGeosPolygon( holeRing ); if ( !GEOSDisjoint_r( geosinit.ctxt, hole, newRingPolygon ) ) { GEOSGeom_destroy_r( geosinit.ctxt, hole ); break; } } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); if ( hole ) GEOSGeom_destroy_r( geosinit.ctxt, hole ); else if ( holeRing ) GEOSGeom_destroy_r( geosinit.ctxt, holeRing ); break; } rings << GEOSGeom_clone_r( geosinit.ctxt, holeRing ); GEOSGeom_destroy_r( geosinit.ctxt, hole ); } if ( j == n ) // this is it... break; } if ( i == polygonList.size() ) { // clear rings for ( int j = 0; j < rings.size(); j++ ) GEOSGeom_destroy_r( geosinit.ctxt, rings[j] ); rings.clear(); GEOSGeom_destroy_r( geosinit.ctxt, newRingPolygon ); // no containing polygon found return 5; } rings << GEOSGeom_clone_r( geosinit.ctxt, newRing ); GEOSGeom_destroy_r( geosinit.ctxt, newRingPolygon ); GEOSGeometry *newPolygon = createGeosPolygon( rings ); if ( wkbType() == QGis::WKBPolygon ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = newPolygon; } else if ( wkbType() == QGis::WKBMultiPolygon ) { QVector<GEOSGeometry*> newPolygons; for ( int j = 0; j < polygonList.size(); j++ ) { newPolygons << ( i == j ? newPolygon : GEOSGeom_clone_r( geosinit.ctxt, polygonList[j] ) ); } GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = createGeosCollection( GEOS_MULTIPOLYGON, newPolygons ); } mDirtyWkb = true; mDirtyGeos = false; return 0; } int QgsGeometry::addPart( const QList<QgsPoint> &points, QGis::GeometryType geomType ) { if ( geomType == QGis::UnknownGeometry ) { geomType = type(); } switch ( geomType ) { case QGis::Point: // only one part at a time if ( points.size() != 1 ) { QgsDebugMsg( "expected 1 point: " + QString::number( points.size() ) ); return 2; } break; case QGis::Line: // line needs to have at least two points if ( points.size() < 2 ) { QgsDebugMsg( "line must at least have two points: " + QString::number( points.size() ) ); return 2; } break; case QGis::Polygon: // polygon needs to have at least three distinct points and must be closed if ( points.size() < 4 ) { QgsDebugMsg( "polygon must at least have three distinct points and must be closed: " + QString::number( points.size() ) ); return 2; } // Polygon must be closed if ( points.first() != points.last() ) { QgsDebugMsg( "polygon not closed" ); return 2; } break; default: QgsDebugMsg( "unsupported geometry type: " + QString::number( geomType ) ); return 2; } GEOSGeometry *newPart = 0; switch ( geomType ) { case QGis::Point: newPart = createGeosPoint( points[0] ); break; case QGis::Line: newPart = createGeosLineString( points.toVector() ); break; case QGis::Polygon: { //create new polygon from ring GEOSGeometry *newRing = 0; try { newRing = createGeosLinearRing( points.toVector() ); if ( !GEOSisValid_r( geosinit.ctxt, newRing ) ) throw GEOSException( "ring invalid" ); newPart = createGeosPolygon( newRing ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); if ( newRing ) GEOSGeom_destroy_r( geosinit.ctxt, newRing ); return 2; } } break; default: QgsDebugMsg( "unsupported type: " + QString::number( type() ) ); return 2; } if ( type() == QGis::UnknownGeometry ) { fromGeos( newPart ); return 0; } return addPart( newPart ); } int QgsGeometry::addPart( QgsGeometry *newPart ) { if ( !newPart ) return 4; const GEOSGeometry * geosPart = newPart->asGeos(); return addPart( GEOSGeom_clone_r( geosinit.ctxt, geosPart ) ); } int QgsGeometry::addPart( GEOSGeometry *newPart ) { QGis::GeometryType geomType = type(); if ( !isMultipart() && !convertToMultiType() ) { QgsDebugMsg( "could not convert to multipart" ); return 1; } //create geos geometry from wkb if not already there if ( mDirtyGeos ) { exportWkbToGeos(); } if ( !mGeos ) { QgsDebugMsg( "GEOS geometry not available!" ); return 4; } int geosType = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); Q_ASSERT( newPart ); try { if ( !GEOSisValid_r( geosinit.ctxt, newPart ) ) throw GEOSException( "new part geometry invalid" ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); if ( newPart ) GEOSGeom_destroy_r( geosinit.ctxt, newPart ); QgsDebugMsg( "part invalid: " + e.what() ); return 2; } QVector<GEOSGeometry*> parts; //create new multipolygon int n = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); int i; for ( i = 0; i < n; ++i ) { const GEOSGeometry *partN = GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); if ( geomType == QGis::Polygon && GEOSOverlaps_r( geosinit.ctxt, partN, newPart ) ) //bail out if new polygon overlaps with existing ones break; parts << GEOSGeom_clone_r( geosinit.ctxt, partN ); } if ( i < n ) { // bailed out for ( int i = 0; i < parts.size(); i++ ) GEOSGeom_destroy_r( geosinit.ctxt, parts[i] ); QgsDebugMsg( "new polygon part overlaps" ); return 3; } int nPartGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, newPart ); for ( int i = 0; i < nPartGeoms; ++i ) { parts << GEOSGeom_clone_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, newPart, i ) ); } GEOSGeom_destroy_r( geosinit.ctxt, newPart ); GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = createGeosCollection( geosType, parts ); mDirtyWkb = true; mDirtyGeos = false; return 0; } int QgsGeometry::transform( const QTransform& t ) { if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return 1; } bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { transformVertex( wkbPtr, t, hasZValue ); } break; case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) transformVertex( wkbPtr, t, hasZValue ); break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int index = 0; index < nRings; ++index ) { int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) transformVertex( wkbPtr, t, hasZValue ); } break; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) { wkbPtr += 1 + sizeof( int ); transformVertex( wkbPtr, t, hasZValue ); } break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int index = 0; index < nLines; ++index ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) transformVertex( wkbPtr, t, hasZValue ); } break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolys; wkbPtr >> nPolys; for ( int index = 0; index < nPolys; ++index ) { wkbPtr += 1 + sizeof( int ); //skip endian and polygon type int nRings; wkbPtr >> nRings; for ( int index2 = 0; index2 < nRings; ++index2 ) { int nPoints; wkbPtr >> nPoints; for ( int index3 = 0; index3 < nPoints; ++index3 ) transformVertex( wkbPtr, t, hasZValue ); } } } default: break; } mDirtyGeos = true; return 0; } int QgsGeometry::translate( double dx, double dy ) { return transform( QTransform::fromTranslate( dx, dy ) ); } int QgsGeometry::rotate( double rotation, const QgsPoint& center ) { QTransform t = QTransform::fromTranslate( center.x(), center.y() ); t.rotate( -rotation ); t.translate( -center.x(), -center.y() ); return transform( t ); } int QgsGeometry::transform( const QgsCoordinateTransform& ct ) { if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return 1; } bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { transformVertex( wkbPtr, ct, hasZValue ); } break; case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) transformVertex( wkbPtr, ct, hasZValue ); break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { int nRings; wkbPtr >> nRings; for ( int index = 0; index < nRings; ++index ) { int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) transformVertex( wkbPtr, ct, hasZValue ); } break; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; for ( int index = 0; index < nPoints; ++index ) { wkbPtr += 1 + sizeof( int ); transformVertex( wkbPtr, ct, hasZValue ); } break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int index = 0; index < nLines; ++index ) { wkbPtr += 1 + sizeof( int ); int nPoints; wkbPtr >> nPoints; for ( int index2 = 0; index2 < nPoints; ++index2 ) transformVertex( wkbPtr, ct, hasZValue ); } break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolys; wkbPtr >> nPolys; for ( int index = 0; index < nPolys; ++index ) { wkbPtr += 1 + sizeof( int ); //skip endian and polygon type int nRings; wkbPtr >> nRings; for ( int index2 = 0; index2 < nRings; ++index2 ) { int nPoints; wkbPtr >> nPoints; for ( int index3 = 0; index3 < nPoints; ++index3 ) transformVertex( wkbPtr, ct, hasZValue ); } } } default: break; } mDirtyGeos = true; return 0; } int QgsGeometry::splitGeometry( const QList<QgsPoint>& splitLine, QList<QgsGeometry*>& newGeometries, bool topological, QList<QgsPoint> &topologyTestPoints ) { int returnCode = 0; //return if this type is point/multipoint if ( type() == QGis::Point ) { return 1; //cannot split points } //make sure, mGeos and mWkb are there and up-to-date if ( mDirtyWkb ) exportGeosToWkb(); if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 1; if ( !GEOSisValid_r( geosinit.ctxt, mGeos ) ) return 7; //make sure splitLine is valid if (( type() == QGis::Line && splitLine.size() < 1 ) || ( type() == QGis::Polygon && splitLine.size() < 2 ) ) return 1; newGeometries.clear(); try { GEOSGeometry* splitLineGeos; if ( splitLine.size() > 1 ) { splitLineGeos = createGeosLineString( splitLine.toVector() ); } else if ( splitLine.size() == 1 ) { splitLineGeos = createGeosPoint( splitLine.at( 0 ) ); } else { return 1; } if ( !GEOSisValid_r( geosinit.ctxt, splitLineGeos ) || !GEOSisSimple_r( geosinit.ctxt, splitLineGeos ) ) { GEOSGeom_destroy_r( geosinit.ctxt, splitLineGeos ); return 1; } if ( topological ) { //find out candidate points for topological corrections if ( topologicalTestPointsSplit( splitLineGeos, topologyTestPoints ) != 0 ) return 1; } //call split function depending on geometry type if ( type() == QGis::Line ) { returnCode = splitLinearGeometry( splitLineGeos, newGeometries ); GEOSGeom_destroy_r( geosinit.ctxt, splitLineGeos ); } else if ( type() == QGis::Polygon ) { returnCode = splitPolygonGeometry( splitLineGeos, newGeometries ); GEOSGeom_destroy_r( geosinit.ctxt, splitLineGeos ); } else { return 1; } } CATCH_GEOS( 2 ) return returnCode; } /**Replaces a part of this geometry with another line*/ int QgsGeometry::reshapeGeometry( const QList<QgsPoint>& reshapeWithLine ) { if ( reshapeWithLine.size() < 2 ) return 1; if ( type() == QGis::Point ) return 1; //cannot reshape points GEOSGeometry* reshapeLineGeos = createGeosLineString( reshapeWithLine.toVector() ); //make sure this geos geometry is up-to-date if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 1; //single or multi? int numGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); if ( numGeoms == -1 ) return 1; bool isMultiGeom = false; int geosTypeId = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); if ( geosTypeId == GEOS_MULTILINESTRING || geosTypeId == GEOS_MULTIPOLYGON ) isMultiGeom = true; bool isLine = ( type() == QGis::Line ); //polygon or multipolygon? if ( !isMultiGeom ) { GEOSGeometry* reshapedGeometry; if ( isLine ) reshapedGeometry = reshapeLine( mGeos, reshapeLineGeos ); else reshapedGeometry = reshapePolygon( mGeos, reshapeLineGeos ); GEOSGeom_destroy_r( geosinit.ctxt, reshapeLineGeos ); if ( reshapedGeometry ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = reshapedGeometry; mDirtyWkb = true; return 0; } else { return 1; } } else { //call reshape for each geometry part and replace mGeos with new geometry if reshape took place bool reshapeTookPlace = false; GEOSGeometry* currentReshapeGeometry = 0; GEOSGeometry** newGeoms = new GEOSGeometry*[numGeoms]; for ( int i = 0; i < numGeoms; ++i ) { if ( isLine ) currentReshapeGeometry = reshapeLine( GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ), reshapeLineGeos ); else currentReshapeGeometry = reshapePolygon( GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ), reshapeLineGeos ); if ( currentReshapeGeometry ) { newGeoms[i] = currentReshapeGeometry; reshapeTookPlace = true; } else { newGeoms[i] = GEOSGeom_clone_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ) ); } } GEOSGeom_destroy_r( geosinit.ctxt, reshapeLineGeos ); GEOSGeometry* newMultiGeom = 0; if ( isLine ) { newMultiGeom = GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTILINESTRING, newGeoms, numGeoms ); } else //multipolygon { newMultiGeom = GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTIPOLYGON, newGeoms, numGeoms ); } delete[] newGeoms; if ( !newMultiGeom ) return 3; if ( reshapeTookPlace ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = newMultiGeom; mDirtyWkb = true; return 0; } else { GEOSGeom_destroy_r( geosinit.ctxt, newMultiGeom ); return 1; } } } int QgsGeometry::makeDifference( QgsGeometry* other ) { //make sure geos geometry is up to date if ( !other ) return 1; if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 1; if ( !GEOSisValid_r( geosinit.ctxt, mGeos ) ) return 2; if ( !GEOSisSimple_r( geosinit.ctxt, mGeos ) ) return 3; //convert other geometry to geos if ( other->mDirtyGeos ) other->exportWkbToGeos(); if ( !other->mGeos ) return 4; //make geometry::difference try { if ( GEOSIntersects_r( geosinit.ctxt, mGeos, other->mGeos ) ) { //check if multitype before and after bool multiType = isMultipart(); mGeos = GEOSDifference_r( geosinit.ctxt, mGeos, other->mGeos ); mDirtyWkb = true; if ( multiType && !isMultipart() ) { convertToMultiType(); exportWkbToGeos(); } } else { return 0; //nothing to do } } CATCH_GEOS( 5 ) if ( !mGeos ) { mDirtyGeos = true; return 6; } return 0; } QgsRectangle QgsGeometry::boundingBox() const { double xmin = std::numeric_limits<double>::max(); double ymin = std::numeric_limits<double>::max(); double xmax = -std::numeric_limits<double>::max(); double ymax = -std::numeric_limits<double>::max(); // TODO: implement with GEOS if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); // Return minimal QgsRectangle QgsRectangle invalidRect; invalidRect.setMinimal(); return invalidRect; } bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; // consider endian when fetching feature type switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { double x, y; wkbPtr >> x >> y; if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } break; case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { wkbPtr += 1 + sizeof( int ); double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } break; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { // get number of points in the line int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { // each of these is a wbklinestring so must handle as such wkbPtr += 1 + sizeof( int ); // skip type since we know its 2 int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } } break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { // get number of rings in the polygon int nRings; wkbPtr >> nRings; for ( int idx = 0; idx < nRings; idx++ ) { // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { // add points to a point array for drawing the polygon double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } } break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { // get the number of polygons int nPolygons; wkbPtr >> nPolygons; for ( int kdx = 0; kdx < nPolygons; kdx++ ) { //skip the endian and mGeometry type info and // get number of rings in the polygon wkbPtr += 1 + sizeof( int ); int nRings; wkbPtr >> nRings; for ( int idx = 0; idx < nRings; idx++ ) { // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { // add points to a point array for drawing the polygon double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( x < xmin ) xmin = x; if ( x > xmax ) xmax = x; if ( y < ymin ) ymin = y; if ( y > ymax ) ymax = y; } } } break; } default: QgsDebugMsg( QString( "Unknown WkbType %1 ENCOUNTERED" ).arg( wkbType ) ); return QgsRectangle( 0, 0, 0, 0 ); break; } return QgsRectangle( xmin, ymin, xmax, ymax ); } bool QgsGeometry::intersects( const QgsRectangle& r ) const { QgsGeometry* g = fromRect( r ); bool res = intersects( g ); delete g; return res; } bool QgsGeometry::intersects( const QgsGeometry* geometry ) const { if ( !geometry ) return false; try // geos might throw exception on error { // ensure that both geometries have geos geometry exportWkbToGeos(); geometry->exportWkbToGeos(); if ( !mGeos || !geometry->mGeos ) { QgsDebugMsg( "GEOS geometry not available!" ); return false; } return GEOSIntersects_r( geosinit.ctxt, mGeos, geometry->mGeos ); } CATCH_GEOS( false ) } bool QgsGeometry::contains( const QgsPoint* p ) const { exportWkbToGeos(); if ( !p ) { QgsDebugMsg( "pointer p is 0" ); return false; } if ( !mGeos ) { QgsDebugMsg( "GEOS geometry not available!" ); return false; } GEOSGeometry *geosPoint = 0; bool returnval = false; try { geosPoint = createGeosPoint( *p ); returnval = GEOSContains_r( geosinit.ctxt, mGeos, geosPoint ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); returnval = false; } if ( geosPoint ) GEOSGeom_destroy_r( geosinit.ctxt, geosPoint ); return returnval; } bool QgsGeometry::geosRelOp( char( *op )( GEOSContextHandle_t handle, const GEOSGeometry*, const GEOSGeometry * ), const QgsGeometry *a, const QgsGeometry *b ) { if ( !a || !b ) return false; try // geos might throw exception on error { // ensure that both geometries have geos geometry a->exportWkbToGeos(); b->exportWkbToGeos(); if ( !a->mGeos || !b->mGeos ) { QgsDebugMsg( "GEOS geometry not available!" ); return false; } return op( geosinit.ctxt, a->mGeos, b->mGeos ); } CATCH_GEOS( false ) } bool QgsGeometry::contains( const QgsGeometry* geometry ) const { return geosRelOp( GEOSContains_r, this, geometry ); } bool QgsGeometry::disjoint( const QgsGeometry* geometry ) const { return geosRelOp( GEOSDisjoint_r, this, geometry ); } bool QgsGeometry::equals( const QgsGeometry* geometry ) const { return geosRelOp( GEOSEquals_r, this, geometry ); } bool QgsGeometry::touches( const QgsGeometry* geometry ) const { return geosRelOp( GEOSTouches_r, this, geometry ); } bool QgsGeometry::overlaps( const QgsGeometry* geometry ) const { return geosRelOp( GEOSOverlaps_r, this, geometry ); } bool QgsGeometry::within( const QgsGeometry* geometry ) const { return geosRelOp( GEOSWithin_r, this, geometry ); } bool QgsGeometry::crosses( const QgsGeometry* geometry ) const { return geosRelOp( GEOSCrosses_r, this, geometry ); } QString QgsGeometry::exportToWkt( const int &precision ) const { QgsDebugMsg( "entered." ); // TODO: implement with GEOS if ( mDirtyWkb ) { exportGeosToWkb(); } if ( !mGeometry || wkbSize() < 5 ) { QgsDebugMsg( "WKB geometry not available or too short!" ); return QString::null; } bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; QString wkt; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { double x, y; wkbPtr >> x >> y; wkt += "POINT(" + qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ) + ")"; return wkt; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { int nPoints; wkbPtr >> nPoints; wkt += "LINESTRING("; // get number of points in the line for ( int idx = 0; idx < nPoints; ++idx ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); if ( idx != 0 ) wkt += ", "; wkt += qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ); } wkt += ")"; return wkt; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { wkt += "POLYGON("; // get number of rings in the polygon int nRings; wkbPtr >> nRings; if ( nRings == 0 ) // sanity check for zero rings in polygon return QString(); for ( int idx = 0; idx < nRings; idx++ ) { if ( idx != 0 ) wkt += ","; wkt += "("; // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) wkt += ","; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ); } wkt += ")"; } wkt += ")"; return wkt; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { int nPoints; wkbPtr >> nPoints; wkt += "MULTIPOINT("; for ( int idx = 0; idx < nPoints; ++idx ) { wkbPtr += 1 + sizeof( int ); if ( idx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ); } wkt += ")"; return wkt; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { int nLines; wkbPtr >> nLines; wkt += "MULTILINESTRING("; for ( int jdx = 0; jdx < nLines; jdx++ ) { if ( jdx != 0 ) wkt += ", "; wkt += "("; wkbPtr += 1 + sizeof( int ); // skip type since we know its 2 int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { if ( idx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ); } wkt += ")"; } wkt += ")"; return wkt; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { int nPolygons; wkbPtr >> nPolygons; wkt += "MULTIPOLYGON("; for ( int kdx = 0; kdx < nPolygons; kdx++ ) { if ( kdx != 0 ) wkt += ","; wkt += "("; wkbPtr += 1 + sizeof( int ); int nRings; wkbPtr >> nRings; for ( int idx = 0; idx < nRings; idx++ ) { if ( idx != 0 ) wkt += ","; wkt += "("; int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) wkt += ","; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += qgsDoubleToString( x, precision ) + " " + qgsDoubleToString( y, precision ); } wkt += ")"; } wkt += ")"; } wkt += ")"; return wkt; } default: QgsDebugMsg( "error: mGeometry type not recognized" ); return QString::null; } } QString QgsGeometry::exportToGeoJSON( const int &precision ) const { QgsDebugMsg( "entered." ); // TODO: implement with GEOS if ( mDirtyWkb ) exportGeosToWkb(); if ( !mGeometry ) { QgsDebugMsg( "WKB geometry not available!" ); return QString::null; } QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; bool hasZValue = false; QString wkt; switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { double x, y; wkbPtr >> x >> y; wkt += "{ \"type\": \"Point\", \"coordinates\": [" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "] }"; return wkt; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { wkt += "{ \"type\": \"LineString\", \"coordinates\": [ "; // get number of points in the line int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; ++idx ) { if ( idx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += "[" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "]"; } wkt += " ] }"; return wkt; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { wkt += "{ \"type\": \"Polygon\", \"coordinates\": [ "; // get number of rings in the polygon int nRings; wkbPtr >> nRings; if ( nRings == 0 ) // sanity check for zero rings in polygon return QString(); for ( int idx = 0; idx < nRings; idx++ ) { if ( idx != 0 ) wkt += ", "; wkt += "[ "; // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += "[" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "]"; } wkt += " ]"; } wkt += " ] }"; return wkt; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { wkt += "{ \"type\": \"MultiPoint\", \"coordinates\": [ "; int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; ++idx ) { wkbPtr += 1 + sizeof( int ); if ( idx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += "[" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "]"; } wkt += " ] }"; return wkt; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { wkt += "{ \"type\": \"MultiLineString\", \"coordinates\": [ "; int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { if ( jdx != 0 ) wkt += ", "; wkt += "[ "; wkbPtr += 1 + sizeof( int ); // skip type since we know its 2 int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { if ( idx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += "[" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "]"; } wkt += " ]"; } wkt += " ] }"; return wkt; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { wkt += "{ \"type\": \"MultiPolygon\", \"coordinates\": [ "; int nPolygons; wkbPtr >> nPolygons; for ( int kdx = 0; kdx < nPolygons; kdx++ ) { if ( kdx != 0 ) wkt += ", "; wkt += "[ "; wkbPtr += 1 + sizeof( int ); int nRings; wkbPtr >> nRings; for ( int idx = 0; idx < nRings; idx++ ) { if ( idx != 0 ) wkt += ", "; wkt += "[ "; int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { if ( jdx != 0 ) wkt += ", "; double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); wkt += "[" + qgsDoubleToString( x, precision ) + ", " + qgsDoubleToString( y, precision ) + "]"; } wkt += " ]"; } wkt += " ]"; } wkt += " ] }"; return wkt; } default: QgsDebugMsg( "error: mGeometry type not recognized" ); return QString::null; } } bool QgsGeometry::exportWkbToGeos() const { QgsDebugMsgLevel( "entered.", 3 ); if ( !mDirtyGeos ) { // No need to convert again return true; } if ( mGeos ) { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = 0; } // this probably shouldn't return true if ( !mGeometry ) { // no WKB => no GEOS mDirtyGeos = false; return true; } bool hasZValue = false; QgsWkbPtr wkbPtr( mGeometry + 1 ); QGis::WkbType wkbType; wkbPtr >> wkbType; try { switch ( wkbType ) { case QGis::WKBPoint25D: case QGis::WKBPoint: { double x, y; wkbPtr >> x >> y; mGeos = createGeosPoint( QgsPoint( x, y ) ); mDirtyGeos = false; break; } case QGis::WKBMultiPoint25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPoint: { QVector<GEOSGeometry *> points; int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { double x, y; wkbPtr += 1 + sizeof( int ); wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); points << createGeosPoint( QgsPoint( x, y ) ); } mGeos = createGeosCollection( GEOS_MULTIPOINT, points ); mDirtyGeos = false; break; } case QGis::WKBLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBLineString: { QgsPolyline sequence; int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); sequence << QgsPoint( x, y ); } mDirtyGeos = false; mGeos = createGeosLineString( sequence ); break; } case QGis::WKBMultiLineString25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiLineString: { QVector<GEOSGeometry*> lines; int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { QgsPolyline sequence; // each of these is a wbklinestring so must handle as such wkbPtr += 1 + sizeof( int ); // skip type since we know its 2 int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; idx++ ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); sequence << QgsPoint( x, y ); } // ignore invalid parts, it can come from ST_Simplify operations if ( sequence.count() > 1 ) lines << createGeosLineString( sequence ); } mGeos = createGeosCollection( GEOS_MULTILINESTRING, lines ); mDirtyGeos = false; break; } case QGis::WKBPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBPolygon: { // get number of rings in the polygon int nRings; wkbPtr >> nRings; QVector<GEOSGeometry*> rings; for ( int idx = 0; idx < nRings; idx++ ) { //QgsDebugMsg("Ring nr: "+QString::number(idx)); QgsPolyline sequence; // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { // add points to a point array for drawing the polygon double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); sequence << QgsPoint( x, y ); } GEOSGeometry *ring = createGeosLinearRing( sequence ); if ( ring ) rings << ring; } mGeos = createGeosPolygon( rings ); mDirtyGeos = false; break; } case QGis::WKBMultiPolygon25D: hasZValue = true; //intentional fall-through case QGis::WKBMultiPolygon: { QVector<GEOSGeometry*> polygons; // get the number of polygons int nPolygons; wkbPtr >> nPolygons; for ( int kdx = 0; kdx < nPolygons; kdx++ ) { //QgsDebugMsg("Polygon nr: "+QString::number(kdx)); QVector<GEOSGeometry*> rings; //skip the endian and mGeometry type info and // get number of rings in the polygon wkbPtr += 1 + sizeof( int ); int numRings; wkbPtr >> numRings; for ( int idx = 0; idx < numRings; idx++ ) { //QgsDebugMsg("Ring nr: "+QString::number(idx)); QgsPolyline sequence; // get number of points in the ring int nPoints; wkbPtr >> nPoints; for ( int jdx = 0; jdx < nPoints; jdx++ ) { // add points to a point array for drawing the polygon double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); sequence << QgsPoint( x, y ); } GEOSGeometry *ring = createGeosLinearRing( sequence ); if ( ring ) rings << ring; } GEOSGeometry *polygon = createGeosPolygon( rings ); if ( polygon ) polygons << polygon; } mGeos = createGeosCollection( GEOS_MULTIPOLYGON, polygons ); mDirtyGeos = false; break; } default: return false; } } CATCH_GEOS( false ) return true; } bool QgsGeometry::exportGeosToWkb() const { //QgsDebugMsg("entered."); if ( !mDirtyWkb ) { // No need to convert again return true; } // clear the WKB, ready to replace with the new one if ( mGeometry ) { delete [] mGeometry; mGeometry = 0; } if ( !mGeos ) { // GEOS is null, therefore WKB is null. mDirtyWkb = false; return true; } // set up byteOrder char byteOrder = QgsApplication::endian(); switch ( GEOSGeomTypeId_r( geosinit.ctxt, mGeos ) ) { case GEOS_POINT: // a point { mGeometrySize = 1 + sizeof( int ) + 2 * sizeof( double ); mGeometry = new unsigned char[mGeometrySize]; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, mGeos ); double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, 0, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, 0, &y ); QgsWkbPtr wkbPtr( mGeometry ); wkbPtr << byteOrder << QGis::WKBPoint << x << y; mDirtyWkb = false; return true; } // case GEOS_GEOM::GEOS_POINT case GEOS_LINESTRING: // a linestring { //QgsDebugMsg("Got a geos::GEOS_LINESTRING."); const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, mGeos ); unsigned int nPoints; GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &nPoints ); // allocate some space for the WKB mGeometrySize = 1 + // sizeof(byte) sizeof( int ) + sizeof( int ) + (( sizeof( double ) + sizeof( double ) ) * nPoints ); mGeometry = new unsigned char[mGeometrySize]; QgsWkbPtr wkbPtr( mGeometry ); wkbPtr << byteOrder << QGis::WKBLineString << nPoints; const GEOSCoordSequence *sequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, mGeos ); // assign points for ( unsigned int n = 0; n < nPoints; n++ ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, sequence, n, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, sequence, n, &y ); wkbPtr << x << y; } mDirtyWkb = false; return true; // TODO: Deal with endian-ness } // case GEOS_GEOM::GEOS_LINESTRING case GEOS_LINEARRING: // a linear ring (linestring with 1st point == last point) { // TODO break; } // case GEOS_GEOM::GEOS_LINEARRING case GEOS_POLYGON: // a polygon { int nPointsInRing = 0; //first calculate the geometry size int geometrySize = 1 + 2 * sizeof( int ); //endian, type, number of rings const GEOSGeometry *theRing = GEOSGetExteriorRing_r( geosinit.ctxt, mGeos ); if ( theRing ) { geometrySize += sizeof( int ); geometrySize += getNumGeosPoints( theRing ) * 2 * sizeof( double ); } for ( int i = 0; i < GEOSGetNumInteriorRings_r( geosinit.ctxt, mGeos ); ++i ) { geometrySize += sizeof( int ); //number of points in ring theRing = GEOSGetInteriorRingN_r( geosinit.ctxt, mGeos, i ); if ( theRing ) { geometrySize += getNumGeosPoints( theRing ) * 2 * sizeof( double ); } } mGeometry = new unsigned char[geometrySize]; mGeometrySize = geometrySize; //then fill the geometry itself into the wkb QgsWkbPtr wkbPtr( mGeometry ); int nRings = GEOSGetNumInteriorRings_r( geosinit.ctxt, mGeos ) + 1; wkbPtr << byteOrder << QGis::WKBPolygon << nRings; //exterior ring first theRing = GEOSGetExteriorRing_r( geosinit.ctxt, mGeos ); if ( theRing ) { nPointsInRing = getNumGeosPoints( theRing ); wkbPtr << nPointsInRing; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, theRing ); unsigned int n; GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &n ); for ( unsigned int j = 0; j < n; ++j ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, j, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, j, &y ); wkbPtr << x << y; } } //interior rings after for ( int i = 0; i < GEOSGetNumInteriorRings_r( geosinit.ctxt, mGeos ); i++ ) { theRing = GEOSGetInteriorRingN_r( geosinit.ctxt, mGeos, i ); const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, theRing ); unsigned int nPointsInRing; GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &nPointsInRing ); wkbPtr << nPointsInRing; for ( unsigned int j = 0; j < nPointsInRing; j++ ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, j, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, j, &y ); wkbPtr << x << y; } } mDirtyWkb = false; return true; } // case GEOS_GEOM::GEOS_POLYGON break; case GEOS_MULTIPOINT: // a collection of points { // determine size of geometry int geometrySize = 1 + 2 * sizeof( int ); for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { geometrySize += 1 + sizeof( int ) + 2 * sizeof( double ); } mGeometry = new unsigned char[geometrySize]; mGeometrySize = geometrySize; QgsWkbPtr wkbPtr( mGeometry ); int numPoints = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); wkbPtr << byteOrder << QGis::WKBMultiPoint << numPoints; for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { //copy endian and point type wkbPtr << byteOrder << QGis::WKBPoint; const GEOSGeometry *currentPoint = GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, currentPoint ); double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, 0, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, 0, &y ); wkbPtr << x << y; } mDirtyWkb = false; return true; } // case GEOS_GEOM::GEOS_MULTIPOINT case GEOS_MULTILINESTRING: // a collection of linestrings { // determine size of geometry int geometrySize = 1 + 2 * sizeof( int ); for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { geometrySize += 1 + 2 * sizeof( int ); geometrySize += getNumGeosPoints( GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ) ) * 2 * sizeof( double ); } mGeometry = new unsigned char[geometrySize]; mGeometrySize = geometrySize; QgsWkbPtr wkbPtr( mGeometry ); int numLines = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); wkbPtr << byteOrder << QGis::WKBMultiLineString << numLines; //loop over lines for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { //endian and type WKBLineString wkbPtr << byteOrder << QGis::WKBLineString; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ) ); //line size unsigned int lineSize; GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &lineSize ); wkbPtr << lineSize; //vertex coordinates for ( unsigned int j = 0; j < lineSize; ++j ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, j, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, j, &y ); wkbPtr << x << y; } } mDirtyWkb = false; return true; } // case GEOS_GEOM::GEOS_MULTILINESTRING case GEOS_MULTIPOLYGON: // a collection of polygons { //first determine size of geometry int geometrySize = 1 + 2 * sizeof( int ); //endian, type, number of polygons for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { const GEOSGeometry *thePoly = GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); geometrySize += 1 + 2 * sizeof( int ); //endian, type, number of rings //exterior ring geometrySize += sizeof( int ); //number of points in exterior ring const GEOSGeometry *exRing = GEOSGetExteriorRing_r( geosinit.ctxt, thePoly ); geometrySize += 2 * sizeof( double ) * getNumGeosPoints( exRing ); const GEOSGeometry *intRing = 0; for ( int j = 0; j < GEOSGetNumInteriorRings_r( geosinit.ctxt, thePoly ); j++ ) { geometrySize += sizeof( int ); //number of points in ring intRing = GEOSGetInteriorRingN_r( geosinit.ctxt, thePoly, j ); geometrySize += 2 * sizeof( double ) * getNumGeosPoints( intRing ); } } mGeometry = new unsigned char[geometrySize]; mGeometrySize = geometrySize; QgsWkbPtr wkbPtr( mGeometry ); int numPolygons = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); wkbPtr << byteOrder << QGis::WKBMultiPolygon << numPolygons; //loop over polygons for ( int i = 0; i < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); i++ ) { const GEOSGeometry *thePoly = GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); int numRings = GEOSGetNumInteriorRings_r( geosinit.ctxt, thePoly ) + 1; //exterior ring const GEOSGeometry *theRing = GEOSGetExteriorRing_r( geosinit.ctxt, thePoly ); int nPointsInRing = getNumGeosPoints( theRing ); wkbPtr << byteOrder << QGis::WKBPolygon << numRings << nPointsInRing; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, theRing ); for ( int k = 0; k < nPointsInRing; ++k ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, k, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, k, &y ); wkbPtr << x << y; } //interior rings for ( int j = 0; j < GEOSGetNumInteriorRings_r( geosinit.ctxt, thePoly ); j++ ) { theRing = GEOSGetInteriorRingN_r( geosinit.ctxt, thePoly, j ); int nPointsInRing = getNumGeosPoints( theRing ); wkbPtr << nPointsInRing; const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, theRing ); for ( int k = 0; k < nPointsInRing; ++k ) { double x, y; GEOSCoordSeq_getX_r( geosinit.ctxt, cs, k, &x ); GEOSCoordSeq_getY_r( geosinit.ctxt, cs, k, &y ); wkbPtr << x << y; } } } mDirtyWkb = false; return true; } // case GEOS_GEOM::GEOS_MULTIPOLYGON case GEOS_GEOMETRYCOLLECTION: // a collection of heterogeneus geometries { // TODO QgsDebugMsg( "geometry collection - not supported" ); break; } // case GEOS_GEOM::GEOS_GEOMETRYCOLLECTION } // switch (mGeos->getGeometryTypeId()) return false; } QgsGeometry* QgsGeometry::convertToType( QGis::GeometryType destType, bool destMultipart ) const { switch ( destType ) { case QGis::Point: return convertToPoint( destMultipart ); case QGis::Line: return convertToLine( destMultipart ); case QGis::Polygon: return convertToPolygon( destMultipart ); default: return 0; } } bool QgsGeometry::convertToMultiType() { // TODO: implement with GEOS if ( mDirtyWkb ) { exportGeosToWkb(); } if ( !mGeometry ) { return false; } QGis::WkbType geomType = wkbType(); if ( geomType == QGis::WKBMultiPoint || geomType == QGis::WKBMultiPoint25D || geomType == QGis::WKBMultiLineString || geomType == QGis::WKBMultiLineString25D || geomType == QGis::WKBMultiPolygon || geomType == QGis::WKBMultiPolygon25D || geomType == QGis::WKBUnknown ) { return false; //no need to convert } size_t newGeomSize = mGeometrySize + 1 + 2 * sizeof( int ); //endian: 1, multitype: sizeof(int), number of geometries: sizeof(int) unsigned char* newGeometry = new unsigned char[newGeomSize]; //copy endian char byteOrder = QgsApplication::endian(); QgsWkbPtr wkbPtr( newGeometry ); wkbPtr << byteOrder; //copy wkbtype //todo QGis::WkbType newMultiType; switch ( geomType ) { case QGis::WKBPoint: newMultiType = QGis::WKBMultiPoint; break; case QGis::WKBPoint25D: newMultiType = QGis::WKBMultiPoint25D; break; case QGis::WKBLineString: newMultiType = QGis::WKBMultiLineString; break; case QGis::WKBLineString25D: newMultiType = QGis::WKBMultiLineString25D; break; case QGis::WKBPolygon: newMultiType = QGis::WKBMultiPolygon; break; case QGis::WKBPolygon25D: newMultiType = QGis::WKBMultiPolygon25D; break; default: delete [] newGeometry; return false; } wkbPtr << newMultiType << 1; //copy the existing single geometry memcpy( wkbPtr, mGeometry, mGeometrySize ); delete [] mGeometry; mGeometry = newGeometry; mGeometrySize = newGeomSize; mDirtyGeos = true; return true; } void QgsGeometry::transformVertex( QgsWkbPtr &wkbPtr, const QTransform& trans, bool hasZValue ) { qreal x, y, rotated_x, rotated_y; QgsWkbPtr tmp = wkbPtr; tmp >> x >> y; trans.map( x, y, &rotated_x, &rotated_y ); wkbPtr << rotated_x << rotated_y; if ( hasZValue ) wkbPtr += sizeof( double ); } void QgsGeometry::transformVertex( QgsWkbPtr &wkbPtr, const QgsCoordinateTransform& ct, bool hasZValue ) { double x, y, z = 0.0; QgsWkbPtr tmp = wkbPtr; tmp >> x >> y; ct.transformInPlace( x, y, z ); wkbPtr << x << y; if ( hasZValue ) wkbPtr += sizeof( double ); } GEOSGeometry* QgsGeometry::linePointDifference( GEOSGeometry* GEOSsplitPoint ) { int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); QgsMultiPolyline multiLine; if ( type == GEOS_MULTILINESTRING ) multiLine = asMultiPolyline(); else if ( type == GEOS_LINESTRING ) multiLine = QgsMultiPolyline() << asPolyline(); else return 0; // GEOSsplitPoint will be deleted in the caller, so make a clone QgsGeometry* geosPoint = fromGeosGeom( GEOSGeom_clone_r( geosinit.ctxt, GEOSsplitPoint ) ); QgsPoint splitPoint = geosPoint->asPoint(); delete geosPoint; QgsMultiPolyline lines; QgsPolyline line; QgsPolyline newline; //For each part for ( int i = 0; i < multiLine.size() ; ++i ) { line = multiLine[i]; newline = QgsPolyline(); newline.append( line[0] ); //For each segment for ( int j = 1; j < line.size() - 1 ; ++j ) { newline.append( line[j] ); if ( line[j] == splitPoint ) { lines.append( newline ); newline = QgsPolyline(); newline.append( line[j] ); } } newline.append( line.last() ); lines.append( newline ); } QgsGeometry* splitLines = fromMultiPolyline( lines ); GEOSGeometry* splitGeom = GEOSGeom_clone_r( geosinit.ctxt, splitLines->asGeos() ); delete splitLines; return splitGeom; } int QgsGeometry::splitLinearGeometry( GEOSGeometry *splitLine, QList<QgsGeometry*>& newGeometries ) { if ( !splitLine ) return 2; if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 5; //first test if linestring intersects geometry. If not, return straight away if ( !GEOSIntersects_r( geosinit.ctxt, splitLine, mGeos ) ) return 1; //check that split line has no linear intersection int linearIntersect = GEOSRelatePattern_r( geosinit.ctxt, mGeos, splitLine, "1********" ); if ( linearIntersect > 0 ) return 3; int splitGeomType = GEOSGeomTypeId_r( geosinit.ctxt, splitLine ); GEOSGeometry* splitGeom; if ( splitGeomType == GEOS_POINT ) { splitGeom = linePointDifference( splitLine ); } else { splitGeom = GEOSDifference_r( geosinit.ctxt, mGeos, splitLine ); } QVector<GEOSGeometry*> lineGeoms; int splitType = GEOSGeomTypeId_r( geosinit.ctxt, splitGeom ); if ( splitType == GEOS_MULTILINESTRING ) { int nGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, splitGeom ); for ( int i = 0; i < nGeoms; ++i ) lineGeoms << GEOSGeom_clone_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, splitGeom, i ) ); } else { lineGeoms << GEOSGeom_clone_r( geosinit.ctxt, splitGeom ); } mergeGeometriesMultiTypeSplit( lineGeoms ); if ( lineGeoms.size() > 0 ) { fromGeos( lineGeoms[0] ); } for ( int i = 1; i < lineGeoms.size(); ++i ) { newGeometries << fromGeosGeom( lineGeoms[i] ); } GEOSGeom_destroy_r( geosinit.ctxt, splitGeom ); return 0; } int QgsGeometry::splitPolygonGeometry( GEOSGeometry* splitLine, QList<QgsGeometry*>& newGeometries ) { if ( !splitLine ) return 2; if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 5; //first test if linestring intersects geometry. If not, return straight away if ( !GEOSIntersects_r( geosinit.ctxt, splitLine, mGeos ) ) return 1; //first union all the polygon rings together (to get them noded, see JTS developer guide) GEOSGeometry *nodedGeometry = nodeGeometries( splitLine, mGeos ); if ( !nodedGeometry ) return 2; //an error occured during noding GEOSGeometry *polygons = GEOSPolygonize_r( geosinit.ctxt, &nodedGeometry, 1 ); if ( !polygons || numberOfGeometries( polygons ) == 0 ) { if ( polygons ) GEOSGeom_destroy_r( geosinit.ctxt, polygons ); GEOSGeom_destroy_r( geosinit.ctxt, nodedGeometry ); return 4; } GEOSGeom_destroy_r( geosinit.ctxt, nodedGeometry ); //test every polygon if contained in original geometry //include in result if yes QVector<GEOSGeometry*> testedGeometries; GEOSGeometry *intersectGeometry = 0; //ratio intersect geometry / geometry. This should be close to 1 //if the polygon belongs to the input geometry for ( int i = 0; i < numberOfGeometries( polygons ); i++ ) { const GEOSGeometry *polygon = GEOSGetGeometryN_r( geosinit.ctxt, polygons, i ); intersectGeometry = GEOSIntersection_r( geosinit.ctxt, mGeos, polygon ); if ( !intersectGeometry ) { QgsDebugMsg( "intersectGeometry is NULL" ); continue; } double intersectionArea; GEOSArea_r( geosinit.ctxt, intersectGeometry, &intersectionArea ); double polygonArea; GEOSArea_r( geosinit.ctxt, polygon, &polygonArea ); const double areaRatio = intersectionArea / polygonArea; if ( areaRatio > 0.99 && areaRatio < 1.01 ) testedGeometries << GEOSGeom_clone_r( geosinit.ctxt, polygon ); GEOSGeom_destroy_r( geosinit.ctxt, intersectGeometry ); } bool splitDone = true; int nGeometriesThis = numberOfGeometries( mGeos ); //original number of geometries if ( testedGeometries.size() == nGeometriesThis ) { splitDone = false; } mergeGeometriesMultiTypeSplit( testedGeometries ); //no split done, preserve original geometry if ( !splitDone ) { for ( int i = 0; i < testedGeometries.size(); ++i ) { GEOSGeom_destroy_r( geosinit.ctxt, testedGeometries[i] ); } return 1; } else if ( testedGeometries.size() > 0 ) //split successfull { GEOSGeom_destroy_r( geosinit.ctxt, mGeos ); mGeos = testedGeometries[0]; mDirtyWkb = true; } int i; for ( i = 1; i < testedGeometries.size() && GEOSisValid_r( geosinit.ctxt, testedGeometries[i] ); ++i ) ; if ( i < testedGeometries.size() ) { for ( i = 0; i < testedGeometries.size(); ++i ) GEOSGeom_destroy_r( geosinit.ctxt, testedGeometries[i] ); return 3; } for ( i = 1; i < testedGeometries.size(); ++i ) newGeometries << fromGeosGeom( testedGeometries[i] ); GEOSGeom_destroy_r( geosinit.ctxt, polygons ); return 0; } GEOSGeometry* QgsGeometry::reshapePolygon( const GEOSGeometry* polygon, const GEOSGeometry* reshapeLineGeos ) { //go through outer shell and all inner rings and check if there is exactly one intersection of a ring and the reshape line int nIntersections = 0; int lastIntersectingRing = -2; const GEOSGeometry* lastIntersectingGeom = 0; int nRings = GEOSGetNumInteriorRings_r( geosinit.ctxt, polygon ); if ( nRings < 0 ) return 0; //does outer ring intersect? const GEOSGeometry* outerRing = GEOSGetExteriorRing_r( geosinit.ctxt, polygon ); if ( GEOSIntersects_r( geosinit.ctxt, outerRing, reshapeLineGeos ) == 1 ) { ++nIntersections; lastIntersectingRing = -1; lastIntersectingGeom = outerRing; } //do inner rings intersect? const GEOSGeometry **innerRings = new const GEOSGeometry*[nRings]; try { for ( int i = 0; i < nRings; ++i ) { innerRings[i] = GEOSGetInteriorRingN_r( geosinit.ctxt, polygon, i ); if ( GEOSIntersects_r( geosinit.ctxt, innerRings[i], reshapeLineGeos ) == 1 ) { ++nIntersections; lastIntersectingRing = i; lastIntersectingGeom = innerRings[i]; } } } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); nIntersections = 0; } if ( nIntersections != 1 ) //reshape line is only allowed to intersect one ring { delete [] innerRings; return 0; } //we have one intersecting ring, let's try to reshape it GEOSGeometry* reshapeResult = reshapeLine( lastIntersectingGeom, reshapeLineGeos ); if ( !reshapeResult ) { delete [] innerRings; return 0; } //if reshaping took place, we need to reassemble the polygon and its rings GEOSGeometry* newRing = 0; const GEOSCoordSequence* reshapeSequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, reshapeResult ); GEOSCoordSequence* newCoordSequence = GEOSCoordSeq_clone_r( geosinit.ctxt, reshapeSequence ); GEOSGeom_destroy_r( geosinit.ctxt, reshapeResult ); try { newRing = GEOSGeom_createLinearRing_r( geosinit.ctxt, newCoordSequence ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); } if ( !newRing ) { delete [] innerRings; return 0; } GEOSGeometry* newOuterRing = 0; if ( lastIntersectingRing == -1 ) newOuterRing = newRing; else newOuterRing = GEOSGeom_clone_r( geosinit.ctxt, outerRing ); //check if all the rings are still inside the outer boundary QList<GEOSGeometry*> ringList; if ( nRings > 0 ) { GEOSGeometry* outerRingPoly = GEOSGeom_createPolygon_r( geosinit.ctxt, GEOSGeom_clone_r( geosinit.ctxt, newOuterRing ), 0, 0 ); if ( outerRingPoly ) { GEOSGeometry* currentRing = 0; for ( int i = 0; i < nRings; ++i ) { if ( lastIntersectingRing == i ) currentRing = newRing; else currentRing = GEOSGeom_clone_r( geosinit.ctxt, innerRings[i] ); //possibly a ring is no longer contained in the result polygon after reshape if ( GEOSContains_r( geosinit.ctxt, outerRingPoly, currentRing ) == 1 ) ringList.push_back( currentRing ); else GEOSGeom_destroy_r( geosinit.ctxt, currentRing ); } } GEOSGeom_destroy_r( geosinit.ctxt, outerRingPoly ); } GEOSGeometry** newInnerRings = new GEOSGeometry*[ringList.size()]; for ( int i = 0; i < ringList.size(); ++i ) newInnerRings[i] = ringList.at( i ); delete [] innerRings; GEOSGeometry* reshapedPolygon = GEOSGeom_createPolygon_r( geosinit.ctxt, newOuterRing, newInnerRings, ringList.size() ); delete[] newInnerRings; return reshapedPolygon; } GEOSGeometry* QgsGeometry::reshapeLine( const GEOSGeometry* line, const GEOSGeometry* reshapeLineGeos ) { if ( !line || !reshapeLineGeos ) return 0; bool atLeastTwoIntersections = false; try { //make sure there are at least two intersection between line and reshape geometry GEOSGeometry* intersectGeom = GEOSIntersection_r( geosinit.ctxt, line, reshapeLineGeos ); if ( intersectGeom ) { atLeastTwoIntersections = ( GEOSGeomTypeId_r( geosinit.ctxt, intersectGeom ) == GEOS_MULTIPOINT && GEOSGetNumGeometries_r( geosinit.ctxt, intersectGeom ) > 1 ); GEOSGeom_destroy_r( geosinit.ctxt, intersectGeom ); } } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); atLeastTwoIntersections = false; } if ( !atLeastTwoIntersections ) return 0; //begin and end point of original line const GEOSCoordSequence* lineCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, line ); if ( !lineCoordSeq ) return 0; unsigned int lineCoordSeqSize; if ( GEOSCoordSeq_getSize_r( geosinit.ctxt, lineCoordSeq, &lineCoordSeqSize ) == 0 ) return 0; if ( lineCoordSeqSize < 2 ) return 0; //first and last vertex of line double x1, y1, x2, y2; GEOSCoordSeq_getX_r( geosinit.ctxt, lineCoordSeq, 0, &x1 ); GEOSCoordSeq_getY_r( geosinit.ctxt, lineCoordSeq, 0, &y1 ); GEOSCoordSeq_getX_r( geosinit.ctxt, lineCoordSeq, lineCoordSeqSize - 1, &x2 ); GEOSCoordSeq_getY_r( geosinit.ctxt, lineCoordSeq, lineCoordSeqSize - 1, &y2 ); GEOSGeometry* beginLineVertex = createGeosPoint( QgsPoint( x1, y1 ) ); GEOSGeometry* endLineVertex = createGeosPoint( QgsPoint( x2, y2 ) ); bool isRing = false; if ( GEOSGeomTypeId_r( geosinit.ctxt, line ) == GEOS_LINEARRING || GEOSEquals_r( geosinit.ctxt, beginLineVertex, endLineVertex ) == 1 ) isRing = true; //node line and reshape line GEOSGeometry* nodedGeometry = nodeGeometries( reshapeLineGeos, line ); if ( !nodedGeometry ) { GEOSGeom_destroy_r( geosinit.ctxt, beginLineVertex ); GEOSGeom_destroy_r( geosinit.ctxt, endLineVertex ); return 0; } //and merge them together GEOSGeometry *mergedLines = GEOSLineMerge_r( geosinit.ctxt, nodedGeometry ); GEOSGeom_destroy_r( geosinit.ctxt, nodedGeometry ); if ( !mergedLines ) { GEOSGeom_destroy_r( geosinit.ctxt, beginLineVertex ); GEOSGeom_destroy_r( geosinit.ctxt, endLineVertex ); return 0; } int numMergedLines = GEOSGetNumGeometries_r( geosinit.ctxt, mergedLines ); if ( numMergedLines < 2 ) //some special cases. Normally it is >2 { GEOSGeom_destroy_r( geosinit.ctxt, beginLineVertex ); GEOSGeom_destroy_r( geosinit.ctxt, endLineVertex ); if ( numMergedLines == 1 ) //reshape line is from begin to endpoint. So we keep the reshapeline return GEOSGeom_clone_r( geosinit.ctxt, reshapeLineGeos ); else return 0; } QList<GEOSGeometry*> resultLineParts; //collection with the line segments that will be contained in result QList<GEOSGeometry*> probableParts; //parts where we can decide on inclusion only after going through all the candidates for ( int i = 0; i < numMergedLines; ++i ) { const GEOSGeometry* currentGeom; currentGeom = GEOSGetGeometryN_r( geosinit.ctxt, mergedLines, i ); const GEOSCoordSequence* currentCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, currentGeom ); unsigned int currentCoordSeqSize; GEOSCoordSeq_getSize_r( geosinit.ctxt, currentCoordSeq, &currentCoordSeqSize ); if ( currentCoordSeqSize < 2 ) continue; //get the two endpoints of the current line merge result double xBegin, xEnd, yBegin, yEnd; GEOSCoordSeq_getX_r( geosinit.ctxt, currentCoordSeq, 0, &xBegin ); GEOSCoordSeq_getY_r( geosinit.ctxt, currentCoordSeq, 0, &yBegin ); GEOSCoordSeq_getX_r( geosinit.ctxt, currentCoordSeq, currentCoordSeqSize - 1, &xEnd ); GEOSCoordSeq_getY_r( geosinit.ctxt, currentCoordSeq, currentCoordSeqSize - 1, &yEnd ); GEOSGeometry* beginCurrentGeomVertex = createGeosPoint( QgsPoint( xBegin, yBegin ) ); GEOSGeometry* endCurrentGeomVertex = createGeosPoint( QgsPoint( xEnd, yEnd ) ); //check how many endpoints of the line merge result are on the (original) line int nEndpointsOnOriginalLine = 0; if ( pointContainedInLine( beginCurrentGeomVertex, line ) == 1 ) nEndpointsOnOriginalLine += 1; if ( pointContainedInLine( endCurrentGeomVertex, line ) == 1 ) nEndpointsOnOriginalLine += 1; //check how many endpoints equal the endpoints of the original line int nEndpointsSameAsOriginalLine = 0; if ( GEOSEquals_r( geosinit.ctxt, beginCurrentGeomVertex, beginLineVertex ) == 1 || GEOSEquals_r( geosinit.ctxt, beginCurrentGeomVertex, endLineVertex ) == 1 ) nEndpointsSameAsOriginalLine += 1; if ( GEOSEquals_r( geosinit.ctxt, endCurrentGeomVertex, beginLineVertex ) == 1 || GEOSEquals_r( geosinit.ctxt, endCurrentGeomVertex, endLineVertex ) == 1 ) nEndpointsSameAsOriginalLine += 1; //check if the current geometry overlaps the original geometry (GEOSOverlap does not seem to work with linestrings) bool currentGeomOverlapsOriginalGeom = false; bool currentGeomOverlapsReshapeLine = false; if ( QgsGeometry::lineContainedInLine( currentGeom, line ) == 1 ) currentGeomOverlapsOriginalGeom = true; if ( QgsGeometry::lineContainedInLine( currentGeom, reshapeLineGeos ) == 1 ) currentGeomOverlapsReshapeLine = true; //logic to decide if this part belongs to the result if ( nEndpointsSameAsOriginalLine == 1 && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom ) { resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) ); } //for closed rings, we take one segment from the candidate list else if ( isRing && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom ) { probableParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) ); } else if ( nEndpointsOnOriginalLine == 2 && !currentGeomOverlapsOriginalGeom ) { resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) ); } else if ( nEndpointsSameAsOriginalLine == 2 && !currentGeomOverlapsOriginalGeom ) { resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) ); } else if ( currentGeomOverlapsOriginalGeom && currentGeomOverlapsReshapeLine ) { resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) ); } GEOSGeom_destroy_r( geosinit.ctxt, beginCurrentGeomVertex ); GEOSGeom_destroy_r( geosinit.ctxt, endCurrentGeomVertex ); } //add the longest segment from the probable list for rings (only used for polygon rings) if ( isRing && probableParts.size() > 0 ) { GEOSGeometry* maxGeom = 0; //the longest geometry in the probabla list GEOSGeometry* currentGeom = 0; double maxLength = -DBL_MAX; double currentLength = 0; for ( int i = 0; i < probableParts.size(); ++i ) { currentGeom = probableParts.at( i ); GEOSLength_r( geosinit.ctxt, currentGeom, &currentLength ); if ( currentLength > maxLength ) { maxLength = currentLength; GEOSGeom_destroy_r( geosinit.ctxt, maxGeom ); maxGeom = currentGeom; } else { GEOSGeom_destroy_r( geosinit.ctxt, currentGeom ); } } resultLineParts.push_back( maxGeom ); } GEOSGeom_destroy_r( geosinit.ctxt, beginLineVertex ); GEOSGeom_destroy_r( geosinit.ctxt, endLineVertex ); GEOSGeom_destroy_r( geosinit.ctxt, mergedLines ); GEOSGeometry* result = 0; if ( resultLineParts.size() < 1 ) return 0; if ( resultLineParts.size() == 1 ) //the whole result was reshaped { result = resultLineParts[0]; } else //>1 { GEOSGeometry **lineArray = new GEOSGeometry*[resultLineParts.size()]; for ( int i = 0; i < resultLineParts.size(); ++i ) { lineArray[i] = resultLineParts[i]; } //create multiline from resultLineParts GEOSGeometry* multiLineGeom = GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTILINESTRING, lineArray, resultLineParts.size() ); delete [] lineArray; //then do a linemerge with the newly combined partstrings result = GEOSLineMerge_r( geosinit.ctxt, multiLineGeom ); GEOSGeom_destroy_r( geosinit.ctxt, multiLineGeom ); } //now test if the result is a linestring. Otherwise something went wrong if ( GEOSGeomTypeId_r( geosinit.ctxt, result ) != GEOS_LINESTRING ) { GEOSGeom_destroy_r( geosinit.ctxt, result ); return 0; } return result; } int QgsGeometry::topologicalTestPointsSplit( const GEOSGeometry* splitLine, QList<QgsPoint>& testPoints ) const { //Find out the intersection points between splitLineGeos and this geometry. //These points need to be tested for topological correctness by the calling function //if topological editing is enabled testPoints.clear(); GEOSGeometry* intersectionGeom = GEOSIntersection_r( geosinit.ctxt, mGeos, splitLine ); if ( !intersectionGeom ) return 1; bool simple = false; int nIntersectGeoms = 1; if ( GEOSGeomTypeId_r( geosinit.ctxt, intersectionGeom ) == GEOS_LINESTRING || GEOSGeomTypeId_r( geosinit.ctxt, intersectionGeom ) == GEOS_POINT ) simple = true; if ( !simple ) nIntersectGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, intersectionGeom ); for ( int i = 0; i < nIntersectGeoms; ++i ) { const GEOSGeometry* currentIntersectGeom; if ( simple ) currentIntersectGeom = intersectionGeom; else currentIntersectGeom = GEOSGetGeometryN_r( geosinit.ctxt, intersectionGeom, i ); const GEOSCoordSequence* lineSequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, currentIntersectGeom ); unsigned int sequenceSize = 0; double x, y; if ( GEOSCoordSeq_getSize_r( geosinit.ctxt, lineSequence, &sequenceSize ) != 0 ) { for ( unsigned int i = 0; i < sequenceSize; ++i ) { if ( GEOSCoordSeq_getX_r( geosinit.ctxt, lineSequence, i, &x ) != 0 ) { if ( GEOSCoordSeq_getY_r( geosinit.ctxt, lineSequence, i, &y ) != 0 ) { testPoints.push_back( QgsPoint( x, y ) ); } } } } } GEOSGeom_destroy_r( geosinit.ctxt, intersectionGeom ); return 0; } GEOSGeometry *QgsGeometry::nodeGeometries( const GEOSGeometry *splitLine, const GEOSGeometry *geom ) { if ( !splitLine || !geom ) return 0; if ( GEOSGeomTypeId_r( geosinit.ctxt, geom ) == GEOS_POLYGON || GEOSGeomTypeId_r( geosinit.ctxt, geom ) == GEOS_MULTIPOLYGON ) { GEOSGeometry *geometryBoundary = GEOSBoundary_r( geosinit.ctxt, geom ); GEOSGeometry *unionGeometry = GEOSUnion_r( geosinit.ctxt, splitLine, geometryBoundary ); GEOSGeom_destroy_r( geosinit.ctxt, geometryBoundary ); return unionGeometry; } else { return GEOSUnion_r( geosinit.ctxt, splitLine, geom ); } } int QgsGeometry::lineContainedInLine( const GEOSGeometry* line1, const GEOSGeometry* line2 ) { if ( !line1 || !line2 ) { return -1; } double bufferDistance = pow( 10.0L, geomDigits( line2 ) - 11 ); GEOSGeometry* bufferGeom = GEOSBuffer_r( geosinit.ctxt, line2, bufferDistance, DEFAULT_QUADRANT_SEGMENTS ); if ( !bufferGeom ) return -2; GEOSGeometry* intersectionGeom = GEOSIntersection_r( geosinit.ctxt, bufferGeom, line1 ); //compare ratio between line1Length and intersectGeomLength (usually close to 1 if line1 is contained in line2) double intersectGeomLength; double line1Length; GEOSLength_r( geosinit.ctxt, intersectionGeom, &intersectGeomLength ); GEOSLength_r( geosinit.ctxt, line1, &line1Length ); GEOSGeom_destroy_r( geosinit.ctxt, bufferGeom ); GEOSGeom_destroy_r( geosinit.ctxt, intersectionGeom ); double intersectRatio = line1Length / intersectGeomLength; if ( intersectRatio > 0.9 && intersectRatio < 1.1 ) return 1; return 0; } int QgsGeometry::pointContainedInLine( const GEOSGeometry* point, const GEOSGeometry* line ) { if ( !point || !line ) return -1; double bufferDistance = pow( 10.0L, geomDigits( line ) - 11 ); GEOSGeometry* lineBuffer = GEOSBuffer_r( geosinit.ctxt, line, bufferDistance, 8 ); if ( !lineBuffer ) return -2; bool contained = false; if ( GEOSContains_r( geosinit.ctxt, lineBuffer, point ) == 1 ) contained = true; GEOSGeom_destroy_r( geosinit.ctxt, lineBuffer ); return contained; } int QgsGeometry::geomDigits( const GEOSGeometry* geom ) { GEOSGeometry* bbox = GEOSEnvelope_r( geosinit.ctxt, geom ); if ( !bbox ) return -1; const GEOSGeometry* bBoxRing = GEOSGetExteriorRing_r( geosinit.ctxt, bbox ); if ( !bBoxRing ) return -1; const GEOSCoordSequence* bBoxCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, bBoxRing ); if ( !bBoxCoordSeq ) return -1; unsigned int nCoords = 0; if ( !GEOSCoordSeq_getSize_r( geosinit.ctxt, bBoxCoordSeq, &nCoords ) ) return -1; int maxDigits = -1; for ( unsigned int i = 0; i < nCoords - 1; ++i ) { double t; GEOSCoordSeq_getX_r( geosinit.ctxt, bBoxCoordSeq, i, &t ); int digits; digits = ceil( log10( fabs( t ) ) ); if ( digits > maxDigits ) maxDigits = digits; GEOSCoordSeq_getY_r( geosinit.ctxt, bBoxCoordSeq, i, &t ); digits = ceil( log10( fabs( t ) ) ); if ( digits > maxDigits ) maxDigits = digits; } return maxDigits; } int QgsGeometry::numberOfGeometries( GEOSGeometry* g ) const { if ( !g ) return 0; int geometryType = GEOSGeomTypeId_r( geosinit.ctxt, g ); if ( geometryType == GEOS_POINT || geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING || geometryType == GEOS_POLYGON ) return 1; //calling GEOSGetNumGeometries is save for multi types and collections also in geos2 return GEOSGetNumGeometries_r( geosinit.ctxt, g ); } int QgsGeometry::mergeGeometriesMultiTypeSplit( QVector<GEOSGeometry*>& splitResult ) { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 1; //convert mGeos to geometry collection int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); if ( type != GEOS_GEOMETRYCOLLECTION && type != GEOS_MULTILINESTRING && type != GEOS_MULTIPOLYGON && type != GEOS_MULTIPOINT ) return 0; QVector<GEOSGeometry*> copyList = splitResult; splitResult.clear(); //collect all the geometries that belong to the initial multifeature QVector<GEOSGeometry*> unionGeom; for ( int i = 0; i < copyList.size(); ++i ) { //is this geometry a part of the original multitype? bool isPart = false; for ( int j = 0; j < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); j++ ) { if ( GEOSEquals_r( geosinit.ctxt, copyList[i], GEOSGetGeometryN_r( geosinit.ctxt, mGeos, j ) ) ) { isPart = true; break; } } if ( isPart ) { unionGeom << copyList[i]; } else { QVector<GEOSGeometry*> geomVector; geomVector << copyList[i]; if ( type == GEOS_MULTILINESTRING ) splitResult << createGeosCollection( GEOS_MULTILINESTRING, geomVector ); else if ( type == GEOS_MULTIPOLYGON ) splitResult << createGeosCollection( GEOS_MULTIPOLYGON, geomVector ); else GEOSGeom_destroy_r( geosinit.ctxt, copyList[i] ); } } //make multifeature out of unionGeom if ( unionGeom.size() > 0 ) { if ( type == GEOS_MULTILINESTRING ) splitResult << createGeosCollection( GEOS_MULTILINESTRING, unionGeom ); else if ( type == GEOS_MULTIPOLYGON ) splitResult << createGeosCollection( GEOS_MULTIPOLYGON, unionGeom ); } else { unionGeom.clear(); } return 0; } QgsPoint QgsGeometry::asPoint( QgsConstWkbPtr &wkbPtr, bool hasZValue ) const { wkbPtr += 1 + sizeof( int ); double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); return QgsPoint( x, y ); } QgsPolyline QgsGeometry::asPolyline( QgsConstWkbPtr &wkbPtr, bool hasZValue ) const { wkbPtr += 1 + sizeof( int ); unsigned int nPoints; wkbPtr >> nPoints; QgsPolyline line( nPoints ); // Extract the points from the WKB format into the x and y vectors. for ( uint i = 0; i < nPoints; ++i ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); line[i] = QgsPoint( x, y ); } return line; } QgsPolygon QgsGeometry::asPolygon( QgsConstWkbPtr &wkbPtr, bool hasZValue ) const { wkbPtr += 1 + sizeof( int ); // get number of rings in the polygon unsigned int numRings; wkbPtr >> numRings; if ( numRings == 0 ) // sanity check for zero rings in polygon return QgsPolygon(); QgsPolygon rings( numRings ); for ( uint idx = 0; idx < numRings; idx++ ) { int nPoints; wkbPtr >> nPoints; QgsPolyline ring( nPoints ); for ( int jdx = 0; jdx < nPoints; jdx++ ) { double x, y; wkbPtr >> x >> y; if ( hasZValue ) wkbPtr += sizeof( double ); ring[jdx] = QgsPoint( x, y ); } rings[idx] = ring; } return rings; } QgsPoint QgsGeometry::asPoint() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBPoint && type != QGis::WKBPoint25D ) return QgsPoint( 0, 0 ); QgsConstWkbPtr wkbPtr( mGeometry ); return asPoint( wkbPtr, type == QGis::WKBPoint25D ); } QgsPolyline QgsGeometry::asPolyline() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBLineString && type != QGis::WKBLineString25D ) return QgsPolyline(); QgsConstWkbPtr wkbPtr( mGeometry ); return asPolyline( wkbPtr, type == QGis::WKBLineString25D ); } QgsPolygon QgsGeometry::asPolygon() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBPolygon && type != QGis::WKBPolygon25D ) return QgsPolygon(); QgsConstWkbPtr wkbPtr( mGeometry ); return asPolygon( wkbPtr, type == QGis::WKBPolygon25D ); } QgsMultiPoint QgsGeometry::asMultiPoint() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBMultiPoint && type != QGis::WKBMultiPoint25D ) return QgsMultiPoint(); bool hasZValue = ( type == QGis::WKBMultiPoint25D ); QgsConstWkbPtr wkbPtr( mGeometry + 1 + sizeof( int ) ); int nPoints; wkbPtr >> nPoints; QgsMultiPoint points( nPoints ); for ( int i = 0; i < nPoints; i++ ) { points[i] = asPoint( wkbPtr, hasZValue ); } return points; } QgsMultiPolyline QgsGeometry::asMultiPolyline() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBMultiLineString && type != QGis::WKBMultiLineString25D ) return QgsMultiPolyline(); bool hasZValue = ( type == QGis::WKBMultiLineString25D ); QgsConstWkbPtr wkbPtr( mGeometry + 1 + sizeof( int ) ); int numLineStrings; wkbPtr >> numLineStrings; QgsMultiPolyline lines( numLineStrings ); for ( int i = 0; i < numLineStrings; i++ ) lines[i] = asPolyline( wkbPtr, hasZValue ); return lines; } QgsMultiPolygon QgsGeometry::asMultiPolygon() const { QGis::WkbType type = wkbType(); if ( type != QGis::WKBMultiPolygon && type != QGis::WKBMultiPolygon25D ) return QgsMultiPolygon(); bool hasZValue = ( type == QGis::WKBMultiPolygon25D ); QgsConstWkbPtr wkbPtr( mGeometry + 1 + sizeof( int ) ); int numPolygons; wkbPtr >> numPolygons; QgsMultiPolygon polygons( numPolygons ); for ( int i = 0; i < numPolygons; i++ ) polygons[i] = asPolygon( wkbPtr, hasZValue ); return polygons; } double QgsGeometry::area() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return -1.0; double area; try { if ( GEOSArea_r( geosinit.ctxt, mGeos, &area ) == 0 ) return -1.0; } CATCH_GEOS( -1.0 ) return area; } double QgsGeometry::length() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return -1.0; double length; try { if ( GEOSLength_r( geosinit.ctxt, mGeos, &length ) == 0 ) return -1.0; } CATCH_GEOS( -1.0 ) return length; } double QgsGeometry::distance( const QgsGeometry& geom ) const { if ( mDirtyGeos ) exportWkbToGeos(); if ( geom.mDirtyGeos ) geom.exportWkbToGeos(); if ( !mGeos || !geom.mGeos ) return -1.0; double dist = -1.0; try { GEOSDistance_r( geosinit.ctxt, mGeos, geom.mGeos, &dist ); } CATCH_GEOS( -1.0 ) return dist; } QgsGeometry* QgsGeometry::buffer( double distance, int segments ) const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSBuffer_r( geosinit.ctxt, mGeos, distance, segments ) ); } CATCH_GEOS( 0 ) } QgsGeometry*QgsGeometry::buffer( double distance, int segments, int endCapStyle, int joinStyle, double mitreLimit ) const { #if defined(GEOS_VERSION_MAJOR) && defined(GEOS_VERSION_MINOR) && \ ((GEOS_VERSION_MAJOR>3) || ((GEOS_VERSION_MAJOR==3) && (GEOS_VERSION_MINOR>=3))) if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSBufferWithStyle_r( geosinit.ctxt, mGeos, distance, segments, endCapStyle, joinStyle, mitreLimit ) ); } CATCH_GEOS( 0 ) #else return 0; #endif } QgsGeometry* QgsGeometry::offsetCurve( double distance, int segments, int joinStyle, double mitreLimit ) const { #if defined(GEOS_VERSION_MAJOR) && defined(GEOS_VERSION_MINOR) && \ ((GEOS_VERSION_MAJOR>3) || ((GEOS_VERSION_MAJOR==3) && (GEOS_VERSION_MINOR>=3))) if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos || this->type() != QGis::Line ) return 0; try { return fromGeosGeom( GEOSOffsetCurve_r( geosinit.ctxt, mGeos, distance, segments, joinStyle, mitreLimit ) ); } CATCH_GEOS( 0 ) #else return 0; #endif } QgsGeometry* QgsGeometry::simplify( double tolerance ) const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSTopologyPreserveSimplify_r( geosinit.ctxt, mGeos, tolerance ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::smooth( const unsigned int iterations, const double offset ) const { switch ( wkbType() ) { case QGis::WKBPoint: case QGis::WKBPoint25D: case QGis::WKBMultiPoint: case QGis::WKBMultiPoint25D: //can't smooth a point based geometry return new QgsGeometry( *this ); case QGis::WKBLineString: case QGis::WKBLineString25D: { QgsPolyline line = asPolyline(); return QgsGeometry::fromPolyline( smoothLine( line, iterations, offset ) ); } case QGis::WKBMultiLineString: case QGis::WKBMultiLineString25D: { QgsMultiPolyline multiline = asMultiPolyline(); QgsMultiPolyline resultMultiline; QgsMultiPolyline::const_iterator lineIt = multiline.constBegin(); for ( ; lineIt != multiline.constEnd(); ++lineIt ) { resultMultiline << smoothLine( *lineIt, iterations, offset ); } return QgsGeometry::fromMultiPolyline( resultMultiline ); } case QGis::WKBPolygon: case QGis::WKBPolygon25D: { QgsPolygon poly = asPolygon(); return QgsGeometry::fromPolygon( smoothPolygon( poly, iterations, offset ) ); } case QGis::WKBMultiPolygon: case QGis::WKBMultiPolygon25D: { QgsMultiPolygon multipoly = asMultiPolygon(); QgsMultiPolygon resultMultipoly; QgsMultiPolygon::const_iterator polyIt = multipoly.constBegin(); for ( ; polyIt != multipoly.constEnd(); ++polyIt ) { resultMultipoly << smoothPolygon( *polyIt, iterations, offset ); } return QgsGeometry::fromMultiPolygon( resultMultipoly ); } break; case QGis::WKBUnknown: default: return new QgsGeometry( *this ); } } inline QgsPoint interpolatePointOnLine( const QgsPoint& p1, const QgsPoint& p2, const double offset ) { double deltaX = p2.x() - p1.x(); double deltaY = p2.y() - p1.y(); return QgsPoint( p1.x() + deltaX * offset, p1.y() + deltaY * offset ); } QgsPolyline QgsGeometry::smoothLine( const QgsPolyline& polyline, const unsigned int iterations, const double offset ) const { QgsPolyline result = polyline; for ( unsigned int iteration = 0; iteration < iterations; ++iteration ) { QgsPolyline outputLine = QgsPolyline(); for ( int i = 0; i < result.count() - 1; i++ ) { const QgsPoint& p1 = result.at( i ); const QgsPoint& p2 = result.at( i + 1 ); outputLine << ( i == 0 ? result.at( i ) : interpolatePointOnLine( p1, p2, offset ) ); outputLine << ( i == result.count() - 2 ? result.at( i + 1 ) : interpolatePointOnLine( p1, p2, 1.0 - offset ) ); } result = outputLine; } return result; } QgsPolygon QgsGeometry::smoothPolygon( const QgsPolygon& polygon, const unsigned int iterations, const double offset ) const { QgsPolygon resultPoly; QgsPolygon::const_iterator ringIt = polygon.constBegin(); for ( ; ringIt != polygon.constEnd(); ++ringIt ) { QgsPolyline resultRing = *ringIt; for ( unsigned int iteration = 0; iteration < iterations; ++iteration ) { QgsPolyline outputRing = QgsPolyline(); for ( int i = 0; i < resultRing.count() - 1; ++i ) { const QgsPoint& p1 = resultRing.at( i ); const QgsPoint& p2 = resultRing.at( i + 1 ); outputRing << interpolatePointOnLine( p1, p2, offset ); outputRing << interpolatePointOnLine( p1, p2, 1.0 - offset ); } //close polygon outputRing << outputRing.at( 0 ); resultRing = outputRing; } resultPoly << resultRing; } return resultPoly; } QgsGeometry* QgsGeometry::centroid() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSGetCentroid_r( geosinit.ctxt, mGeos ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::pointOnSurface() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSPointOnSurface_r( geosinit.ctxt, mGeos ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::convexHull() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSConvexHull_r( geosinit.ctxt, mGeos ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::interpolate( double distance ) const { #if defined(GEOS_VERSION_MAJOR) && defined(GEOS_VERSION_MINOR) && \ ((GEOS_VERSION_MAJOR>3) || ((GEOS_VERSION_MAJOR==3) && (GEOS_VERSION_MINOR>=2))) if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return 0; try { return fromGeosGeom( GEOSInterpolate_r( geosinit.ctxt, mGeos, distance ) ); } CATCH_GEOS( 0 ) #else QgsMessageLog::logMessage( QObject::tr( "GEOS prior to 3.2 doesn't support GEOSInterpolate" ), QObject::tr( "GEOS" ) ); return NULL; #endif } QgsGeometry* QgsGeometry::intersection( const QgsGeometry* geometry ) const { if ( !geometry ) return NULL; if ( mDirtyGeos ) exportWkbToGeos(); if ( geometry->mDirtyGeos ) geometry->exportWkbToGeos(); if ( !mGeos || !geometry->mGeos ) return 0; try { return fromGeosGeom( GEOSIntersection_r( geosinit.ctxt, mGeos, geometry->mGeos ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::combine( const QgsGeometry *geometry ) const { if ( !geometry ) return NULL; if ( mDirtyGeos ) exportWkbToGeos(); if ( geometry->mDirtyGeos ) geometry->exportWkbToGeos(); if ( !mGeos || !geometry->mGeos ) return 0; try { GEOSGeometry* unionGeom = GEOSUnion_r( geosinit.ctxt, mGeos, geometry->mGeos ); if ( !unionGeom ) return 0; if ( type() == QGis::Line ) { GEOSGeometry* mergedGeom = GEOSLineMerge_r( geosinit.ctxt, unionGeom ); if ( mergedGeom ) { GEOSGeom_destroy_r( geosinit.ctxt, unionGeom ); unionGeom = mergedGeom; } } return fromGeosGeom( unionGeom ); } CATCH_GEOS( new QgsGeometry( *this ) ) //return this geometry if union not possible } QgsGeometry* QgsGeometry::difference( const QgsGeometry* geometry ) const { if ( !geometry ) return NULL; if ( mDirtyGeos ) exportWkbToGeos(); if ( geometry->mDirtyGeos ) geometry->exportWkbToGeos(); if ( !mGeos || !geometry->mGeos ) return 0; try { return fromGeosGeom( GEOSDifference_r( geosinit.ctxt, mGeos, geometry->mGeos ) ); } CATCH_GEOS( 0 ) } QgsGeometry* QgsGeometry::symDifference( const QgsGeometry* geometry ) const { if ( !geometry ) return NULL; if ( mDirtyGeos ) exportWkbToGeos(); if ( geometry->mDirtyGeos ) geometry->exportWkbToGeos(); if ( !mGeos || !geometry->mGeos ) return 0; try { return fromGeosGeom( GEOSSymDifference_r( geosinit.ctxt, mGeos, geometry->mGeos ) ); } CATCH_GEOS( 0 ) } QList<QgsGeometry*> QgsGeometry::asGeometryCollection() const { if ( mDirtyGeos ) exportWkbToGeos(); if ( !mGeos ) return QList<QgsGeometry*>(); int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos ); QgsDebugMsg( "geom type: " + QString::number( type ) ); QList<QgsGeometry*> geomCollection; if ( type != GEOS_MULTIPOINT && type != GEOS_MULTILINESTRING && type != GEOS_MULTIPOLYGON && type != GEOS_GEOMETRYCOLLECTION ) { // we have a single-part geometry - put there a copy of this one geomCollection.append( new QgsGeometry( *this ) ); return geomCollection; } int count = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos ); QgsDebugMsg( "geom count: " + QString::number( count ) ); for ( int i = 0; i < count; ++i ) { const GEOSGeometry * geometry = GEOSGetGeometryN_r( geosinit.ctxt, mGeos, i ); geomCollection.append( fromGeosGeom( GEOSGeom_clone_r( geosinit.ctxt, geometry ) ) ); } return geomCollection; } QPointF QgsGeometry::asQPointF() const { QgsPoint point = asPoint(); return point.toQPointF(); } QPolygonF QgsGeometry::asQPolygonF() const { QPolygonF result; QgsPolyline polyline; QGis::WkbType type = wkbType(); if ( type == QGis::WKBLineString || type == QGis::WKBLineString25D ) { polyline = asPolyline(); } else if ( type == QGis::WKBPolygon || type == QGis::WKBPolygon25D ) { QgsPolygon polygon = asPolygon(); if ( polygon.size() < 1 ) return result; polyline = polygon.at( 0 ); } else { return result; } QgsPolyline::const_iterator lineIt = polyline.constBegin(); for ( ; lineIt != polyline.constEnd(); ++lineIt ) { result << lineIt->toQPointF(); } return result; } bool QgsGeometry::deleteRing( int ringNum, int partNum ) { if ( ringNum <= 0 || partNum < 0 ) return false; switch ( wkbType() ) { case QGis::WKBPolygon25D: case QGis::WKBPolygon: { if ( partNum != 0 ) return false; QgsPolygon polygon = asPolygon(); if ( ringNum >= polygon.count() ) return false; polygon.remove( ringNum ); QgsGeometry* g2 = QgsGeometry::fromPolygon( polygon ); *this = *g2; delete g2; return true; } case QGis::WKBMultiPolygon25D: case QGis::WKBMultiPolygon: { QgsMultiPolygon mpolygon = asMultiPolygon(); if ( partNum >= mpolygon.count() ) return false; if ( ringNum >= mpolygon[partNum].count() ) return false; mpolygon[partNum].remove( ringNum ); QgsGeometry* g2 = QgsGeometry::fromMultiPolygon( mpolygon ); *this = *g2; delete g2; return true; } default: return false; // only makes sense with polygons and multipolygons } } bool QgsGeometry::deletePart( int partNum ) { if ( partNum < 0 ) return false; switch ( wkbType() ) { case QGis::WKBMultiPoint25D: case QGis::WKBMultiPoint: { QgsMultiPoint mpoint = asMultiPoint(); if ( partNum >= mpoint.size() || mpoint.size() == 1 ) return false; mpoint.remove( partNum ); QgsGeometry* g2 = QgsGeometry::fromMultiPoint( mpoint ); *this = *g2; delete g2; break; } case QGis::WKBMultiLineString25D: case QGis::WKBMultiLineString: { QgsMultiPolyline mline = asMultiPolyline(); if ( partNum >= mline.size() || mline.size() == 1 ) return false; mline.remove( partNum ); QgsGeometry* g2 = QgsGeometry::fromMultiPolyline( mline ); *this = *g2; delete g2; break; } case QGis::WKBMultiPolygon25D: case QGis::WKBMultiPolygon: { QgsMultiPolygon mpolygon = asMultiPolygon(); if ( partNum >= mpolygon.size() || mpolygon.size() == 1 ) return false; mpolygon.remove( partNum ); QgsGeometry* g2 = QgsGeometry::fromMultiPolygon( mpolygon ); *this = *g2; delete g2; break; } default: // single part geometries are ignored return false; } return true; } /** Return union of several geometries - try to use unary union if available (GEOS >= 3.3) otherwise use a cascade of unions. * Takes ownership of passed geometries, returns a new instance */ static GEOSGeometry* _makeUnion( QList<GEOSGeometry*> geoms ) { #if defined(GEOS_VERSION_MAJOR) && defined(GEOS_VERSION_MINOR) && (((GEOS_VERSION_MAJOR==3) && (GEOS_VERSION_MINOR>=3)) || (GEOS_VERSION_MAJOR>3)) GEOSGeometry* geomCollection = 0; geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geoms.toVector() ); GEOSGeometry* geomUnion = GEOSUnaryUnion_r( geosinit.ctxt, geomCollection ); GEOSGeom_destroy_r( geosinit.ctxt, geomCollection ); return geomUnion; #else GEOSGeometry* geomCollection = geoms.takeFirst(); while ( !geoms.isEmpty() ) { GEOSGeometry* g = geoms.takeFirst(); GEOSGeometry* geomCollectionNew = GEOSUnion_r( geosinit.ctxt, geomCollection, g ); GEOSGeom_destroy_r( geosinit.ctxt, geomCollection ); GEOSGeom_destroy_r( geosinit.ctxt, g ); geomCollection = geomCollectionNew; } return geomCollection; #endif } int QgsGeometry::avoidIntersections( QMap<QgsVectorLayer*, QSet< QgsFeatureId > > ignoreFeatures ) { int returnValue = 0; //check if g has polygon type if ( type() != QGis::Polygon ) return 1; QGis::WkbType geomTypeBeforeModification = wkbType(); //read avoid intersections list from project properties bool listReadOk; QStringList avoidIntersectionsList = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList(), &listReadOk ); if ( !listReadOk ) return true; //no intersections stored in project does not mean error QList<GEOSGeometry*> nearGeometries; //go through list, convert each layer to vector layer and call QgsVectorLayer::removePolygonIntersections for each QgsVectorLayer* currentLayer = 0; QStringList::const_iterator aIt = avoidIntersectionsList.constBegin(); for ( ; aIt != avoidIntersectionsList.constEnd(); ++aIt ) { currentLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( *aIt ) ); if ( currentLayer ) { QgsFeatureIds ignoreIds; QMap<QgsVectorLayer*, QSet<qint64> >::const_iterator ignoreIt = ignoreFeatures.find( currentLayer ); if ( ignoreIt != ignoreFeatures.constEnd() ) ignoreIds = ignoreIt.value(); QgsFeatureIterator fi = currentLayer->getFeatures( QgsFeatureRequest( boundingBox() ) .setFlags( QgsFeatureRequest::ExactIntersect ) .setSubsetOfAttributes( QgsAttributeList() ) ); QgsFeature f; while ( fi.nextFeature( f ) ) { if ( ignoreIds.contains( f.id() ) ) continue; if ( !f.geometry() ) continue; nearGeometries << GEOSGeom_clone_r( geosinit.ctxt, f.geometry()->asGeos() ); } } } if ( nearGeometries.isEmpty() ) return 0; GEOSGeometry* nearGeometriesUnion = 0; GEOSGeometry* geomWithoutIntersections = 0; try { nearGeometriesUnion = _makeUnion( nearGeometries ); geomWithoutIntersections = GEOSDifference_r( geosinit.ctxt, asGeos(), nearGeometriesUnion ); fromGeos( geomWithoutIntersections ); GEOSGeom_destroy_r( geosinit.ctxt, nearGeometriesUnion ); } catch ( GEOSException &e ) { if ( nearGeometriesUnion ) GEOSGeom_destroy_r( geosinit.ctxt, nearGeometriesUnion ); if ( geomWithoutIntersections ) GEOSGeom_destroy_r( geosinit.ctxt, geomWithoutIntersections ); QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); return 3; } //make sure the geometry still has the same type (e.g. no change from polygon to multipolygon) if ( wkbType() != geomTypeBeforeModification ) return 2; return returnValue; } void QgsGeometry::validateGeometry( QList<Error> &errors ) { QgsGeometryValidator::validateGeometry( this, errors ); } bool QgsGeometry::isGeosValid() const { try { const GEOSGeometry *g = asGeos(); if ( !g ) return false; return GEOSisValid_r( geosinit.ctxt, g ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); return false; } } bool QgsGeometry::isGeosEqual( const QgsGeometry &g ) const { return geosRelOp( GEOSEquals_r, this, &g ); } bool QgsGeometry::isGeosEmpty() const { try { const GEOSGeometry *g = asGeos(); if ( !g ) return false; return GEOSisEmpty_r( geosinit.ctxt, g ); } catch ( GEOSException &e ) { QgsMessageLog::logMessage( QObject::tr( "Exception: %1" ).arg( e.what() ), QObject::tr( "GEOS" ) ); return false; } } double QgsGeometry::leftOf( double x, double y, double& x1, double& y1, double& x2, double& y2 ) const { double f1 = x - x1; double f2 = y2 - y1; double f3 = y - y1; double f4 = x2 - x1; return f1*f2 - f3*f4; } QgsGeometry* QgsGeometry::convertToPoint( bool destMultipart ) const { switch ( type() ) { case QGis::Point: { bool srcIsMultipart = isMultipart(); if (( destMultipart && srcIsMultipart ) || ( !destMultipart && !srcIsMultipart ) ) { // return a copy of the same geom return new QgsGeometry( *this ); } if ( destMultipart ) { // layer is multipart => make a multipoint with a single point return fromMultiPoint( QgsMultiPoint() << asPoint() ); } else { // destination is singlepart => make a single part if possible QgsMultiPoint multiPoint = asMultiPoint(); if ( multiPoint.count() == 1 ) { return fromPoint( multiPoint[0] ); } } return 0; } case QGis::Line: { // only possible if destination is multipart if ( !destMultipart ) return 0; // input geometry is multipart if ( isMultipart() ) { QgsMultiPolyline multiLine = asMultiPolyline(); QgsMultiPoint multiPoint; for ( QgsMultiPolyline::const_iterator multiLineIt = multiLine.constBegin(); multiLineIt != multiLine.constEnd(); ++multiLineIt ) for ( QgsPolyline::const_iterator lineIt = ( *multiLineIt ).constBegin(); lineIt != ( *multiLineIt ).constEnd(); ++lineIt ) multiPoint << *lineIt; return fromMultiPoint( multiPoint ); } // input geometry is not multipart: copy directly the line into a multipoint else { QgsPolyline line = asPolyline(); if ( !line.isEmpty() ) return fromMultiPoint( line ); } return 0; } case QGis::Polygon: { // can only transform if destination is multipoint if ( !destMultipart ) return 0; // input geometry is multipart: make a multipoint from multipolygon if ( isMultipart() ) { QgsMultiPolygon multiPolygon = asMultiPolygon(); QgsMultiPoint multiPoint; for ( QgsMultiPolygon::const_iterator polygonIt = multiPolygon.constBegin(); polygonIt != multiPolygon.constEnd(); ++polygonIt ) for ( QgsMultiPolyline::const_iterator multiLineIt = ( *polygonIt ).constBegin(); multiLineIt != ( *polygonIt ).constEnd(); ++multiLineIt ) for ( QgsPolyline::const_iterator lineIt = ( *multiLineIt ).constBegin(); lineIt != ( *multiLineIt ).constEnd(); ++lineIt ) multiPoint << *lineIt; return fromMultiPoint( multiPoint ); } // input geometry is not multipart: make a multipoint from polygon else { QgsPolygon polygon = asPolygon(); QgsMultiPoint multiPoint; for ( QgsMultiPolyline::const_iterator multiLineIt = polygon.constBegin(); multiLineIt != polygon.constEnd(); ++multiLineIt ) for ( QgsPolyline::const_iterator lineIt = ( *multiLineIt ).constBegin(); lineIt != ( *multiLineIt ).constEnd(); ++lineIt ) multiPoint << *lineIt; return fromMultiPoint( multiPoint ); } } default: return 0; } } QgsGeometry* QgsGeometry::convertToLine( bool destMultipart ) const { switch ( type() ) { case QGis::Point: { if ( !isMultipart() ) return 0; QgsMultiPoint multiPoint = asMultiPoint(); if ( multiPoint.count() < 2 ) return 0; if ( destMultipart ) return fromMultiPolyline( QgsMultiPolyline() << multiPoint ); else return fromPolyline( multiPoint ); } case QGis::Line: { bool srcIsMultipart = isMultipart(); if (( destMultipart && srcIsMultipart ) || ( !destMultipart && ! srcIsMultipart ) ) { // return a copy of the same geom return new QgsGeometry( *this ); } if ( destMultipart ) { // destination is multipart => makes a multipoint with a single line QgsPolyline line = asPolyline(); if ( !line.isEmpty() ) return fromMultiPolyline( QgsMultiPolyline() << line ); } else { // destination is singlepart => make a single part if possible QgsMultiPolyline multiLine = asMultiPolyline(); if ( multiLine.count() == 1 ) return fromPolyline( multiLine[0] ); } return 0; } case QGis::Polygon: { // input geometry is multipolygon if ( isMultipart() ) { QgsMultiPolygon multiPolygon = asMultiPolygon(); QgsMultiPolyline multiLine; for ( QgsMultiPolygon::const_iterator polygonIt = multiPolygon.constBegin(); polygonIt != multiPolygon.constEnd(); ++polygonIt ) for ( QgsMultiPolyline::const_iterator multiLineIt = ( *polygonIt ).constBegin(); multiLineIt != ( *polygonIt ).constEnd(); ++multiLineIt ) multiLine << *multiLineIt; if ( destMultipart ) { // destination is multipart return fromMultiPolyline( multiLine ); } else if ( multiLine.count() == 1 ) { // destination is singlepart => make a single part if possible return fromPolyline( multiLine[0] ); } } // input geometry is single polygon else { QgsPolygon polygon = asPolygon(); // if polygon has rings if ( polygon.count() > 1 ) { // cannot fit a polygon with rings in a single line layer // TODO: would it be better to remove rings? if ( destMultipart ) { QgsPolygon polygon = asPolygon(); QgsMultiPolyline multiLine; for ( QgsMultiPolyline::const_iterator multiLineIt = polygon.constBegin(); multiLineIt != polygon.constEnd(); ++multiLineIt ) multiLine << *multiLineIt; return fromMultiPolyline( multiLine ); } } // no rings else if ( polygon.count() == 1 ) { if ( destMultipart ) { return fromMultiPolyline( polygon ); } else { return fromPolyline( polygon[0] ); } } } return 0; } default: return 0; } } QgsGeometry* QgsGeometry::convertToPolygon( bool destMultipart ) const { switch ( type() ) { case QGis::Point: { if ( !isMultipart() ) return 0; QgsMultiPoint multiPoint = asMultiPoint(); if ( multiPoint.count() < 3 ) return 0; if ( multiPoint.last() != multiPoint.first() ) multiPoint << multiPoint.first(); QgsPolygon polygon = QgsPolygon() << multiPoint; if ( destMultipart ) return fromMultiPolygon( QgsMultiPolygon() << polygon ); else return fromPolygon( polygon ); } case QGis::Line: { // input geometry is multiline if ( isMultipart() ) { QgsMultiPolyline multiLine = asMultiPolyline(); QgsMultiPolygon multiPolygon; for ( QgsMultiPolyline::iterator multiLineIt = multiLine.begin(); multiLineIt != multiLine.end(); ++multiLineIt ) { // do not create polygon for a 1 segment line if (( *multiLineIt ).count() < 3 ) return 0; if (( *multiLineIt ).count() == 3 && ( *multiLineIt ).first() == ( *multiLineIt ).last() ) return 0; // add closing node if (( *multiLineIt ).first() != ( *multiLineIt ).last() ) *multiLineIt << ( *multiLineIt ).first(); multiPolygon << ( QgsPolygon() << *multiLineIt ); } // check that polygons were inserted if ( !multiPolygon.isEmpty() ) { if ( destMultipart ) { return fromMultiPolygon( multiPolygon ); } else if ( multiPolygon.count() == 1 ) { // destination is singlepart => make a single part if possible return fromPolygon( multiPolygon[0] ); } } } // input geometry is single line else { QgsPolyline line = asPolyline(); // do not create polygon for a 1 segment line if ( line.count() < 3 ) return 0; if ( line.count() == 3 && line.first() == line.last() ) return 0; // add closing node if ( line.first() != line.last() ) line << line.first(); // destination is multipart if ( destMultipart ) { return fromMultiPolygon( QgsMultiPolygon() << ( QgsPolygon() << line ) ); } else { return fromPolygon( QgsPolygon() << line ); } } return 0; } case QGis::Polygon: { bool srcIsMultipart = isMultipart(); if (( destMultipart && srcIsMultipart ) || ( !destMultipart && ! srcIsMultipart ) ) { // return a copy of the same geom return new QgsGeometry( *this ); } if ( destMultipart ) { // destination is multipart => makes a multipoint with a single polygon QgsPolygon polygon = asPolygon(); if ( !polygon.isEmpty() ) return fromMultiPolygon( QgsMultiPolygon() << polygon ); } else { QgsMultiPolygon multiPolygon = asMultiPolygon(); if ( multiPolygon.count() == 1 ) { // destination is singlepart => make a single part if possible return fromPolygon( multiPolygon[0] ); } } return 0; } default: return 0; } } QgsGeometry *QgsGeometry::unaryUnion( const QList<QgsGeometry *> &geometryList ) { QList<GEOSGeometry*> geoms; foreach ( QgsGeometry* g, geometryList ) { geoms.append( GEOSGeom_clone_r( geosinit.ctxt, g->asGeos() ) ); } GEOSGeometry *geomUnion = _makeUnion( geoms ); QgsGeometry *ret = new QgsGeometry(); ret->fromGeos( geomUnion ); return ret; } bool QgsGeometry::compare( const QgsPolyline &p1, const QgsPolyline &p2, double epsilon ) { if ( p1.count() != p2.count() ) return false; for ( int i = 0; i < p1.count(); ++i ) { if ( !p1.at( i ).compare( p2.at( i ), epsilon ) ) return false; } return true; } bool QgsGeometry::compare( const QgsPolygon &p1, const QgsPolygon &p2, double epsilon ) { if ( p1.count() != p2.count() ) return false; for ( int i = 0; i < p1.count(); ++i ) { if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) ) return false; } return true; } bool QgsGeometry::compare( const QgsMultiPolygon &p1, const QgsMultiPolygon &p2, double epsilon ) { if ( p1.count() != p2.count() ) return false; for ( int i = 0; i < p1.count(); ++i ) { if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) ) return false; } return true; }
Gaia3D/QGIS
src/core/qgsgeometry.cpp
C++
gpl-2.0
172,273
<?php /* core/themes/stable/templates/admin/status-report.html.twig */ class __TwigTemplate_e430300fd396a513b4bbea1ba72ba097b3368caf91f53bf7a42c6fc32f807ca4 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("for" => 20, "if" => 22); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array('for', 'if'), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 18 echo "<table class=\"system-status-report\"> <tbody> "; // line 20 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable((isset($context["requirements"]) ? $context["requirements"] : null)); foreach ($context['_seq'] as $context["_key"] => $context["requirement"]) { // line 21 echo " <tr class=\"system-status-report__entry system-status-report__entry--"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "severity_status", array()), "html", null, true)); echo " color-"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "severity_status", array()), "html", null, true)); echo "\"> "; // line 22 if (twig_in_filter($this->getAttribute($context["requirement"], "severity_status", array()), array(0 => "warning", 1 => "error"))) { // line 23 echo " <th class=\"system-status-report__status-title system-status-report__status-icon system-status-report__status-icon--"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "severity_status", array()), "html", null, true)); echo "\"> <span class=\"visually-hidden\">"; // line 24 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "severity_title", array()), "html", null, true)); echo "</span> "; } else { // line 26 echo " <th class=\"system-status-report__status-title\"> "; } // line 28 echo " "; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "title", array()), "html", null, true)); echo " </th> <td> "; // line 31 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "value", array()), "html", null, true)); echo " "; // line 32 if ($this->getAttribute($context["requirement"], "description", array())) { // line 33 echo " <div class=\"description\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["requirement"], "description", array()), "html", null, true)); echo "</div> "; } // line 35 echo " </td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['requirement'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 38 echo " </tbody> </table> "; } public function getTemplateName() { return "core/themes/stable/templates/admin/status-report.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 101 => 38, 93 => 35, 87 => 33, 85 => 32, 81 => 31, 74 => 28, 70 => 26, 65 => 24, 60 => 23, 58 => 22, 51 => 21, 47 => 20, 43 => 18,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for the status report.*/ /* **/ /* * Available variables:*/ /* * - requirements: Contains multiple requirement instances.*/ /* * Each requirement contains:*/ /* * - title: The title of the requirement.*/ /* * - value: (optional) The requirement's status.*/ /* * - description: (optional) The requirement's description.*/ /* * - severity_title: The title of the severity.*/ /* * - severity_status: Indicates the severity status.*/ /* **/ /* * @see template_preprocess_status_report()*/ /* *//* */ /* #}*/ /* <table class="system-status-report">*/ /* <tbody>*/ /* {% for requirement in requirements %}*/ /* <tr class="system-status-report__entry system-status-report__entry--{{ requirement.severity_status }} color-{{ requirement.severity_status }}">*/ /* {% if requirement.severity_status in ['warning', 'error'] %}*/ /* <th class="system-status-report__status-title system-status-report__status-icon system-status-report__status-icon--{{ requirement.severity_status }}">*/ /* <span class="visually-hidden">{{ requirement.severity_title }}</span>*/ /* {% else %}*/ /* <th class="system-status-report__status-title">*/ /* {% endif %}*/ /* {{ requirement.title }}*/ /* </th>*/ /* <td>*/ /* {{ requirement.value }}*/ /* {% if requirement.description %}*/ /* <div class="description">{{ requirement.description }}</div>*/ /* {% endif %}*/ /* </td>*/ /* </tr>*/ /* {% endfor %}*/ /* </tbody>*/ /* </table>*/ /* */
mikekeilty/seventen-marketing-website
sites/default/files/php/twig/355c3156_status-report.html.twig_3e03b167c95d4b6831b9342a307e4844d3c75df6ce65256942c4f44c1f2dbaaf/ae5a6275ec07e81ddc57afa9e680b5c8df13d88bfb4800dc1045d59d5da2b9a8.php
PHP
gpl-2.0
7,075
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Author: Joseph Herlant <herlantj@gmail.com> # File name: hdfs_disk_usage_per_datanode.py # Creation date: 2014-10-08 # # Distributed under terms of the GNU GPLv3 license. """ This nagios active check parses the Hadoop HDFS web interface url: http://<namenode>:<port>/dfsnodelist.jsp?whatNodes=LIVE to check for active datanodes that use disk beyond the given thresholds. The output includes performance datas and is truncated if longer than 1024 chars. Tested on: Hadoop CDH3U5 """ __author__ = 'Joseph Herlant' __copyright__ = 'Copyright 2014, Joseph Herlant' __credits__ = ['Joseph Herlant'] __license__ = 'GNU GPLv3' __version__ = '1.0.2' __maintainer__ = 'Joseph Herlant' __email__ = 'herlantj@gmail.com' __status__ = 'Production' __website__ = 'https://github.com/aerostitch/' from mechanize import Browser from BeautifulSoup import BeautifulSoup import argparse, sys if __name__ == '__main__': # use -h argument to get help parser = argparse.ArgumentParser( description='A Nagios check to verify all datanodes disk usage in \ an HDFS cluster from the namenode web interface.') parser.add_argument('-n', '--namenode', required=True, help='hostname of the namenode of the cluster') parser.add_argument('-p', '--port', type=int, default=50070, help='port of the namenode http interface. \ Defaults to 50070.') parser.add_argument('-w', '--warning', type=int, default=80, help='warning threshold. Defaults to 80.') parser.add_argument('-c', '--critical', type=int, default=90, help='critical threshold. Defaults to 90.') args = parser.parse_args() # Get the web page from the namenode url = "http://%s:%d/dfsnodelist.jsp?whatNodes=LIVE" % \ (args.namenode, args.port) try: page = Browser().open(url) except IOError: print 'CRITICAL: Cannot access namenode interface on %s:%d!' % \ (args.namenode, args.port) sys.exit(2) # parse the page html = page.read() soup = BeautifulSoup(html) datanodes = soup.findAll('td', {'class' : 'name'}) pcused = soup.findAll('td', {'class' : 'pcused', 'align' : 'right'}) w_msg = '' c_msg = '' perfdata = '' for (idx, node) in enumerate(datanodes): pct = float(pcused[idx].contents[0].strip()) node = datanodes[idx].findChildren('a')[0].contents[0].strip() if pct >= args.critical: c_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) elif pct >= args.warning: w_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) else: perfdata += ' %s=%.1f,' % (node, pct) # Prints the values and exits with the nagios exit code if len(c_msg) > 0: print ('CRITICAL:%s%s |%s' % (c_msg, w_msg, perfdata)).strip(',')[:1024] sys.exit(2) elif len(w_msg) > 0: print ('WARNING:%s |%s' % (w_msg, perfdata)).strip(',')[:1024] sys.exit(1) elif len(perfdata) == 0: print 'CRITICAL: Unable to find any node data in the page.' sys.exit(2) else: print ('OK |%s' % (perfdata)).strip(',')[:1024] sys.exit(0)
aerostitch/nagios_checks
hdfs_disk_usage_per_datanode.py
Python
gpl-2.0
3,375
# Require any additional compass plugins here. # Set this to the root of your project when deployed: http_path = "/" # Paths to the base theme directories. css_dir = "sites/all/themes/mosaic/css" sass_dir = "sites/all/themes/mosaic/sass" javascripts_dir = "sites/all/themes/mosaic/js" project_type = :stand_alone images_path = "sites/all/themes/mosaic/assets" # Images are located in the mosaic theme icons_dir = "sites/all/themes/mosaic/assets/icons" mosaic_dir = "sites/all/themes/mosaic/assets/mosaic" vtiles_dir = "sites/all/themes/mosaic/assets/vtiles" htiles_dir = "sites/all/themes/mosaic/assets/htiles" require 'sassy-buttons' # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed # To enable relative paths to assets via compass helper functions. Uncomment: #relative_assets = true # To disable debugging comments that display the original location of your selectors. Uncomment: # line_comments = false # If you prefer the indented syntax, you might want to regenerate this # project again passing --syntax sass, or you can uncomment this: #preferred_syntax = :sass # and then run: # sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass # sass-convert -R --from scss --to sass scss sass
coraltech/drupal-cn
config.rb
Ruby
gpl-2.0
1,339
/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_OOPS_METHODDATAOOP_HPP #define SHARE_VM_OOPS_METHODDATAOOP_HPP #include "interpreter/bytecodes.hpp" #include "memory/universe.hpp" #include "oops/method.hpp" #include "oops/oop.hpp" #include "runtime/orderAccess.hpp" class BytecodeStream; class KlassSizeStats; // The MethodData object collects counts and other profile information // during zeroth-tier (interpretive) and first-tier execution. // The profile is used later by compilation heuristics. Some heuristics // enable use of aggressive (or "heroic") optimizations. An aggressive // optimization often has a down-side, a corner case that it handles // poorly, but which is thought to be rare. The profile provides // evidence of this rarity for a given method or even BCI. It allows // the compiler to back out of the optimization at places where it // has historically been a poor choice. Other heuristics try to use // specific information gathered about types observed at a given site. // // All data in the profile is approximate. It is expected to be accurate // on the whole, but the system expects occasional inaccuraces, due to // counter overflow, multiprocessor races during data collection, space // limitations, missing MDO blocks, etc. Bad or missing data will degrade // optimization quality but will not affect correctness. Also, each MDO // is marked with its birth-date ("creation_mileage") which can be used // to assess the quality ("maturity") of its data. // // Short (<32-bit) counters are designed to overflow to a known "saturated" // state. Also, certain recorded per-BCI events are given one-bit counters // which overflow to a saturated state which applied to all counters at // that BCI. In other words, there is a small lattice which approximates // the ideal of an infinite-precision counter for each event at each BCI, // and the lattice quickly "bottoms out" in a state where all counters // are taken to be indefinitely large. // // The reader will find many data races in profile gathering code, starting // with invocation counter incrementation. None of these races harm correct // execution of the compiled code. // forward decl class ProfileData; // DataLayout // // Overlay for generic profiling data. class DataLayout VALUE_OBJ_CLASS_SPEC { private: // Every data layout begins with a header. This header // contains a tag, which is used to indicate the size/layout // of the data, 4 bits of flags, which can be used in any way, // 4 bits of trap history (none/one reason/many reasons), // and a bci, which is used to tie this piece of data to a // specific bci in the bytecodes. union { intptr_t _bits; struct { u1 _tag; u1 _flags; u2 _bci; } _struct; } _header; // The data layout has an arbitrary number of cells, each sized // to accomodate a pointer or an integer. intptr_t _cells[1]; // Some types of data layouts need a length field. static bool needs_array_len(u1 tag); public: enum { counter_increment = 1 }; enum { cell_size = sizeof(intptr_t) }; // Tag values enum { no_tag, bit_data_tag, counter_data_tag, jump_data_tag, receiver_type_data_tag, virtual_call_data_tag, ret_data_tag, branch_data_tag, multi_branch_data_tag, arg_info_data_tag }; enum { // The _struct._flags word is formatted as [trap_state:4 | flags:4]. // The trap state breaks down further as [recompile:1 | reason:3]. // This further breakdown is defined in deoptimization.cpp. // See Deoptimization::trap_state_reason for an assert that // trap_bits is big enough to hold reasons < Reason_RECORDED_LIMIT. // // The trap_state is collected only if ProfileTraps is true. trap_bits = 1+3, // 3: enough to distinguish [0..Reason_RECORDED_LIMIT]. trap_shift = BitsPerByte - trap_bits, trap_mask = right_n_bits(trap_bits), trap_mask_in_place = (trap_mask << trap_shift), flag_limit = trap_shift, flag_mask = right_n_bits(flag_limit), first_flag = 0 }; // Size computation static int header_size_in_bytes() { return cell_size; } static int header_size_in_cells() { return 1; } static int compute_size_in_bytes(int cell_count) { return header_size_in_bytes() + cell_count * cell_size; } // Initialization void initialize(u1 tag, u2 bci, int cell_count); // Accessors u1 tag() { return _header._struct._tag; } // Return a few bits of trap state. Range is [0..trap_mask]. // The state tells if traps with zero, one, or many reasons have occurred. // It also tells whether zero or many recompilations have occurred. // The associated trap histogram in the MDO itself tells whether // traps are common or not. If a BCI shows that a trap X has // occurred, and the MDO shows N occurrences of X, we make the // simplifying assumption that all N occurrences can be blamed // on that BCI. int trap_state() { return ((_header._struct._flags >> trap_shift) & trap_mask); } void set_trap_state(int new_state) { assert(ProfileTraps, "used only under +ProfileTraps"); uint old_flags = (_header._struct._flags & flag_mask); _header._struct._flags = (new_state << trap_shift) | old_flags; } u1 flags() { return _header._struct._flags; } u2 bci() { return _header._struct._bci; } void set_header(intptr_t value) { _header._bits = value; } void release_set_header(intptr_t value) { OrderAccess::release_store_ptr(&_header._bits, value); } intptr_t header() { return _header._bits; } void set_cell_at(int index, intptr_t value) { _cells[index] = value; } void release_set_cell_at(int index, intptr_t value) { OrderAccess::release_store_ptr(&_cells[index], value); } intptr_t cell_at(int index) { return _cells[index]; } void set_flag_at(int flag_number) { assert(flag_number < flag_limit, "oob"); _header._struct._flags |= (0x1 << flag_number); } bool flag_at(int flag_number) { assert(flag_number < flag_limit, "oob"); return (_header._struct._flags & (0x1 << flag_number)) != 0; } // Low-level support for code generation. static ByteSize header_offset() { return byte_offset_of(DataLayout, _header); } static ByteSize tag_offset() { return byte_offset_of(DataLayout, _header._struct._tag); } static ByteSize flags_offset() { return byte_offset_of(DataLayout, _header._struct._flags); } static ByteSize bci_offset() { return byte_offset_of(DataLayout, _header._struct._bci); } static ByteSize cell_offset(int index) { return byte_offset_of(DataLayout, _cells) + in_ByteSize(index * cell_size); } // Return a value which, when or-ed as a byte into _flags, sets the flag. static int flag_number_to_byte_constant(int flag_number) { assert(0 <= flag_number && flag_number < flag_limit, "oob"); DataLayout temp; temp.set_header(0); temp.set_flag_at(flag_number); return temp._header._struct._flags; } // Return a value which, when or-ed as a word into _header, sets the flag. static intptr_t flag_mask_to_header_mask(int byte_constant) { DataLayout temp; temp.set_header(0); temp._header._struct._flags = byte_constant; return temp._header._bits; } ProfileData* data_in(); // GC support void clean_weak_klass_links(BoolObjectClosure* cl); }; // ProfileData class hierarchy class ProfileData; class BitData; class CounterData; class ReceiverTypeData; class VirtualCallData; class RetData; class JumpData; class BranchData; class ArrayData; class MultiBranchData; class ArgInfoData; // ProfileData // // A ProfileData object is created to refer to a section of profiling // data in a structured way. class ProfileData : public ResourceObj { private: #ifndef PRODUCT enum { tab_width_one = 16, tab_width_two = 36 }; #endif // !PRODUCT // This is a pointer to a section of profiling data. DataLayout* _data; protected: DataLayout* data() { return _data; } enum { cell_size = DataLayout::cell_size }; public: // How many cells are in this? virtual int cell_count() { ShouldNotReachHere(); return -1; } // Return the size of this data. int size_in_bytes() { return DataLayout::compute_size_in_bytes(cell_count()); } protected: // Low-level accessors for underlying data void set_intptr_at(int index, intptr_t value) { assert(0 <= index && index < cell_count(), "oob"); data()->set_cell_at(index, value); } void release_set_intptr_at(int index, intptr_t value) { assert(0 <= index && index < cell_count(), "oob"); data()->release_set_cell_at(index, value); } intptr_t intptr_at(int index) { assert(0 <= index && index < cell_count(), "oob"); return data()->cell_at(index); } void set_uint_at(int index, uint value) { set_intptr_at(index, (intptr_t) value); } void release_set_uint_at(int index, uint value) { release_set_intptr_at(index, (intptr_t) value); } uint uint_at(int index) { return (uint)intptr_at(index); } void set_int_at(int index, int value) { set_intptr_at(index, (intptr_t) value); } void release_set_int_at(int index, int value) { release_set_intptr_at(index, (intptr_t) value); } int int_at(int index) { return (int)intptr_at(index); } int int_at_unchecked(int index) { return (int)data()->cell_at(index); } void set_oop_at(int index, oop value) { set_intptr_at(index, (intptr_t) value); } oop oop_at(int index) { return (oop)intptr_at(index); } void set_flag_at(int flag_number) { data()->set_flag_at(flag_number); } bool flag_at(int flag_number) { return data()->flag_at(flag_number); } // two convenient imports for use by subclasses: static ByteSize cell_offset(int index) { return DataLayout::cell_offset(index); } static int flag_number_to_byte_constant(int flag_number) { return DataLayout::flag_number_to_byte_constant(flag_number); } ProfileData(DataLayout* data) { _data = data; } public: // Constructor for invalid ProfileData. ProfileData(); u2 bci() { return data()->bci(); } address dp() { return (address)_data; } int trap_state() { return data()->trap_state(); } void set_trap_state(int new_state) { data()->set_trap_state(new_state); } // Type checking virtual bool is_BitData() { return false; } virtual bool is_CounterData() { return false; } virtual bool is_JumpData() { return false; } virtual bool is_ReceiverTypeData(){ return false; } virtual bool is_VirtualCallData() { return false; } virtual bool is_RetData() { return false; } virtual bool is_BranchData() { return false; } virtual bool is_ArrayData() { return false; } virtual bool is_MultiBranchData() { return false; } virtual bool is_ArgInfoData() { return false; } BitData* as_BitData() { assert(is_BitData(), "wrong type"); return is_BitData() ? (BitData*) this : NULL; } CounterData* as_CounterData() { assert(is_CounterData(), "wrong type"); return is_CounterData() ? (CounterData*) this : NULL; } JumpData* as_JumpData() { assert(is_JumpData(), "wrong type"); return is_JumpData() ? (JumpData*) this : NULL; } ReceiverTypeData* as_ReceiverTypeData() { assert(is_ReceiverTypeData(), "wrong type"); return is_ReceiverTypeData() ? (ReceiverTypeData*)this : NULL; } VirtualCallData* as_VirtualCallData() { assert(is_VirtualCallData(), "wrong type"); return is_VirtualCallData() ? (VirtualCallData*)this : NULL; } RetData* as_RetData() { assert(is_RetData(), "wrong type"); return is_RetData() ? (RetData*) this : NULL; } BranchData* as_BranchData() { assert(is_BranchData(), "wrong type"); return is_BranchData() ? (BranchData*) this : NULL; } ArrayData* as_ArrayData() { assert(is_ArrayData(), "wrong type"); return is_ArrayData() ? (ArrayData*) this : NULL; } MultiBranchData* as_MultiBranchData() { assert(is_MultiBranchData(), "wrong type"); return is_MultiBranchData() ? (MultiBranchData*)this : NULL; } ArgInfoData* as_ArgInfoData() { assert(is_ArgInfoData(), "wrong type"); return is_ArgInfoData() ? (ArgInfoData*)this : NULL; } // Subclass specific initialization virtual void post_initialize(BytecodeStream* stream, MethodData* mdo) {} // GC support virtual void clean_weak_klass_links(BoolObjectClosure* is_alive_closure) {} // CI translation: ProfileData can represent both MethodDataOop data // as well as CIMethodData data. This function is provided for translating // an oop in a ProfileData to the ci equivalent. Generally speaking, // most ProfileData don't require any translation, so we provide the null // translation here, and the required translators are in the ci subclasses. virtual void translate_from(ProfileData* data) {} virtual void print_data_on(outputStream* st) { ShouldNotReachHere(); } #ifndef PRODUCT void print_shared(outputStream* st, const char* name); void tab(outputStream* st); #endif }; // BitData // // A BitData holds a flag or two in its header. class BitData : public ProfileData { protected: enum { // null_seen: // saw a null operand (cast/aastore/instanceof) null_seen_flag = DataLayout::first_flag + 0 }; enum { bit_cell_count = 0 }; // no additional data fields needed. public: BitData(DataLayout* layout) : ProfileData(layout) { } virtual bool is_BitData() { return true; } static int static_cell_count() { return bit_cell_count; } virtual int cell_count() { return static_cell_count(); } // Accessor // The null_seen flag bit is specially known to the interpreter. // Consulting it allows the compiler to avoid setting up null_check traps. bool null_seen() { return flag_at(null_seen_flag); } void set_null_seen() { set_flag_at(null_seen_flag); } // Code generation support static int null_seen_byte_constant() { return flag_number_to_byte_constant(null_seen_flag); } static ByteSize bit_data_size() { return cell_offset(bit_cell_count); } #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // CounterData // // A CounterData corresponds to a simple counter. class CounterData : public BitData { protected: enum { count_off, counter_cell_count }; public: CounterData(DataLayout* layout) : BitData(layout) {} virtual bool is_CounterData() { return true; } static int static_cell_count() { return counter_cell_count; } virtual int cell_count() { return static_cell_count(); } // Direct accessor uint count() { return uint_at(count_off); } // Code generation support static ByteSize count_offset() { return cell_offset(count_off); } static ByteSize counter_data_size() { return cell_offset(counter_cell_count); } void set_count(uint count) { set_uint_at(count_off, count); } #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // JumpData // // A JumpData is used to access profiling information for a direct // branch. It is a counter, used for counting the number of branches, // plus a data displacement, used for realigning the data pointer to // the corresponding target bci. class JumpData : public ProfileData { protected: enum { taken_off_set, displacement_off_set, jump_cell_count }; void set_displacement(int displacement) { set_int_at(displacement_off_set, displacement); } public: JumpData(DataLayout* layout) : ProfileData(layout) { assert(layout->tag() == DataLayout::jump_data_tag || layout->tag() == DataLayout::branch_data_tag, "wrong type"); } virtual bool is_JumpData() { return true; } static int static_cell_count() { return jump_cell_count; } virtual int cell_count() { return static_cell_count(); } // Direct accessor uint taken() { return uint_at(taken_off_set); } void set_taken(uint cnt) { set_uint_at(taken_off_set, cnt); } // Saturating counter uint inc_taken() { uint cnt = taken() + 1; // Did we wrap? Will compiler screw us?? if (cnt == 0) cnt--; set_uint_at(taken_off_set, cnt); return cnt; } int displacement() { return int_at(displacement_off_set); } // Code generation support static ByteSize taken_offset() { return cell_offset(taken_off_set); } static ByteSize displacement_offset() { return cell_offset(displacement_off_set); } // Specific initialization. void post_initialize(BytecodeStream* stream, MethodData* mdo); #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // ReceiverTypeData // // A ReceiverTypeData is used to access profiling information about a // dynamic type check. It consists of a counter which counts the total times // that the check is reached, and a series of (Klass*, count) pairs // which are used to store a type profile for the receiver of the check. class ReceiverTypeData : public CounterData { protected: enum { receiver0_offset = counter_cell_count, count0_offset, receiver_type_row_cell_count = (count0_offset + 1) - receiver0_offset }; public: ReceiverTypeData(DataLayout* layout) : CounterData(layout) { assert(layout->tag() == DataLayout::receiver_type_data_tag || layout->tag() == DataLayout::virtual_call_data_tag, "wrong type"); } virtual bool is_ReceiverTypeData() { return true; } static int static_cell_count() { return counter_cell_count + (uint) TypeProfileWidth * receiver_type_row_cell_count; } virtual int cell_count() { return static_cell_count(); } // Direct accessors static uint row_limit() { return TypeProfileWidth; } static int receiver_cell_index(uint row) { return receiver0_offset + row * receiver_type_row_cell_count; } static int receiver_count_cell_index(uint row) { return count0_offset + row * receiver_type_row_cell_count; } Klass* receiver(uint row) { assert(row < row_limit(), "oob"); Klass* recv = (Klass*)intptr_at(receiver_cell_index(row)); assert(recv == NULL || recv->is_klass(), "wrong type"); return recv; } void set_receiver(uint row, Klass* k) { assert((uint)row < row_limit(), "oob"); set_intptr_at(receiver_cell_index(row), (uintptr_t)k); } uint receiver_count(uint row) { assert(row < row_limit(), "oob"); return uint_at(receiver_count_cell_index(row)); } void set_receiver_count(uint row, uint count) { assert(row < row_limit(), "oob"); set_uint_at(receiver_count_cell_index(row), count); } void clear_row(uint row) { assert(row < row_limit(), "oob"); // Clear total count - indicator of polymorphic call site. // The site may look like as monomorphic after that but // it allow to have more accurate profiling information because // there was execution phase change since klasses were unloaded. // If the site is still polymorphic then MDO will be updated // to reflect it. But it could be the case that the site becomes // only bimorphic. Then keeping total count not 0 will be wrong. // Even if we use monomorphic (when it is not) for compilation // we will only have trap, deoptimization and recompile again // with updated MDO after executing method in Interpreter. // An additional receiver will be recorded in the cleaned row // during next call execution. // // Note: our profiling logic works with empty rows in any slot. // We do sorting a profiling info (ciCallProfile) for compilation. // set_count(0); set_receiver(row, NULL); set_receiver_count(row, 0); } // Code generation support static ByteSize receiver_offset(uint row) { return cell_offset(receiver_cell_index(row)); } static ByteSize receiver_count_offset(uint row) { return cell_offset(receiver_count_cell_index(row)); } static ByteSize receiver_type_data_size() { return cell_offset(static_cell_count()); } // GC support virtual void clean_weak_klass_links(BoolObjectClosure* is_alive_closure); #ifndef PRODUCT void print_receiver_data_on(outputStream* st); void print_data_on(outputStream* st); #endif }; // VirtualCallData // // A VirtualCallData is used to access profiling information about a // virtual call. For now, it has nothing more than a ReceiverTypeData. class VirtualCallData : public ReceiverTypeData { public: VirtualCallData(DataLayout* layout) : ReceiverTypeData(layout) { assert(layout->tag() == DataLayout::virtual_call_data_tag, "wrong type"); } virtual bool is_VirtualCallData() { return true; } static int static_cell_count() { // At this point we could add more profile state, e.g., for arguments. // But for now it's the same size as the base record type. return ReceiverTypeData::static_cell_count(); } virtual int cell_count() { return static_cell_count(); } // Direct accessors static ByteSize virtual_call_data_size() { return cell_offset(static_cell_count()); } #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // RetData // // A RetData is used to access profiling information for a ret bytecode. // It is composed of a count of the number of times that the ret has // been executed, followed by a series of triples of the form // (bci, count, di) which count the number of times that some bci was the // target of the ret and cache a corresponding data displacement. class RetData : public CounterData { protected: enum { bci0_offset = counter_cell_count, count0_offset, displacement0_offset, ret_row_cell_count = (displacement0_offset + 1) - bci0_offset }; void set_bci(uint row, int bci) { assert((uint)row < row_limit(), "oob"); set_int_at(bci0_offset + row * ret_row_cell_count, bci); } void release_set_bci(uint row, int bci) { assert((uint)row < row_limit(), "oob"); // 'release' when setting the bci acts as a valid flag for other // threads wrt bci_count and bci_displacement. release_set_int_at(bci0_offset + row * ret_row_cell_count, bci); } void set_bci_count(uint row, uint count) { assert((uint)row < row_limit(), "oob"); set_uint_at(count0_offset + row * ret_row_cell_count, count); } void set_bci_displacement(uint row, int disp) { set_int_at(displacement0_offset + row * ret_row_cell_count, disp); } public: RetData(DataLayout* layout) : CounterData(layout) { assert(layout->tag() == DataLayout::ret_data_tag, "wrong type"); } virtual bool is_RetData() { return true; } enum { no_bci = -1 // value of bci when bci1/2 are not in use. }; static int static_cell_count() { return counter_cell_count + (uint) BciProfileWidth * ret_row_cell_count; } virtual int cell_count() { return static_cell_count(); } static uint row_limit() { return BciProfileWidth; } static int bci_cell_index(uint row) { return bci0_offset + row * ret_row_cell_count; } static int bci_count_cell_index(uint row) { return count0_offset + row * ret_row_cell_count; } static int bci_displacement_cell_index(uint row) { return displacement0_offset + row * ret_row_cell_count; } // Direct accessors int bci(uint row) { return int_at(bci_cell_index(row)); } uint bci_count(uint row) { return uint_at(bci_count_cell_index(row)); } int bci_displacement(uint row) { return int_at(bci_displacement_cell_index(row)); } // Interpreter Runtime support address fixup_ret(int return_bci, MethodData* mdo); // Code generation support static ByteSize bci_offset(uint row) { return cell_offset(bci_cell_index(row)); } static ByteSize bci_count_offset(uint row) { return cell_offset(bci_count_cell_index(row)); } static ByteSize bci_displacement_offset(uint row) { return cell_offset(bci_displacement_cell_index(row)); } // Specific initialization. void post_initialize(BytecodeStream* stream, MethodData* mdo); #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // BranchData // // A BranchData is used to access profiling data for a two-way branch. // It consists of taken and not_taken counts as well as a data displacement // for the taken case. class BranchData : public JumpData { protected: enum { not_taken_off_set = jump_cell_count, branch_cell_count }; void set_displacement(int displacement) { set_int_at(displacement_off_set, displacement); } public: BranchData(DataLayout* layout) : JumpData(layout) { assert(layout->tag() == DataLayout::branch_data_tag, "wrong type"); } virtual bool is_BranchData() { return true; } static int static_cell_count() { return branch_cell_count; } virtual int cell_count() { return static_cell_count(); } // Direct accessor uint not_taken() { return uint_at(not_taken_off_set); } void set_not_taken(uint cnt) { set_uint_at(not_taken_off_set, cnt); } uint inc_not_taken() { uint cnt = not_taken() + 1; // Did we wrap? Will compiler screw us?? if (cnt == 0) cnt--; set_uint_at(not_taken_off_set, cnt); return cnt; } // Code generation support static ByteSize not_taken_offset() { return cell_offset(not_taken_off_set); } static ByteSize branch_data_size() { return cell_offset(branch_cell_count); } // Specific initialization. void post_initialize(BytecodeStream* stream, MethodData* mdo); #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // ArrayData // // A ArrayData is a base class for accessing profiling data which does // not have a statically known size. It consists of an array length // and an array start. class ArrayData : public ProfileData { protected: friend class DataLayout; enum { array_len_off_set, array_start_off_set }; uint array_uint_at(int index) { int aindex = index + array_start_off_set; return uint_at(aindex); } int array_int_at(int index) { int aindex = index + array_start_off_set; return int_at(aindex); } oop array_oop_at(int index) { int aindex = index + array_start_off_set; return oop_at(aindex); } void array_set_int_at(int index, int value) { int aindex = index + array_start_off_set; set_int_at(aindex, value); } // Code generation support for subclasses. static ByteSize array_element_offset(int index) { return cell_offset(array_start_off_set + index); } public: ArrayData(DataLayout* layout) : ProfileData(layout) {} virtual bool is_ArrayData() { return true; } static int static_cell_count() { return -1; } int array_len() { return int_at_unchecked(array_len_off_set); } virtual int cell_count() { return array_len() + 1; } // Code generation support static ByteSize array_len_offset() { return cell_offset(array_len_off_set); } static ByteSize array_start_offset() { return cell_offset(array_start_off_set); } }; // MultiBranchData // // A MultiBranchData is used to access profiling information for // a multi-way branch (*switch bytecodes). It consists of a series // of (count, displacement) pairs, which count the number of times each // case was taken and specify the data displacment for each branch target. class MultiBranchData : public ArrayData { protected: enum { default_count_off_set, default_disaplacement_off_set, case_array_start }; enum { relative_count_off_set, relative_displacement_off_set, per_case_cell_count }; void set_default_displacement(int displacement) { array_set_int_at(default_disaplacement_off_set, displacement); } void set_displacement_at(int index, int displacement) { array_set_int_at(case_array_start + index * per_case_cell_count + relative_displacement_off_set, displacement); } public: MultiBranchData(DataLayout* layout) : ArrayData(layout) { assert(layout->tag() == DataLayout::multi_branch_data_tag, "wrong type"); } virtual bool is_MultiBranchData() { return true; } static int compute_cell_count(BytecodeStream* stream); int number_of_cases() { int alen = array_len() - 2; // get rid of default case here. assert(alen % per_case_cell_count == 0, "must be even"); return (alen / per_case_cell_count); } uint default_count() { return array_uint_at(default_count_off_set); } int default_displacement() { return array_int_at(default_disaplacement_off_set); } uint count_at(int index) { return array_uint_at(case_array_start + index * per_case_cell_count + relative_count_off_set); } int displacement_at(int index) { return array_int_at(case_array_start + index * per_case_cell_count + relative_displacement_off_set); } // Code generation support static ByteSize default_count_offset() { return array_element_offset(default_count_off_set); } static ByteSize default_displacement_offset() { return array_element_offset(default_disaplacement_off_set); } static ByteSize case_count_offset(int index) { return case_array_offset() + (per_case_size() * index) + relative_count_offset(); } static ByteSize case_array_offset() { return array_element_offset(case_array_start); } static ByteSize per_case_size() { return in_ByteSize(per_case_cell_count) * cell_size; } static ByteSize relative_count_offset() { return in_ByteSize(relative_count_off_set) * cell_size; } static ByteSize relative_displacement_offset() { return in_ByteSize(relative_displacement_off_set) * cell_size; } // Specific initialization. void post_initialize(BytecodeStream* stream, MethodData* mdo); #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; class ArgInfoData : public ArrayData { public: ArgInfoData(DataLayout* layout) : ArrayData(layout) { assert(layout->tag() == DataLayout::arg_info_data_tag, "wrong type"); } virtual bool is_ArgInfoData() { return true; } int number_of_args() { return array_len(); } uint arg_modified(int arg) { return array_uint_at(arg); } void set_arg_modified(int arg, uint val) { array_set_int_at(arg, val); } #ifndef PRODUCT void print_data_on(outputStream* st); #endif }; // MethodData* // // A MethodData* holds information which has been collected about // a method. Its layout looks like this: // // ----------------------------- // | header | // | klass | // ----------------------------- // | method | // | size of the MethodData* | // ----------------------------- // | Data entries... | // | (variable size) | // | | // . . // . . // . . // | | // ----------------------------- // // The data entry area is a heterogeneous array of DataLayouts. Each // DataLayout in the array corresponds to a specific bytecode in the // method. The entries in the array are sorted by the corresponding // bytecode. Access to the data is via resource-allocated ProfileData, // which point to the underlying blocks of DataLayout structures. // // During interpretation, if profiling in enabled, the interpreter // maintains a method data pointer (mdp), which points at the entry // in the array corresponding to the current bci. In the course of // intepretation, when a bytecode is encountered that has profile data // associated with it, the entry pointed to by mdp is updated, then the // mdp is adjusted to point to the next appropriate DataLayout. If mdp // is NULL to begin with, the interpreter assumes that the current method // is not (yet) being profiled. // // In MethodData* parlance, "dp" is a "data pointer", the actual address // of a DataLayout element. A "di" is a "data index", the offset in bytes // from the base of the data entry array. A "displacement" is the byte offset // in certain ProfileData objects that indicate the amount the mdp must be // adjusted in the event of a change in control flow. // class MethodData : public Metadata { friend class VMStructs; private: friend class ProfileData; // Back pointer to the Method* Method* _method; // Size of this oop in bytes int _size; // Cached hint for bci_to_dp and bci_to_data int _hint_di; MethodData(methodHandle method, int size, TRAPS); public: static MethodData* allocate(ClassLoaderData* loader_data, methodHandle method, TRAPS); MethodData() {}; // For ciMethodData bool is_methodData() const volatile { return true; } // Whole-method sticky bits and flags enum { _trap_hist_limit = 17, // decoupled from Deoptimization::Reason_LIMIT _trap_hist_mask = max_jubyte, _extra_data_count = 4 // extra DataLayout headers, for trap history }; // Public flag values private: uint _nof_decompiles; // count of all nmethod removals uint _nof_overflow_recompiles; // recompile count, excluding recomp. bits uint _nof_overflow_traps; // trap count, excluding _trap_hist union { intptr_t _align; u1 _array[_trap_hist_limit]; } _trap_hist; // Support for interprocedural escape analysis, from Thomas Kotzmann. intx _eflags; // flags on escape information intx _arg_local; // bit set of non-escaping arguments intx _arg_stack; // bit set of stack-allocatable arguments intx _arg_returned; // bit set of returned arguments int _creation_mileage; // method mileage at MDO creation // How many invocations has this MDO seen? // These counters are used to determine the exact age of MDO. // We need those because in tiered a method can be concurrently // executed at different levels. InvocationCounter _invocation_counter; // Same for backedges. InvocationCounter _backedge_counter; // Counter values at the time profiling started. int _invocation_counter_start; int _backedge_counter_start; // Number of loops and blocks is computed when compiling the first // time with C1. It is used to determine if method is trivial. short _num_loops; short _num_blocks; // Highest compile level this method has ever seen. u1 _highest_comp_level; // Same for OSR level u1 _highest_osr_comp_level; // Does this method contain anything worth profiling? bool _would_profile; // Size of _data array in bytes. (Excludes header and extra_data fields.) int _data_size; // Beginning of the data entries intptr_t _data[1]; // Helper for size computation static int compute_data_size(BytecodeStream* stream); static int bytecode_cell_count(Bytecodes::Code code); enum { no_profile_data = -1, variable_cell_count = -2 }; // Helper for initialization DataLayout* data_layout_at(int data_index) const { assert(data_index % sizeof(intptr_t) == 0, "unaligned"); return (DataLayout*) (((address)_data) + data_index); } // Initialize an individual data segment. Returns the size of // the segment in bytes. int initialize_data(BytecodeStream* stream, int data_index); // Helper for data_at DataLayout* limit_data_position() const { return (DataLayout*)((address)data_base() + _data_size); } bool out_of_bounds(int data_index) const { return data_index >= data_size(); } // Give each of the data entries a chance to perform specific // data initialization. void post_initialize(BytecodeStream* stream); // hint accessors int hint_di() const { return _hint_di; } void set_hint_di(int di) { assert(!out_of_bounds(di), "hint_di out of bounds"); _hint_di = di; } ProfileData* data_before(int bci) { // avoid SEGV on this edge case if (data_size() == 0) return NULL; int hint = hint_di(); if (data_layout_at(hint)->bci() <= bci) return data_at(hint); return first_data(); } // What is the index of the first data entry? int first_di() const { return 0; } // Find or create an extra ProfileData: ProfileData* bci_to_extra_data(int bci, bool create_if_missing); // return the argument info cell ArgInfoData *arg_info(); public: static int header_size() { return sizeof(MethodData)/wordSize; } // Compute the size of a MethodData* before it is created. static int compute_allocation_size_in_bytes(methodHandle method); static int compute_allocation_size_in_words(methodHandle method); static int compute_extra_data_count(int data_size, int empty_bc_count); // Determine if a given bytecode can have profile information. static bool bytecode_has_profile(Bytecodes::Code code) { return bytecode_cell_count(code) != no_profile_data; } // Perform initialization of a new MethodData* void initialize(methodHandle method); // My size int size_in_bytes() const { return _size; } int size() const { return align_object_size(align_size_up(_size, BytesPerWord)/BytesPerWord); } #if INCLUDE_SERVICES void collect_statistics(KlassSizeStats *sz) const; #endif int creation_mileage() const { return _creation_mileage; } void set_creation_mileage(int x) { _creation_mileage = x; } int invocation_count() { if (invocation_counter()->carry()) { return InvocationCounter::count_limit; } return invocation_counter()->count(); } int backedge_count() { if (backedge_counter()->carry()) { return InvocationCounter::count_limit; } return backedge_counter()->count(); } int invocation_count_start() { if (invocation_counter()->carry()) { return 0; } return _invocation_counter_start; } int backedge_count_start() { if (backedge_counter()->carry()) { return 0; } return _backedge_counter_start; } int invocation_count_delta() { return invocation_count() - invocation_count_start(); } int backedge_count_delta() { return backedge_count() - backedge_count_start(); } void reset_start_counters() { _invocation_counter_start = invocation_count(); _backedge_counter_start = backedge_count(); } InvocationCounter* invocation_counter() { return &_invocation_counter; } InvocationCounter* backedge_counter() { return &_backedge_counter; } void set_would_profile(bool p) { _would_profile = p; } bool would_profile() const { return _would_profile; } int highest_comp_level() { return _highest_comp_level; } void set_highest_comp_level(int level) { _highest_comp_level = level; } int highest_osr_comp_level() { return _highest_osr_comp_level; } void set_highest_osr_comp_level(int level) { _highest_osr_comp_level = level; } int num_loops() const { return _num_loops; } void set_num_loops(int n) { _num_loops = n; } int num_blocks() const { return _num_blocks; } void set_num_blocks(int n) { _num_blocks = n; } bool is_mature() const; // consult mileage and ProfileMaturityPercentage static int mileage_of(Method* m); // Support for interprocedural escape analysis, from Thomas Kotzmann. enum EscapeFlag { estimated = 1 << 0, return_local = 1 << 1, return_allocated = 1 << 2, allocated_escapes = 1 << 3, unknown_modified = 1 << 4 }; intx eflags() { return _eflags; } intx arg_local() { return _arg_local; } intx arg_stack() { return _arg_stack; } intx arg_returned() { return _arg_returned; } uint arg_modified(int a) { ArgInfoData *aid = arg_info(); assert(a >= 0 && a < aid->number_of_args(), "valid argument number"); return aid->arg_modified(a); } void set_eflags(intx v) { _eflags = v; } void set_arg_local(intx v) { _arg_local = v; } void set_arg_stack(intx v) { _arg_stack = v; } void set_arg_returned(intx v) { _arg_returned = v; } void set_arg_modified(int a, uint v) { ArgInfoData *aid = arg_info(); assert(a >= 0 && a < aid->number_of_args(), "valid argument number"); aid->set_arg_modified(a, v); } void clear_escape_info() { _eflags = _arg_local = _arg_stack = _arg_returned = 0; } // Location and size of data area address data_base() const { return (address) _data; } int data_size() const { return _data_size; } // Accessors Method* method() const { return _method; } // Get the data at an arbitrary (sort of) data index. ProfileData* data_at(int data_index) const; // Walk through the data in order. ProfileData* first_data() const { return data_at(first_di()); } ProfileData* next_data(ProfileData* current) const; bool is_valid(ProfileData* current) const { return current != NULL; } // Convert a dp (data pointer) to a di (data index). int dp_to_di(address dp) const { return dp - ((address)_data); } address di_to_dp(int di) { return (address)data_layout_at(di); } // bci to di/dp conversion. address bci_to_dp(int bci); int bci_to_di(int bci) { return dp_to_di(bci_to_dp(bci)); } // Get the data at an arbitrary bci, or NULL if there is none. ProfileData* bci_to_data(int bci); // Same, but try to create an extra_data record if one is needed: ProfileData* allocate_bci_to_data(int bci) { ProfileData* data = bci_to_data(bci); return (data != NULL) ? data : bci_to_extra_data(bci, true); } // Add a handful of extra data records, for trap tracking. DataLayout* extra_data_base() const { return limit_data_position(); } DataLayout* extra_data_limit() const { return (DataLayout*)((address)this + size_in_bytes()); } int extra_data_size() const { return (address)extra_data_limit() - (address)extra_data_base(); } static DataLayout* next_extra(DataLayout* dp) { return (DataLayout*)((address)dp + in_bytes(DataLayout::cell_offset(0))); } // Return (uint)-1 for overflow. uint trap_count(int reason) const { assert((uint)reason < _trap_hist_limit, "oob"); return (int)((_trap_hist._array[reason]+1) & _trap_hist_mask) - 1; } // For loops: static uint trap_reason_limit() { return _trap_hist_limit; } static uint trap_count_limit() { return _trap_hist_mask; } uint inc_trap_count(int reason) { // Count another trap, anywhere in this method. assert(reason >= 0, "must be single trap"); if ((uint)reason < _trap_hist_limit) { uint cnt1 = 1 + _trap_hist._array[reason]; if ((cnt1 & _trap_hist_mask) != 0) { // if no counter overflow... _trap_hist._array[reason] = cnt1; return cnt1; } else { return _trap_hist_mask + (++_nof_overflow_traps); } } else { // Could not represent the count in the histogram. return (++_nof_overflow_traps); } } uint overflow_trap_count() const { return _nof_overflow_traps; } uint overflow_recompile_count() const { return _nof_overflow_recompiles; } void inc_overflow_recompile_count() { _nof_overflow_recompiles += 1; } uint decompile_count() const { return _nof_decompiles; } void inc_decompile_count() { _nof_decompiles += 1; if (decompile_count() > (uint)PerMethodRecompilationCutoff) { method()->set_not_compilable(CompLevel_full_optimization, true, "decompile_count > PerMethodRecompilationCutoff"); } } // Support for code generation static ByteSize data_offset() { return byte_offset_of(MethodData, _data[0]); } static ByteSize invocation_counter_offset() { return byte_offset_of(MethodData, _invocation_counter); } static ByteSize backedge_counter_offset() { return byte_offset_of(MethodData, _backedge_counter); } // Deallocation support - no pointer fields to deallocate void deallocate_contents(ClassLoaderData* loader_data) {} // GC support void set_size(int object_size_in_bytes) { _size = object_size_in_bytes; } // Printing #ifndef PRODUCT void print_on (outputStream* st) const; #endif void print_value_on(outputStream* st) const; #ifndef PRODUCT // printing support for method data void print_data_on(outputStream* st) const; #endif const char* internal_name() const { return "{method data}"; } // verification void verify_on(outputStream* st); void verify_data_on(outputStream* st); }; #endif // SHARE_VM_OOPS_METHODDATAOOP_HPP
karianna/jdk8_tl
hotspot/src/share/vm/oops/methodData.hpp
C++
gpl-2.0
46,319
/** * @license BitSet.js v4.0.1 14/08/2015 * http://www.xarg.org/2014/03/javascript-bit-array/ * * Copyright (c) 2016, Robert Eisele (robert@xarg.org) * Dual licensed under the MIT or GPL Version 2 licenses. **/ (function(root) { 'use strict'; /** * The number of bits of a word * @const * @type number */ var WORD_LENGTH = 32; /** * The log base 2 of WORD_LENGTH * @const * @type number */ var WORD_LOG = 5; /** * Calculates the number of set bits * * @param {number} v * @returns {number} */ function popCount(v) { // Warren, H. (2009). Hacker`s Delight. New York, NY: Addison-Wesley v -= ((v >>> 1) & 0x55555555); v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); return (((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24); } /** * Divide a number in base two by B * * @param {Array} arr * @param {number} B * @returns {number} */ function divide(arr, B) { var r = 0; var d; var i = 0; for (; i < arr.length; i++) { r *= 2; d = (arr[i] + r) / B | 0; r = (arr[i] + r) % B; arr[i] = d; } return r; } /** * Parses the parameters and set variable P * * @param {Object} P * @param {string|BitSet|Array|Uint8Array|number=} val */ function parse(P, val) { if (val == null) { P['data'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; P['_'] = 0; return; } if (val instanceof BitSet) { P['data'] = val['data']; P['_'] = val['_']; return; } switch (typeof val) { case 'number': P['data'] = [val | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; P['_'] = 0; break; case 'string': var base = 2; var len = WORD_LENGTH; if (val.indexOf('0b') === 0) { val = val.substr(2); } else if (val.indexOf('0x') === 0) { val = val.substr(2); base = 16; len = 8; } P['data'] = []; P['_'] = 0; var a = val.length - len; var b = val.length; do { var num = parseInt(val.slice(a > 0 ? a : 0, b), base); if (isNaN(num)) { throw SyntaxError('Invalid param'); } P['data'].push(num | 0); if (a <= 0) break; a -= len; b -= len; } while (1); break; default: P['data'] = [0]; var data = P['data']; if (val instanceof Array) { for (var i = val.length - 1; i >= 0; i--) { var ndx = val[i]; if (ndx === Infinity) { P['_'] = -1; } else { scale(P, ndx); data[ndx >>> WORD_LOG] |= 1 << ndx; } } break; } if (Uint8Array && val instanceof Uint8Array) { var bits = 8; scale(P, val.length * bits); for (var i = 0; i < val.length; i++) { var n = val[i]; for (var j = 0; j < bits; j++) { var k = i * bits + j; data[k >>> WORD_LOG] |= (n >> j & 1) << k; } } break; } throw SyntaxError('Invalid param'); } } /** * Module entry point * * @constructor * @param {string|BitSet|number=} param * @returns {BitSet} */ function BitSet(param) { if (!(this instanceof BitSet)) { return new BitSet(param); } parse(this, param); this['data'] = this['data'].slice(); } function scale(dst, ndx) { var l = ndx >>> WORD_LOG; var d = dst['data']; var v = dst['_']; for (var i = d.length; l >= i; l--) { d[l] = v; } } var P = { 'data': [], '_': 0 }; BitSet.prototype = { 'data': [], '_': 0, /** * Set a single bit flag * * Ex: * bs1 = new BitSet(10); * * bs1.set(3, 1); * * @param {number} ndx The index of the bit to be set * @param {number=} value Optional value that should be set on the index (0 or 1) * @returns {BitSet} this */ 'set': function(ndx, value) { ndx |= 0; scale(this, ndx); if (value === undefined || value) { this['data'][ndx >>> WORD_LOG] |= (1 << ndx); } else { this['data'][ndx >>> WORD_LOG] &= ~(1 << ndx); } return this; }, /** * Get a single bit flag of a certain bit position * * Ex: * bs1 = new BitSet(); * var isValid = bs1.get(12); * * @param {number} ndx the index to be fetched * @returns {number|null} The binary flag */ 'get': function(ndx) { ndx |= 0; var d = this['data']; var n = ndx >>> WORD_LOG; if (n > d.length) { return this['_'] & 1; } return (d[n] >>> ndx) & 1; }, /** * Creates the bitwise AND of two sets. The result is stored in-place. * * Ex: * bs1 = new BitSet(10); * bs2 = new BitSet(10); * * bs1.and(bs2); * * @param {BitSet} value A bitset object * @returns {BitSet} this */ 'and': function(value) {// intersection parse(P, value); var t = this['data']; var p = P['data']; var p_ = P['_']; var pl = p.length - 1; var tl = t.length - 1; if (p_ == 0) { // clear any bits set: for (var i = tl; i > pl; i--) { t[i] = 0; } } for (; i >= 0; i--) { t[i] &= p[i]; } this['_'] &= P['_']; return this; }, /** * Creates the bitwise OR of two sets. The result is stored in-place. * * Ex: * bs1 = new BitSet(10); * bs2 = new BitSet(10); * * bs1.or(bs2); * * @param {BitSet} val A bitset object * @returns {BitSet} this */ 'or': function(val) { // union parse(P, val); var t = this['data']; var p = P['data']; var pl = p.length - 1; var tl = t.length - 1; var minLength = Math.min(tl, pl); // Append backwards, extend array only once for (var i = pl; i > minLength; i--) { t[i] = p[i]; } for (; i >= 0; i--) { t[i] |= p[i]; } this['_'] |= P['_']; return this; }, /** * Creates the bitwise NOT of a set. The result is stored in-place. * * Ex: * bs1 = new BitSet(10); * * bs1.not(); * * @returns {BitSet} this */ 'not': function() { // invert() var d = this['data']; for (var i = 0; i < d.length; i++) { d[i] = ~d[i]; } this['_'] = ~this['_']; return this; }, /** * Creates the bitwise XOR of two sets. The result is stored in-place. * * Ex: * bs1 = new BitSet(10); * bs2 = new BitSet(10); * * bs1.xor(bs2); * * @param {BitSet} val A bitset object * @returns {BitSet} this */ 'xor': function(val) { // symmetric difference parse(P, val); var t = this['data']; var p = P['data']; var t_ = this['_']; var p_ = P['_']; var i = 0; var tl = t.length - 1; var pl = p.length - 1; // Cut if tl > pl for (i = tl; i > pl; i--) { t[i] ^= p_; } // Cut if pl > tl for (i = pl; i > tl; i--) { t[i] = t_ ^ p[i]; } // XOR the rest for (; i >= 0; i--) { t[i] ^= p[i]; } // XOR infinity this['_'] ^= p_; return this; }, /** * Flip/Invert a range of bits by setting * * Ex: * bs1 = new BitSet(); * bs1.flip(); // Flip entire set * bs1.flip(5); // Flip single bit * bs1.flip(3,10); // Flip a bit range * * @param {number=} from The start index of the range to be flipped * @param {number=} to The end index of the range to be flipped * @returns {BitSet} this */ 'flip': function(from, to) { if (from === undefined) { return this['not'](); } else if (to === undefined) { from |= 0; scale(this, from); this['data'][from >>> WORD_LOG] ^= (1 << from); } else if (from <= to && 0 <= from) { scale(this, to); for (var i = from; i <= to; i++) { this['data'][i >>> WORD_LOG] ^= (1 << i); } } return this; }, /** * Creates the bitwise AND NOT (not confuse with NAND!) of two sets. The result is stored in-place. * * Ex: * bs1 = new BitSet(10); * bs2 = new BitSet(10); * * bs1.notAnd(bs2); * * @param {BitSet} val A bitset object * @returns {BitSet} this */ 'andNot': function(val) { // difference parse(P, val); var t = this['data']; var p = P['data']; var t_ = this['_']; var p_ = P['_']; var l = Math.min(t.length, p.length); for (var k = 0; k < l; k++) { t[k] &= ~p[k]; } this['_'] &= ~p_; return this; }, /** * Clear a range of bits by setting it to 0 * * Ex: * bs1 = new BitSet(); * bs1.clear(); // Clear entire set * bs1.clear(5); // Clear single bit * bs1.clar(3,10); // Clear a bit range * * @param {number=} from The start index of the range to be cleared * @param {number=} to The end index of the range to be cleared * @returns {BitSet} this */ 'clear': function(from, to) { var data = this['data']; if (from === undefined) { for (var i = data.length - 1; i >= 0; i--) { data[i] = 0; } this['_'] = 0; } else if (to === undefined) { from |= 0; scale(this, from); data[from >>> WORD_LOG] &= ~(1 << from); } else if (from <= to) { scale(this, to); for (var i = from; i <= to; i++) { data[i >>> WORD_LOG] &= ~(1 << i); } } return this; }, /** * Gets an entire range as a new bitset object * * Ex: * bs1 = new BitSet(); * bs1.slice(4, 8); * * @param {number=} from The start index of the range to be get * @param {number=} to The end index of the range to be get * @returns {BitSet|Object} A new smaller bitset object, containing the extracted range */ 'slice': function(from, to) { if (from === undefined) { return this['clone'](); } else if (to === undefined) { to = this['data'].length * WORD_LENGTH; var im = Object.create(BitSet.prototype); im['_'] = this['_']; im['data'] = [0]; for (var i = from; i <= to; i++) { im['set'](i - from, this['get'](i)); } return im; } else if (from <= to && 0 <= from) { var im = Object.create(BitSet.prototype); im['data'] = [0]; for (var i = from; i <= to; i++) { im['set'](i - from, this['get'](i)); } return im; } return null; }, /** * Set a range of bits * * Ex: * bs1 = new BitSet(); * * bs1.setRange(10, 15, 1); * * @param {number} from The start index of the range to be set * @param {number} to The end index of the range to be set * @param {number} value Optional value that should be set on the index (0 or 1) * @returns {BitSet} this */ 'setRange': function(from, to, value) { for (var i = from; i <= to; i++) { this['set'](i, value); } return this; }, /** * Clones the actual object * * Ex: * bs1 = new BitSet(10); * bs2 = bs1.clone(); * * @returns {BitSet|Object} A new BitSet object, containing a copy of the actual object */ 'clone': function() { var im = Object.create(BitSet.prototype); im['data'] = this['data'].slice(); im['_'] = this['_']; return im; }, /** * Gets a list of set bits * * @returns {Array|number} */ 'toArray': Math['clz32'] ? function() { var ret = []; var data = this['data']; for (var i = data.length - 1; i >= 0; i--) { var num = data[i]; while (num !== 0) { var t = 31 - Math['clz32'](num); num ^= 1 << t; ret.unshift((i * WORD_LENGTH) + t); } } if (this['_'] !== 0) ret.push(Infinity); return ret; } : function() { var ret = []; var data = this['data']; for (var i = 0; i < data.length; i++) { var num = data[i]; while (num !== 0) { var t = num & -num; num ^= t; ret.push((i * WORD_LENGTH) + popCount(t - 1)); } } if (this['_'] !== 0) ret.push(Infinity); return ret; }, /** * Overrides the toString method to get a binary representation of the BitSet * * @param {number=} base * @returns string A binary string */ 'toString': function(base) { var data = this['data']; if (!base) base = 2; // If base is power of two if ((base & (base - 1)) === 0 && base < 36) { var ret = ''; var len = 2 + Math.log(4294967295/*Math.pow(2, WORD_LENGTH)-1*/) / Math.log(base) | 0; for (var i = data.length - 1; i >= 0; i--) { var cur = data[i]; // Make the number unsigned if (cur < 0) cur += 4294967296 /*Math.pow(2, WORD_LENGTH)*/; var tmp = cur.toString(base); if (ret !== '') { // Fill small positive numbers with leading zeros. The +1 for array creation is added outside already ret += new Array(len - tmp.length).join('0'); } ret += tmp; } if (this['_'] === 0) { ret = ret.replace(/^0+/, ''); if (ret === '') ret = '0'; return ret; } else { // Pad the string with ones ret = '1111' + ret; return ret.replace(/^1+/, '...1111'); } } else { if ((2 > base || base > 36)) throw 'Invalid base'; var ret = []; var arr = []; // Copy every single bit to a new array for (var i = data.length; i--; ) { for (var j = WORD_LENGTH; j--; ) { arr.push(data[i] >>> j & 1); } } do { ret.unshift(divide(arr, base).toString(base)); } while (!arr.every(function(x) { return x === 0; })); return ret.join(''); } }, /** * Check if the BitSet is empty, means all bits are unset * * Ex: * bs1 = new BitSet(10); * * bs1.isEmpty() ? 'yes' : 'no' * * @returns {boolean} Whether the bitset is empty */ 'isEmpty': function() { if (this['_'] !== 0) return false; var d = this['data']; for (var i = d.length - 1; i >= 0; i--) { if (d[i] !== 0) return false; } return true; }, /** * Calculates the number of bits set * * Ex: * bs1 = new BitSet(10); * * var num = bs1.cardinality(); * * @returns {number} The number of bits set */ 'cardinality': function() { if (this['_'] !== 0) { return Infinity; } var s = 0; var d = this['data']; for (var i = 0; i < d.length; i++) { var n = d[i]; if (n !== 0) s += popCount(n); } return s; }, /** * Calculates the Most Significant Bit / log base two * * Ex: * bs1 = new BitSet(10); * * var logbase2 = bs1.msb(); * * var truncatedTwo = Math.pow(2, logbase2); // May overflow! * * @returns {number} The index of the highest bit set */ 'msb': Math['clz32'] ? function() { if (this['_'] !== 0) { return Infinity; } var data = this['data']; for (var i = data.length; i-- > 0; ) { var c = Math['clz32'](data[i]); if (c !== WORD_LENGTH) { return (i * WORD_LENGTH) + WORD_LENGTH - 1 - c; } } return Infinity; } : function() { if (this['_'] !== 0) { return Infinity; } var data = this['data']; for (var i = data.length; i-- > 0; ) { var v = data[i]; var c = 0; if (v) { for (; (v >>>= 1) > 0; c++) { } return (i * WORD_LENGTH) + c; } } return Infinity; }, /** * Calculates the number of trailing zeros * * Ex: * bs1 = new BitSet(10); * * var ntz = bs1.ntz(); * * @returns {number} The index of the lowest bit set */ 'ntz': function() { var data = this['data']; for (var j = 0; j < data.length; j++) { var v = data[j]; if (v !== 0) { v = (v ^ (v - 1)) >>> 1; // Set v's trailing 0s to 1s and zero rest return (j * WORD_LENGTH) + popCount(v); } } return Infinity; }, /** * Calculates the Least Significant Bit * * Ex: * bs1 = new BitSet(10); * * var lsb = bs1.lsb(); * * @returns {number} The index of the lowest bit set */ 'lsb': function() { var data = this['data']; for (var i = 0; i < data.length; i++) { var v = data[i]; var c = 0; if (v) { var bit = (v & -v); for (; (bit >>>= 1); c++) { } return WORD_LENGTH * i + c; } } return this['_'] & 1; }, /** * Compares two BitSet objects * * Ex: * bs1 = new BitSet(10); * bs2 = new BitSet(10); * * bs1.equals(bs2) ? 'yes' : 'no' * * @param {BitSet} val A bitset object * @returns {boolean} Whether the two BitSets are similar */ 'equals': function(val) { parse(P, val); var t = this['data']; var p = P['data']; var t_ = this['_']; var p_ = P['_']; var tl = t.length - 1; var pl = p.length - 1; if (p_ !== t_) { return false; } var minLength = tl < pl ? tl : pl; for (var i = 0; i <= minLength; i++) { if (t[i] !== p[i]) return false; } for (i = tl; i > pl; i--) { if (t[i] !== p_) return false; } for (i = pl; i > tl; i--) { if (p[i] !== t_) return false; } return true; } }; BitSet.fromBinaryString = function(str) { return new BitSet('0b' + str); }; BitSet.fromHexString = function(str) { return new BitSet('0x' + str); }; if (typeof define === 'function' && define['amd']) { define([], function() { return BitSet; }); } else if (typeof exports === 'object') { module['exports'] = BitSet; } else { root['BitSet'] = BitSet; } })(this);
dashuo556/pkbitmap
bitset.js
JavaScript
gpl-2.0
19,561
package cz.cestadomu.hospis.mock; import static cz.cestadomu.hospis.mock.Mock.BACKEND_GET_VIEW_X_EMPLOYEES_RESPONSE_MOCK; import static cz.cestadomu.hospis.mock.Mock.BACKEND_LOGIN_RESPONSE_MOCK; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component("backendMockResponse") public class BackendMockResponse { private static final Logger LOG = LoggerFactory.getLogger(BackendMockResponse.class); public String mock(Mock mockResponseResource, String request) { LOG.info("Recieved request to backend mock component:\n{}", request); String response; try { response = IOUtils.toString(mockResponseResource.resourceUrl()); LOG.info("Returning mock response from backend component:\n{}", response); return response; } catch (IOException e) { throw new RuntimeException("Unable to return mock response from backend component.", e); } } public String login(String request) { return mock(BACKEND_LOGIN_RESPONSE_MOCK, request); } public String getViewX(String request) { return mock(BACKEND_GET_VIEW_X_EMPLOYEES_RESPONSE_MOCK, request); } }
calaveraInfo/hospis
core/mock/src/main/java/cz/cestadomu/hospis/mock/BackendMockResponse.java
Java
gpl-2.0
1,197
/* * Renjin : JVM-based interpreter for the R language for the statistical analysis * Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, a copy is available at * https://www.gnu.org/licenses/gpl-2.0.txt */ package org.renjin.primitives.sequence; import org.renjin.sexp.AttributeMap; import org.renjin.sexp.StringVector; import org.renjin.sexp.Vector; public class RepStringVector extends StringVector { public Vector source; private int sourceLength; private int length; private int each; public RepStringVector(Vector source, int length, int each, AttributeMap attributes) { super(attributes); this.source = source; this.sourceLength = source.length(); this.length = length; this.each = each; } private RepStringVector(String constant, int length) { super(AttributeMap.EMPTY); this.source = StringVector.valueOf(constant); this.sourceLength = source.length(); this.length = length; this.each = 1; } @Override public int length() { return length; } @Override protected StringVector cloneWithNewAttributes(AttributeMap attributes) { return new RepStringVector(source, length, each, attributes); } @Override public String getElementAsString(int index) { sourceLength = source.length(); return source.getElementAsString( (index / each) % sourceLength); } @Override public boolean isConstantAccessTime() { return true; } public static StringVector createConstantVector(String constant, int length) { if (length <= 0) { return StringVector.EMPTY; } return new RepStringVector(constant, length); } }
bedatadriven/renjin
core/src/main/java/org/renjin/primitives/sequence/RepStringVector.java
Java
gpl-2.0
2,266
package com.yongk.pattern.chainOfResponsibility; public class LimitSupport extends Support { private int limit; public LimitSupport(String name, int limit) { super(name); this.limit = limit; } public LimitSupport(String name) { super(name); } @Override public boolean resolve(Trouble t) { if (t.getNumber() < limit) return true; return false; } }
tturbs/pattern
src/com/yongk/pattern/chainOfResponsibility/LimitSupport.java
Java
gpl-2.0
375
/* cddrevs.C: Reverse Search Procedures for cdd.C written by Komei Fukuda, fukuda@ifor.math.ethz.ch Version 0.77, August 19, 2003 */ /* cdd.C : C-Implementation of the double description method for computing all vertices and extreme rays of the polyhedron P= {x : b - A x >= 0}. Please read COPYING (GNU General Public Licence) and the manual cddman.tex for detail. */ #include <fstream> #include <string> using namespace std; #include "cddtype.h" #include "cddrevs.h" extern "C" { #include "setoper.h" /* set operation library header (Ver. May 14,1995 or later) */ #include "cdddef.h" #include "cdd.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> } /* end of extern "C" */ topeOBJECT::topeOBJECT(const topeOBJECT& tope) { long j; dim=tope.dim; sv = new int[dim]; for (j=1;j<=dim;j++) sv[j-1]=tope.sv[j-1]; } void topeOBJECT::operator=(const topeOBJECT& tope) { long j; delete[] sv; dim = tope.dim; sv = new int[dim]; for (j=1;j<=dim;j++) sv[j-1]=tope.sv[j-1]; } int topeOBJECT::operator[](long j) // return the i-th component of tope { if (j>=1 && j<=dim) return sv[j-1];else return 0; } topeOBJECT operator-(topeOBJECT tope, long j) // reversing the sign of sv[j-1] { topeOBJECT t=tope; if (j>=1 && j<=t.dim) t.sv[j-1]=-t.sv[j-1]; return t; } void topeOBJECT::fwrite(ostream& f) { long j; for (j=1; j<=this->dim; j++) { if (this->sv[j-1] > 0) f << " +"; if (this->sv[j-1] < 0) f << " -"; if (this->sv[j-1] ==0) f << " 0"; } } int operator==(const topeOBJECT &t1, const topeOBJECT &t2) { long j=1; int equal=1; if (t1.dim != t2.dim) return 0; else { while (equal && j<=t1.dim) { if (t1.sv[j-1] != t2.sv[j-1]) equal=0; j++; } } return equal; } int operator!=(const topeOBJECT &t1, const topeOBJECT &t2) { if (t1==t2) return 0; else return 1; } topeOBJECT f(topeOBJECT v) { long i=1, nexti=0; while (nexti==0 && i<=v.dim) { if (v[i]<0 && Facet_Q(v,i)) nexti=i; i++; } if (nexti==0) return v; else return v-nexti; } long NeighbourIndex(topeOBJECT u, topeOBJECT v) { long i=1,nindex=0; while ( nindex==0 && i <= v.dim) { if (u==v-i) nindex = i; i++; } return nindex; } topeOBJECT Adj(topeOBJECT v, long i) { if (i<=0 || i>v.dim || v[i] <= 0) return v; else if (Facet_Q(v, i)) return v-i; else return v; } void ReverseSearch(ostream &wf, topeOBJECT s, long delta) { topeOBJECT v=s,u=s,w=s; long j=0,count=1,fcount=0; boolean completed=False; cout << "\nReverse search starts with #1 object: "; s.fwrite(cout); if (CondensedListOn) { wf << "begin\n" << " ***** " << delta << " tope_condensed\n"; }else{ wf << "begin\n" << " ***** " << delta << " tope\n"; } s.fwrite(wf); while (!completed) { while (j<delta) { j=j+1; w=Adj(v,j); if (w!=v && f(w)==v) { count++; if (CondensedListOn){ cout << "\n #" << count << " r " << j << " f " << fcount; wf << "\n r " << j << " f " << fcount; } else { cout << "\nA new object #" << count << " found: "; w.fwrite(cout); wf << "\n"; w.fwrite(wf); } v=w; j=0; fcount=0; } } if (!(v==s)) { u=v; v=f(v); j=NeighbourIndex(u,v); fcount++; if (j==delta) completed=True; } } wf << "\nend"; cout << "\nNumber ***** of topes = " << count << "\n"; wf << "\nNumber ***** of topes = " << count << "\n"; } // Facet recognition programs using Linear Programming boolean Facet_Q(topeOBJECT tope, rowrange ii) { static colindex nbindex; /* NBIndex[s] stores the nonbasic variable in column s */ static Arow LPdsol; /* LP solution and the dual solution (basic var only) */ static colrange nlast=0; if (nlast!=nn){ if (nlast>0){ delete[] LPdsol; } LPdsol = new myTYPE[nn]; nlast=nn; } return Facet_Q2(tope,ii,nbindex,LPdsol); } boolean Facet_Q2(topeOBJECT tope, rowrange ii, colindex NBIndex, Arow LPdsol) { /* Before calling this, LPdsol must be initialized with LPdsol = new myTYPE[nn]. When ii is detected to be non-facet, NBIndex returns the nonbasic variables at the evidence solution. LPdsol returns the evidence dual solution. */ static Arow LPsol; /* LP solution and the dual solution (basic var only) */ rowrange re; /* evidence row when LP is inconsistent */ colrange se; /* evidence col when LP is dual-inconsistent */ colrange s=0; myTYPE ov=0, tempRHS=0, purezero=0, pureone=1; /* ov = LP optimum value */ long LPiter,testi, i, j; boolean answer=True,localdebug=False; static colrange nlast=0; static Bmatrix BInv; static boolean firstcall=True, UsePrevBasis; static ConversionType ConversionSave; if (nlast!=nn){ if (nlast>0){ delete[] LPsol; free_Bmatrix(BInv); } InitializeBmatrix(BInv); LPsol = new myTYPE[nn]; nlast=nn; firstcall=True; } // if (firstcall || Conversion==TopeListing) // UsePrevBasis=False; else UsePrevBasis=True; UsePrevBasis=False; ConversionSave=Conversion; Conversion=LPmax; RHScol=1; mm=mm+1; OBJrow=mm; AA[OBJrow-1]=new myTYPE[nn]; if (localdebug) cout << "Facet_Q: create an exra row " << OBJrow << "\n"; for (i=1; i<=mm; i++) { if (tope[i]<0) { if (debug) cout << "reversing the signs of " << i << "th inequality\n"; for (s=0,j=1; j<=nn; j++){ AA[i-1][j-1]=-AA[i-1][j-1]; } } } tempRHS=AA[ii-1][0]; for (s=0,j=1; j<=nn; j++){ AA[OBJrow-1][j-1]=-AA[ii-1][j-1]; if (!firstcall && NBIndex[j]==ii){ s=j; if (localdebug) cout << "Row "<< ii << " is nonbasic" << s << "\n"; } } AA[OBJrow-1][0]=purezero; AA[ii-1][0]=tempRHS+pureone; /* relax the ii-th inequality by a large number*/ if (s>0) GausianColumnPivot2(AA,BInv, ii, s); DualSimplexMaximize(cout, cout, AA, BInv, OBJrow, RHScol, UsePrevBasis, &LPStatus, &ov, LPsol, LPdsol,NBIndex, &re, &se, &LPiter); if (LPStatus!=Optimal){ if (DynamicWriteOn) cout << "The Dual Simplex failed. Run the Criss-Cross method.\n"; CrissCrossMaximize(cout, cout, AA, BInv, OBJrow, RHScol, UsePrevBasis, &LPStatus, &ov, LPsol, LPdsol,NBIndex, &re, &se, &LPiter); } if (localdebug) cout << ii << "-th LP solved with objective value =" << ov << " RHS value = " << tempRHS << " iter= " << LPiter << "\n"; if ((ov - tempRHS) > zero) { answer=True; if (localdebug) cout << ii << "-th inequality determines a facet.\n"; } else { answer=False; if (localdebug) cout << ii << "-th inequality does not determine a facet.\n"; } AA[ii-1][0]=tempRHS; /* restore the original RHS */ for (s=0,j=1; j<=nn; j++){ if (NBIndex[j]==ii){ s=j; } } if (s>0){ if (localdebug) cout << "Row "<< ii << " is nonbasic: basisinv updated " << s << "\n"; GausianColumnPivot2(AA,BInv, ii, s); } delete[] AA[OBJrow-1]; if (localdebug) cout << "Facet_Q: delete the exra row " << OBJrow << "\n"; mm=mm-1; for (i=1; i<=mm; i++) { if (tope[i]<0) { for (j=1; j<=nn; j++) AA[i-1][j-1]=-AA[i-1][j-1]; /* restore the original data */ } } firstcall=False; Conversion=ConversionSave; return answer; } void FacetandVertexListMain(ostream &f, ostream &f_log) { rowrange i; colrange j; rowset subrows; /* rows which define a facet inequality */ colset allcols; /* allcols: all column indices */ rowindex rowequiv; rowrange classno; topeOBJECT Tope(mm); Arow LPdsol,center; static colindex NBIndex; LPdsol = new myTYPE[nn]; center = new myTYPE[nn]; WriteProgramDescription(f); (f) << "*Input File:" << inputfile << "(" << minput << "x" << ninput << ")\n"; WriteRunningMode(f); WriteRunningMode(f_log); if (Conversion==VertexListing){ ShiftPointsAroundOrigin(f,f_log, center); /* Shifting the points so that the origin will be in the relative interior of their convex hull */ } (f) << "* `e` means essential and `r` means redundant.\n"; if (DynamicWriteOn) cout << "* `e` means essential and `r` means redundant.\n"; rowequiv = new long[mm+1]; // FindRowEquivalenceClasses(&classno, rowequiv); // if (classno<mm) { // cout << "*There are multiple equivalent rows!!!\n"; // cout << "*You have to remove duplicates before listing facets. \n"; // (f) << "*There are multiple equivalent rows!!!\n"; // (f) << "*You have to remove duplicates before listing facets. \n"; // WriteRowEquivalence(cout, classno, rowequiv); // WriteRowEquivalence(f, classno, rowequiv); // goto _L99; // } time(&starttime); set_initialize(&subrows,mm); set_initialize(&allcols,nn); for (j=1;j<=nn;j++) set_addelem(allcols,j); if (Inequality==ZeroRHS){ printf("Sorry, facet/vertex listing is not implemented for RHS==0.\n"); goto _L99; } (f) << "begin\n"; if (DynamicWriteOn) (cout) <<"begin\n"; for (i=1; i<=mm; i++){ if (Facet_Q2(Tope, i, NBIndex, LPdsol)) { if (DynamicWriteOn) cout << i << " e:"; (f) << i << " e:"; set_addelem(subrows,i); } else { (f) << i << " r:"; if (DynamicWriteOn) (cout) << i << " r:"; } for (j=1; j<nn; j++){ (f) << " " << NBIndex[j+1]; if (LogWriteOn){ (f) <<"("; WriteNumber(f,LPdsol[j]); (f) << ")"; } } (f) << "\n"; if (DynamicWriteOn){ for (j=1; j<nn; j++){ (cout) << " " << NBIndex[j+1]; if (LogWriteOn){ (cout) <<"("; WriteNumber(cout,LPdsol[j]); (cout) << ")"; } } (cout) << "\n"; } } (f) << "end\n"; if (DynamicWriteOn) (cout) <<"end\n"; time(&endtime); // (f) << "* Here is a minimal system representing the same polyhedral set as the input.\n"; // WriteSubMatrixOfAA(f,subrows,allcols,Inequality); WriteTimes(f); WriteTimes(f_log); WriteTimes(cout); // set_free(&subrows); // set_free(&allcols); _L99:; // delete[] rowequiv; // delete[] LPdsol; // delete[] center; } void FacetandVertexExternalListMain(ostream &f, ostream &f_log) { rowrange i,mmxtn; colrange j,nnxtn; rowset subrows; /* rows which define a facet inequality */ colset allcols; /* allcols: all column indices */ rowindex rowequiv; rowrange classno; topeOBJECT Tope(mm); Arow LPdsol,center; static colindex NBIndex; string xtnnumbertype,command; myRational rvalue=0; myTYPE value=0; boolean found,localdebug=False; char ch; SetReadFileName(xtnfile,'x',"external"); ifstream reading_xtn(xtnfile); if (reading_xtn.is_open()) { found=False; while (!found) { if (!reading_xtn.eof()) { reading_xtn >> command; if (command=="begin") { found=True; } } else { Error=ImproperInputFormat; goto _L99; } } reading_xtn >> mmxtn; reading_xtn >> nnxtn; reading_xtn >> xtnnumbertype; LPdsol = new myTYPE[nn]; center = new myTYPE[nn]; WriteProgramDescription(f); (f) << "*Essential File:" << inputfile << "(" << minput << "x" << ninput << ")\n"; (f) << "*Input File:" << xtnfile << "(" << mmxtn << "x" << nnxtn << ")\n"; WriteRunningMode(f); WriteRunningMode(f_log); if (Conversion==VertexListingExternal){ ShiftPointsAroundOrigin(f,f_log, center); /* Shifting the points so that the origin will be in the relative interior of their convex hull */ } (f) << "* `e` means essential and `r` means redundant.\n"; /* Extrarow to store each line from the external file */ mm = minput + 1; AA[mm-1]= new myTYPE[ninput]; time(&starttime); set_initialize(&subrows,mm); set_initialize(&allcols,nn); for (j=1;j<=nn;j++) set_addelem(allcols,j); if (Inequality==ZeroRHS){ printf("Sorry, facet/vertex listing is not implemented for RHS==0.\n"); goto _L99; } (f) << "begin\n"; if (DynamicWriteOn) (cout) <<"begin\n"; for (i=1; i<=mmxtn; i++){ for (j = 1; j <= nn; j++) { if (xtnnumbertype=="rational" && OutputNumberString=="real"){ reading_xtn >> rvalue; value=myTYPE(rvalue); } else { reading_xtn >> value; } AA[mm-1][j - 1] = value; if (localdebug){ if (xtnnumbertype=="rational" && OutputNumberString=="real") cout << "a(" << i << "," << j << ") = " << value << " ("<< rvalue << ")\n"; else cout << "a(" << i << "," << j << ") = " << value << "\n"; } } /*of j*/ while (reading_xtn.get(ch) && ch != '\n') { if (localdebug) cout << ch; } if (Conversion==VertexListingExternal){ /* Each point must be shifted w.r.t the relative interior of their convex hull */ for (j=2; j<=nn; j++){AA[mm-1][j-1]-=center[j-1];} if (localdebug){ for (j=1; j<=nn; j++){cout << " " << AA[mm-1][j-1];} cout << " " << i << "th point Shifted.\n"; } } if (Facet_Q2(Tope, mm, NBIndex, LPdsol)) { if (DynamicWriteOn) cout << i << " e:"; (f) << i << " e:"; set_addelem(subrows,i); } else { (f) << i << " r:"; if (DynamicWriteOn) (cout) << i << " r:"; } long poscomp_count=0,rindex=0; for (j=1; j<nn; j++){ (f) << " " << NBIndex[j+1]; if (LPdsol[j]>zero) {poscomp_count++; rindex=NBIndex[j+1];}; if (LogWriteOn){ (f) <<"("; WriteNumber(f,LPdsol[j]); (f) << ")"; } } if (poscomp_count==1 && RowEquivalent_Q(AA[mm-1],AA[rindex-1], nn)) { (f) << " =#" << rindex; } else {poscomp_count=0;} (f) << "\n"; if (DynamicWriteOn){ for (j=1; j<nn; j++){ (cout) << " " << NBIndex[j+1]; if (LogWriteOn){ (cout) <<"("; WriteNumber(cout,LPdsol[j]); (cout) << ")"; } } if (poscomp_count==1) cout << " =#" << rindex; (cout) << "\n"; } } (f) << "end\n"; if (DynamicWriteOn) (cout) <<"end\n"; time(&endtime); WriteTimes(f); WriteTimes(f_log); WriteTimes(cout); _L99:; reading_xtn.close(); } else { Error=FileNotFound; WriteErrorMessages(cout); WriteErrorMessages(f_log); } } void TopeListMain(ostream &f, ostream &f_log) { rowrange i; colrange j; rowset subrows; /* rows which define a facet inequality */ colset allcols; /* allcols: all column indices */ rowindex rowequiv; rowrange classno; topeOBJECT Tope(mm); WriteProgramDescription(f); (f) << "*Input File:" << inputfile << "(" << minput << "x" << ninput << ")\n"; WriteRunningMode(f); WriteRunningMode(f_log); rowequiv = new long[mm+1]; FindRowEquivalenceClasses(&classno, rowequiv); if (classno<mm) { cout << "*There are multiple equivalent rows!!!\n"; cout << "*You have to remove duplicates before listing topes. \n"; (f) << "*There are multiple equivalent rows!!!\n"; (f) << "*You have to remove duplicates before listing topes. \n"; WriteRowEquivalence(cout, classno, rowequiv); WriteRowEquivalence(f, classno, rowequiv); goto _L99; } time(&starttime); set_initialize(&subrows,mm); set_initialize(&allcols,nn); for (j=1;j<=nn;j++) set_addelem(allcols,j); if (Inequality==ZeroRHS){ printf("Sorry, tope listing is not implemented for RHS==0.\n"); } else { ReverseSearch(f, Tope,mm); } time(&endtime); WriteTimes(f); WriteTimes(f_log); WriteTimes(cout); set_free(&subrows); set_free(&allcols); _L99:; delete[] rowequiv; } // end of cddrevs.C
bchretien/cddplus
cddrevs.C
C++
gpl-2.0
15,666
/** Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Oct 26, 2011 */ package com.bigdata.rdf.sparql.ast.optimizers; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import org.openrdf.model.Literal; import org.openrdf.model.URI; import com.bigdata.bop.BOp; import com.bigdata.bop.BOpUtility; import com.bigdata.bop.IBindingSet; import com.bigdata.bop.IValueExpression; import com.bigdata.rdf.model.BigdataURI; import com.bigdata.rdf.model.BigdataValue; import com.bigdata.rdf.sparql.ast.ASTBase; import com.bigdata.rdf.sparql.ast.ConstantNode; import com.bigdata.rdf.sparql.ast.FilterNode; import com.bigdata.rdf.sparql.ast.GraphPatternGroup; import com.bigdata.rdf.sparql.ast.IGroupMemberNode; import com.bigdata.rdf.sparql.ast.IQueryNode; import com.bigdata.rdf.sparql.ast.IValueExpressionNode; import com.bigdata.rdf.sparql.ast.NamedSubqueriesNode; import com.bigdata.rdf.sparql.ast.NamedSubqueryRoot; import com.bigdata.rdf.sparql.ast.QueryBase; import com.bigdata.rdf.sparql.ast.QueryHints; import com.bigdata.rdf.sparql.ast.QueryNodeWithBindingSet; import com.bigdata.rdf.sparql.ast.QueryRoot; import com.bigdata.rdf.sparql.ast.StatementPatternNode; import com.bigdata.rdf.sparql.ast.SubqueryFunctionNodeBase; import com.bigdata.rdf.sparql.ast.SubqueryRoot; import com.bigdata.rdf.sparql.ast.TermNode; import com.bigdata.rdf.sparql.ast.VarNode; import com.bigdata.rdf.sparql.ast.eval.AST2BOpContext; import com.bigdata.rdf.sparql.ast.hints.IQueryHint; import com.bigdata.rdf.sparql.ast.hints.QueryHintException; import com.bigdata.rdf.sparql.ast.hints.QueryHintRegistry; import com.bigdata.rdf.sparql.ast.hints.QueryHintScope; import com.bigdata.rdf.sparql.ast.service.ServiceNode; /** * Query hints are identified applied to AST nodes based on the specified scope * and the location within the AST in which they are found. Query hints * recognized by this optimizer have the form: * * <pre> * scopeURL propertyURL value * </pre> * * Where <i>scope</i> is any of the {@link QueryHintScope}s; and <br/> * Where <i>propertyURL</i> identifies the query hint;<br/> * Where <i>value</i> is a literal. * <p> * Once recognized, query hints are removed from the AST. All query hints are * declared internally using interfaces. It is an error if the specified query * hint has not been registered with the {@link QueryHintRegistry}, if the * {@link IQueryHint} can not validate the value, if the {@link QueryHintScope} * is not legal for the {@link IQueryHint}, etc. * <p> * For example: * * <pre> * ... * { * # query hint binds for this join group. * hint:Group hint:com.bigdata.bop.PipelineOp.maxParallel 10 * * ... * * # query hint binds for the next basic graph pattern in this join group. * hint:Prior hint:com.bigdata.relation.accesspath.IBuffer.chunkCapacity 100 * * ?x rdf:type foaf:Person . * } * </pre> * * @see QueryHints * @see QueryHintScope * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> */ public class ASTQueryHintOptimizer implements IASTOptimizer { private static final Logger log = Logger .getLogger(ASTQueryHintOptimizer.class); @SuppressWarnings("unchecked") @Override public QueryNodeWithBindingSet optimize( final AST2BOpContext context, final QueryNodeWithBindingSet input) { final IQueryNode queryNode = input.getQueryNode(); final IBindingSet[] bindingSets = input.getBindingSets(); final QueryRoot queryRoot = (QueryRoot) queryNode; if (context.queryHints != null && !context.queryHints.isEmpty()) { // Apply any given query hints globally. applyGlobalQueryHints(context, queryRoot, context.queryHints); } // First, process any pre-existing named subqueries. { final NamedSubqueriesNode namedSubqueries = queryRoot .getNamedSubqueries(); if (namedSubqueries != null) { for (NamedSubqueryRoot namedSubquery : namedSubqueries) { processGroup(context, queryRoot, namedSubquery, namedSubquery.getWhereClause()); } } } // Now process the main where clause. processGroup(context, queryRoot, queryRoot, queryRoot.getWhereClause()); return new QueryNodeWithBindingSet(queryNode, bindingSets); } /** * Tnis is used to avoid descent into parts of the AST which can not have * query hints, such as value expressions. */ private boolean isNodeAcceptingQueryHints(final BOp op) { /** * Note: Historically, only visited QueryNodeBase, but that does not let * query hints be applied to a variety of relevant AST nodes, including * the SliceOp. The new pattern is to exclude those parts of the AST * interface heirarchy that should not have query hints applied, which * is basically the value expressions. * * @see <a href="http://sourceforge.net/apps/trac/bigdata/ticket/791" > * Clean up query hints </a> */ if (op instanceof IValueExpressionNode) { // Skip value expressions. return false; } if (op instanceof IValueExpression) { // Skip value expressions. return false; } // Visit anything else. return true; } /** * Applies the global query hints to each node in the query. * * @param queryRoot * @param queryHints */ private void applyGlobalQueryHints(final AST2BOpContext context, final QueryRoot queryRoot, final Properties queryHints) { if (queryHints == null || queryHints.isEmpty()) return; // validateQueryHints(context, queryHints); final Iterator<BOp> itr = BOpUtility .preOrderIteratorWithAnnotations(queryRoot); // Note: working around a ConcurrentModificationException. final List<ASTBase> list = new LinkedList<ASTBase>(); while (itr.hasNext()) { final BOp op = itr.next(); if (!isNodeAcceptingQueryHints(op)) continue; final ASTBase t = (ASTBase) op; list.add(t); } for (ASTBase t : list) { applyQueryHints(context, queryRoot, QueryHintScope.Query, t, queryHints); } } /** * Apply each query hint in turn to the AST node. * * @param t * The AST node. * @param queryHints * The query hints. */ private void applyQueryHints(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final ASTBase t, final Properties queryHints) { /* * Apply the query hints to the node. */ @SuppressWarnings("rawtypes") final Enumeration e = queryHints.propertyNames(); while (e.hasMoreElements()) { final String name = (String) e.nextElement(); final String value = queryHints.getProperty(name); _applyQueryHint(context, queryRoot, scope, t, name, value); } } /** * Apply the query hint to the AST node. * * @param t * The AST node to which the query hint will be bound. * @param name * The name of the query hint. * @param value * The value. */ @SuppressWarnings("unchecked") private void _applyQueryHint(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final ASTBase t, final String name, final String value) { @SuppressWarnings("rawtypes") final IQueryHint queryHint = QueryHintRegistry.get(name); if (queryHint == null) { // Unknown query hint. throw new QueryHintException(scope, t, name, value); } // Parse/validate and handle type conversion for the query hint value. final Object value2 = queryHint.validate(value); if (log.isTraceEnabled()) log.trace("Applying hint: hint=" + queryHint.getName() + ", value=" + value2 + ", node=" + t.getClass().getName()); // Apply the query hint. queryHint.handle(context, queryRoot, scope, t, value2); // if (scope == QueryHintScope.Query) { // /* // * All of these hints either are only permitted in the Query scope // * or effect the default settings for the evaluation of this query // * when they appear in the Query scope. For the latter category, the // * hints may also appear in other scopes. For example, you can // * override the access path sampling behavior either for the entire // * query, for all BGPs in some scope, or for just a single BGP. // */ // if (name.equals(QueryHints.ANALYTIC)) { // context.nativeHashJoins = Boolean.valueOf(value); // context.nativeDistinctSolutions = Boolean.valueOf(value); // context.nativeDistinctSPO = Boolean.valueOf(value); // } else if (name.equals(QueryHints.MERGE_JOIN)) { // context.mergeJoin = Boolean.valueOf(value); // } else if (name.equals(QueryHints.NATIVE_HASH_JOINS)) { // context.nativeHashJoins = Boolean.valueOf(value); // } else if (name.equals(QueryHints.NATIVE_DISTINCT_SOLUTIONS)) { // context.nativeDistinctSolutions = Boolean.valueOf(value); // } else if (name.equals(QueryHints.NATIVE_DISTINCT_SPO)) { // context.nativeDistinctSPO = Boolean.valueOf(value); // } else if (name.equals(QueryHints.REMOTE_APS)) { // context.remoteAPs = Boolean.valueOf(value); // } else if (name.equals(QueryHints.ACCESS_PATH_SAMPLE_LIMIT)) { // context.accessPathSampleLimit = Integer.valueOf(value); // } else if (name.equals(QueryHints.ACCESS_PATH_SCAN_AND_FILTER)) { // context.accessPathScanAndFilter = Boolean.valueOf(value); // } else { // t.setQueryHint(name, value); // } // } else { // t.setQueryHint(name, value); // } } // /** // * Validate the global query hints. // * // * @param queryHints // */ // private void validateQueryHints(final AST2BOpContext context, // final Properties queryHints) { // // final Enumeration<?> e = queryHints.propertyNames(); // // while (e.hasMoreElements()) { // // final String name = (String) e.nextElement(); // // final String value = queryHints.getProperty(name); // // validateQueryHint(context, name, value); // // } // // } /** * Recursively process a join group, applying any query hints found and * removing them from the join group. * * @param context * @param queryRoot * The {@link QueryRoot}. * @param group * The join group. */ @SuppressWarnings("unchecked") private void processGroup(final AST2BOpContext context, final QueryRoot queryRoot, final QueryBase queryBase, final GraphPatternGroup<IGroupMemberNode> group) { if (group == null) return; /* * Note: The loop needs to be carefully written as query hints will be * removed after they are processed. This can either be done on a hint * by hint basis or after we have processed all hints in the group. It * is easier to make the latter robust, so this uses a second pass over * each group in which a query hint was identified to remove the query * hints once they have been interpreted. */ /* * Identify and interpret query hints. */ // #of query hints found in this group. int nfound = 0; { final int arity = group.arity(); // The previous AST node which was not a query hint. ASTBase prior = null; for (int i = 0; i < arity; i++) { final IGroupMemberNode child = (IGroupMemberNode) group.get(i); if (child instanceof StatementPatternNode) { // Look for a query hint. final StatementPatternNode sp = (StatementPatternNode) child; if (!isQueryHint(sp)) { // Not a query hint. prior = sp; continue; } // Apply query hint. applyQueryHint(context, queryRoot, queryBase, group, prior, sp); nfound++; continue; } /* * Recursion (looking for query hints to be applied). */ if(child instanceof GraphPatternGroup<?>) { processGroup(context, queryRoot, queryBase, (GraphPatternGroup<IGroupMemberNode>) child); } else if (child instanceof SubqueryRoot) { processGroup(context, queryRoot, (SubqueryRoot)child, ((SubqueryRoot) child).getWhereClause()); } else if (child instanceof ServiceNode) { processGroup(context, queryRoot, queryBase, ((ServiceNode) child).getGraphPattern()); } else if (child instanceof FilterNode && ((FilterNode) child).getValueExpressionNode() instanceof SubqueryFunctionNodeBase) { /** * @see <a href="http://trac.blazegraph.com/ticket/990"> Query hint not recognized in FILTER</a> */ final GraphPatternGroup<IGroupMemberNode> filterGraphPattern = ((SubqueryFunctionNodeBase) ((FilterNode) child) .getValueExpressionNode()).getGraphPattern(); processGroup(context, queryRoot, queryBase, filterGraphPattern); } prior = (ASTBase) child; } } /* * Remove the query hints from this group. */ if (nfound > 0) { for (int i = 0; i < group.arity(); ) { final IGroupMemberNode child = (IGroupMemberNode) group.get(i); if (!(child instanceof StatementPatternNode)) { i++; continue; } final StatementPatternNode sp = (StatementPatternNode) child; if (isQueryHint(sp)) { // Remove and redo the loop. group.removeArg(sp); continue; } // Next child. i++; } } } /** * Return <code>true</code> iff this {@link StatementPatternNode} is a query * hint. This method checks the namespace of the predicate. All query hints * MUST start with the <code>hint:</code> namespace, which is given by * {@link QueryHints#NAMESPACE}. * <p> * Within that namespace we have public query hints whose localName is * declared in the {@link QueryHints} interface, e.g., * {@link QueryHints#CHUNK_SIZE} which appears as follows in a query: * * <pre> * hint:chunkSize * </pre> * * We also have non-public, fully qualified, query hints, e.g., * * <pre> * hint:com.bigdata.relation.accesspath.IBuffer.chunkCapacity * </pre> * * In both cases, an {@link IQueryHint} is registered with the * {@link QueryHintRegistry}. The "non-public" query hints are simply not * declared by the {@link QueryHints} interface and are intended more for * internal development and performance testing rather than as generally * useful query hints. * * @param sp * The {@link StatementPatternNode}. * * @return <code>true</code> if the SP is a query hint. * * @see <a href="http://sourceforge.net/apps/trac/bigdata/ticket/791" > * Clean up query hints </a> */ private boolean isQueryHint(final StatementPatternNode sp) { if(!(sp.p() instanceof ConstantNode)) return false; final BigdataValue p = ((ConstantNode) sp.p()).getValue(); if(!(p instanceof URI)) return false; final BigdataURI u = (BigdataURI) p; final String str = u.stringValue(); if (str.startsWith(QueryHints.NAMESPACE)) { // A possible query hint. return true; } return false; } /** * Extract and return the {@link QueryHintScope}. * * @param t * The subject position of the query hint * {@link StatementPatternNode}. * * @return The {@link QueryHintScope}. * * @throws RuntimeException * if something goes wrong. * @throws IllegalArgumentException * if something goes wrong. */ private QueryHintScope getScope(final TermNode t) { if(!(t instanceof ConstantNode)) throw new RuntimeException( "Subject position of query hint must be a constant."); final BigdataValue v = ((ConstantNode) t).getValue(); if (!(v instanceof BigdataURI)) throw new RuntimeException("Query hint scope is not a URI."); final BigdataURI u = (BigdataURI) v; return QueryHintScope.valueOf(u); } /** * Extract, validate, and return the name of the query hint property. * * @param t * The predicate position of the query hint * {@link StatementPatternNode}. * * @return The name of the query hint property. */ private String getName(final TermNode t) { if (!(t instanceof ConstantNode)) { throw new RuntimeException( "Predicate position of query hint must be a constant."); } final BigdataValue v = ((ConstantNode) t).getValue(); if (!(v instanceof BigdataURI)) throw new RuntimeException("Predicate position of query hint is not a URI."); final BigdataURI u = (BigdataURI) v; final String name = u.getLocalName(); return name; } /** * Return the value for the query hint. * * @param t * @return */ private String getValue(final TermNode t) { // if (!(t instanceof ConstantNode)) { // throw new RuntimeException( // "Object position of query hint must be a constant."); // } /* * Let the variable through as a string. */ if (t instanceof VarNode) { return '?'+((VarNode) t).getValueExpression().getName(); } final BigdataValue v = ((ConstantNode) t).getValue(); if (!(v instanceof Literal)) throw new RuntimeException( "Object position of query hint is not a Literal."); final Literal lit = (Literal) v; return lit.stringValue(); } /** * @param context * @param queryRoot * @param group * @param prior * @param s The subject position of the query hint. * @param o The object position of the query hint. */ private void applyQueryHint(// final AST2BOpContext context,// final QueryRoot queryRoot,// top-level query final QueryBase queryBase,// either top-level query or subquery. final GraphPatternGroup<IGroupMemberNode> group,// final ASTBase prior, // MAY be null IFF scope != Prior final StatementPatternNode hint // ) { if(context == null) throw new IllegalArgumentException(); if(queryRoot == null) throw new IllegalArgumentException(); if(group == null) throw new IllegalArgumentException(); if(hint == null) throw new IllegalArgumentException(); final QueryHintScope scope = getScope(hint.s()); final String name = getName(hint.p()); final String value = getValue(hint.o()); if (log.isInfoEnabled()) log.info("name=" + name + ", scope=" + scope + ", value=" + value); // validateQueryHint(context, name, value); switch (scope) { case Query: { applyToQuery(context, queryRoot, scope, name, value); break; } case SubQuery: { applyToSubQuery(context, queryRoot, scope, queryBase, group, name, value); break; } case Group: { applyToGroup(context, queryRoot, scope, group, name, value); break; } case GroupAndSubGroups: { applyToGroupAndSubGroups(context, queryRoot, scope, group, name, value); break; } case Prior: { if (scope == QueryHintScope.Prior && prior == null) { throw new RuntimeException( "Query hint with Prior scope must follow the AST node to which it will bind."); } // Apply to just the last SP. _applyQueryHint(context, queryRoot, scope, prior, name, value); break; } default: throw new UnsupportedOperationException("Unknown scope: " + scope); } } /** * @param group * @param name * @param value */ private void applyToSubQuery(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final QueryBase queryBase, GraphPatternGroup<IGroupMemberNode> group, final String name, final String value) { /* * Find the top-level parent group for the given group. */ GraphPatternGroup<IGroupMemberNode> parent = group; while (parent != null) { group = parent; parent = parent.getParentGraphPatternGroup(); } // Apply to all child groups of that top-level group. applyToGroupAndSubGroups(context, queryRoot, scope, group, name, value); // if (isNodeAcceptingQueryHints(queryBase)) { _applyQueryHint(context, queryRoot, scope, (ASTBase) queryBase, name, value); // } } /** * Applies the query hint to the entire query. * * @param queryRoot * @param name * @param value */ private void applyToQuery(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final String name, final String value) { if (false && context.queryHints != null) { /** * Also stuff the query hint on the global context for things which * look there. * * Note: HINTS: This was putting the literal given name and value of * the query hint. This is basically backwards. The query hints in * the global scope provide a default. Explicitly given query hints * in the query are delegated to IQueryHint implementations and then * applied to the appropriate AST nodes. * * @see <a * href="http://sourceforge.net/apps/trac/bigdata/ticket/791" > * Clean up query hints </a> */ context.queryHints.setProperty(name, value); } final Iterator<BOp> itr = BOpUtility .preOrderIteratorWithAnnotations(queryRoot); // Note: working around a ConcurrentModificationException. final List<ASTBase> list = new LinkedList<ASTBase>(); while (itr.hasNext()) { final BOp op = itr.next(); if (!isNodeAcceptingQueryHints(op)) continue; /* * Set a properties object on each AST node. The properties object * for each AST node will use the global query hints for its * defaults so it can be overridden selectively. */ final ASTBase t = (ASTBase) op; list.add(t); } for(ASTBase t : list) { _applyQueryHint(context, queryRoot, scope, t, name, value); } } /** * Apply the query hint to the group and, recursively, to any sub-groups. * * @param group * @param name * @param value */ @SuppressWarnings("unchecked") private void applyToGroupAndSubGroups(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final GraphPatternGroup<IGroupMemberNode> group, final String name, final String value) { for (IGroupMemberNode child : group) { _applyQueryHint(context, queryRoot, scope, (ASTBase) child, name, value); if (child instanceof GraphPatternGroup<?>) { applyToGroupAndSubGroups(context, queryRoot, scope, (GraphPatternGroup<IGroupMemberNode>) child, name, value); } } // if(isNodeAcceptingQueryHints(group)) { _applyQueryHint(context, queryRoot, scope, (ASTBase) group, name, value); // } } /** * Apply the query hint to the group. * * @param group * @param name * @param value */ private void applyToGroup(final AST2BOpContext context, final QueryRoot queryRoot, final QueryHintScope scope, final GraphPatternGroup<IGroupMemberNode> group, final String name, final String value) { for (IGroupMemberNode child : group) { _applyQueryHint(context, queryRoot, scope, (ASTBase) child, name, value); } // if (isNodeAcceptingQueryHints(group)) { _applyQueryHint(context, queryRoot, scope, (ASTBase) group, name, value); // } } }
rac021/blazegraph_1_5_3_cluster_2_nodes
bigdata-rdf/src/java/com/bigdata/rdf/sparql/ast/optimizers/ASTQueryHintOptimizer.java
Java
gpl-2.0
28,914
<?php /** * The template for displaying posts in the Audio post format * * @package WordPress * @subpackage Shopera * @since Shopera 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <span class="post-format post-format-audio"> <a class="entry-format" href="<?php echo esc_url( get_post_format_link( 'audio' ) ); ?>"><span class="glyphicon glyphicon-music"></span></a> </span> <?php if ( is_single() ) : the_title( '<h1 class="entry-title">', '</h1>' ); else : the_title( '<h1 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h1>' ); endif; ?> <div class="entry-meta"> <?php if ( in_array( 'category', get_object_taxonomies( get_post_type() ) ) && shopera_categorized_blog() ) : ?> <span class="cat-links"><span class="glyphicon glyphicon-eye-open"></span><?php echo get_the_category_list( _x( ', ', 'Used between list items, there is a space after the comma.', 'shopera' ) ); ?></span> <?php endif; if ( 'post' == get_post_type() ) shopera_posted_on(); if ( ! post_password_required() && ( comments_open() || get_comments_number() ) ) : ?> <span class="comments-link"><span class="glyphicon glyphicon-comment"></span><?php comments_popup_link( __( 'Leave a comment', 'shopera' ), __( '1 Comment', 'shopera' ), __( '% Comments', 'shopera' ) ); ?></span> <?php endif; ?> <?php the_tags( '<span class="tag-links"><span class="glyphicon glyphicon-tag"></span>', '', '</span>' ); ?> </div><!-- .entry-meta --> </header><!-- .entry-header --> <?php shopera_post_thumbnail(); ?> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'shopera' ) ); wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'shopera' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>', ) ); edit_post_link( __( 'Edit', 'shopera' ), '<span class="edit-link">', '</span>' ); ?> </div><!-- .entry-content --> </article><!-- #post-## -->
sumeetbajra/jewelleryshop
wp-content/themes/shopera/content-audio.php
PHP
gpl-2.0
2,237
// =================================================================================== // Microsoft Developer Guidance // Application Guidance for Windows Phone 7 // =================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. // =================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. // =================================================================================== using System; using System.Collections.ObjectModel; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Windows.Media.Imaging; namespace FuelTracker.Model { /// <summary> /// Represents the data-access layer of the Fuel Recorder application. /// </summary> public static class CarDataStore { private const string CAR_PHOTO_DIR_NAME = "FuelTracker"; private const string CAR_PHOTO_FILE_NAME = "CarPhoto.jpg"; private const string CAR_PHOTO_TEMP_FILE_NAME = "TempCarPhoto.jpg"; private const string CAR_KEY = "FuelTracker.Car"; private static readonly IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; private static Car _car; public static event EventHandler CarUpdated; /// <summary> /// Gets or sets the car data, loading the data from isolated storage /// (if there is any saved data) on the first access. /// </summary> public static Car Car { get { if (_car == null) { if (appSettings.Contains(CAR_KEY)) { _car = (Car)appSettings[CAR_KEY]; _car.Picture = GetCarPhoto(CAR_PHOTO_FILE_NAME); } else { _car = new Car { FillupHistory = new ObservableCollection<Fillup>() }; } } return _car; } set { _car = value; NotifyCarUpdated(); } } /// <summary> /// Saves the car data to isolated storage. /// </summary> /// <param name="errorCallback">The action to execute if the /// storage attempt fails.</param> public static void SaveCar(Action errorCallback) { try { appSettings[CAR_KEY] = Car; appSettings.Save(); DeleteTempCarPhoto(); SaveCarPhoto(CAR_PHOTO_FILE_NAME, Car.Picture, errorCallback); NotifyCarUpdated(); } catch (IsolatedStorageException) { errorCallback(); } } /// <summary> /// Deletes the car data from isolated storage and resets the Car property. /// </summary> public static void DeleteCar() { appSettings.Remove(CAR_KEY); appSettings.Save(); Car = null; DeleteCarPhoto(); DeleteTempCarPhoto(); NotifyCarUpdated(); } /// <summary> /// Gets the temporary car photo from isolated storage. /// </summary> /// <returns>The temporary car photo.</returns> public static BitmapImage GetTempCarPhoto() { return GetCarPhoto(CAR_PHOTO_TEMP_FILE_NAME); } /// <summary> /// Saves the temporary car photo to isolated storage. /// </summary> /// <param name="carPicture">The image to save.</param> /// <param name="errorCallback">The action to execute if the storage /// attempt fails.</param> public static void SaveTempCarPhoto(BitmapImage carPicture, Action errorCallback) { SaveCarPhoto(CAR_PHOTO_TEMP_FILE_NAME, carPicture, errorCallback); } /// <summary> /// Deletes the car photo from isolated storage. /// </summary> private static void DeleteCarPhoto() { DeletePhoto(CAR_PHOTO_FILE_NAME); } /// <summary> /// Deletes the temporary car photo from isolated storage. /// </summary> public static void DeleteTempCarPhoto() { DeletePhoto(CAR_PHOTO_TEMP_FILE_NAME); } /// <summary> /// Deletes the photo with the specified file name. /// </summary> /// <param name="fileName">The name of the photo file to delete.</param> private static void DeletePhoto(String fileName) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { var path = Path.Combine(CAR_PHOTO_DIR_NAME, fileName); if (store.FileExists(path)) store.DeleteFile(path); } } /// <summary> /// Gets the specified car photo from isolated storage. /// </summary> /// <param name="fileName">The filename of the photo to get.</param> /// <returns>The requested photo.</returns> private static BitmapImage GetCarPhoto(string fileName) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { string path = Path.Combine(CAR_PHOTO_DIR_NAME, fileName); if (!store.FileExists(path)) return null; using (var stream = store.OpenFile(path, FileMode.Open)) { var image = new BitmapImage(); image.SetSource(stream); return image; } } } /// <summary> /// Saves the specified car photo to isolated storage using the /// specified filename. /// </summary> /// <param name="fileName">The filename to use.</param> /// <param name="carPicture">The image to save.</param> /// <param name="errorCallback">The action to execute if the storage /// attempt fails.</param> private static void SaveCarPhoto(string fileName, BitmapImage carPicture, Action errorCallback) { if (carPicture == null) return; try { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { var bitmap = new WriteableBitmap(carPicture); var path = Path.Combine(CAR_PHOTO_DIR_NAME, fileName); if (!store.DirectoryExists(CAR_PHOTO_DIR_NAME)) { store.CreateDirectory(CAR_PHOTO_DIR_NAME); } using (var stream = store.OpenFile(path, FileMode.Create)) { bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100); } } } catch (IsolatedStorageException) { errorCallback(); } } /// <summary> /// Validates the specified Fillup and then, if it is valid, adds it to /// Car.FillupHistory collection. /// </summary> /// <param name="fillup">The fill-up to save.</param> /// <param name="errorCallback">The action to execute if the storage /// attempt fails.</param> /// <returns>The validation results.</returns> public static SaveResult SaveFillup(Fillup fillup, Action errorCallback) { var lastReading = Car.FillupHistory.Count > 0 ? Car.FillupHistory.First().OdometerReading : Car.InitialOdometerReading; fillup.DistanceDriven = fillup.OdometerReading - lastReading; var saveResult = new SaveResult(); var validationResults = fillup.Validate(); if (validationResults.Count > 0) { saveResult.SaveSuccessful = false; saveResult.ErrorMessages = validationResults; } else { Car.FillupHistory.Insert(0, fillup); saveResult.SaveSuccessful = true; SaveCar(delegate { saveResult.SaveSuccessful = false; errorCallback(); }); } return saveResult; } private static void NotifyCarUpdated() { var handler = CarUpdated; if (handler != null) handler(null, null); } } }
chahalarora/R.S.C-WindowsPhone
Fuel Recorder/FuelRecorder/Model/CarDataStore.cs
C#
gpl-2.0
9,593
package com.serotonin.mango.util; import com.serotonin.mango.Common; import com.serotonin.mango.rt.dataImage.DataPointRT; import com.serotonin.mango.rt.event.EventInstance; import com.serotonin.mango.rt.event.handlers.EmailHandlerRT; import com.serotonin.mango.rt.event.handlers.EmailToSmsHandlerRT; import com.serotonin.mango.rt.event.handlers.NotificationType; import com.serotonin.mango.rt.event.type.SystemEventType; import com.serotonin.mango.rt.maint.work.AfterWork; import com.serotonin.mango.rt.maint.work.EmailWorkItem; import com.serotonin.mango.rt.maint.work.EmailNotificationWorkItem; import com.serotonin.mango.view.event.NoneEventRenderer; import com.serotonin.mango.vo.DataPointVO; import com.serotonin.mango.web.email.MangoEmailContent; import com.serotonin.util.StringUtils; import com.serotonin.web.i18n.LocalizableMessage; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import java.text.MessageFormat; import java.util.HashSet; import java.util.ResourceBundle; import java.util.Set; public final class SendMsgUtils { private static final Log LOG = LogFactory.getLog(SendMsgUtils.class); private SendMsgUtils() {} public static boolean sendEmail(EventInstance evt, EmailHandlerRT.EmailNotificationType notificationType, Set<String> addresses, String alias, AfterWork afterWork) { try { SendEmailConfig sendEmailConfig = SendEmailConfig.newConfigFromSystemSettings(); validateEmail(evt, notificationType, addresses, alias); if (evt.getEventType().isSystemMessage()) { if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) { // Don't send email notifications about email send failures. LOG.info("Not sending email for event raised due to email failure"); return false; } } MangoEmailContent content = EmailContentUtils.createContent(evt, notificationType, alias); String[] toAddrs = addresses.toArray(new String[0]); InternetAddress[] internetAddresses = SendMsgUtils.convertToInternetAddresses(toAddrs); validateAddresses(evt, notificationType, internetAddresses, alias); // Send the email. EmailNotificationWorkItem.queueMsg(internetAddresses, content, afterWork, sendEmailConfig); return true; } catch (Exception e) { LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}", getInfoEmail(evt,notificationType,alias), ExceptionUtils.getStackTrace(e))); return false; } } public static boolean sendSms(EventInstance evt, EmailToSmsHandlerRT.SmsNotificationType notificationType, Set<String> addresses, String alias, AfterWork afterWork) { try { SendEmailConfig sendEmailConfig = SendEmailConfig.newConfigFromSystemSettings(); validateEmail(evt, notificationType, addresses, alias); if (evt.getEventType().isSystemMessage()) { if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) { // Don't send email notifications about email send failures. LOG.info("Not sending email for event raised due to email failure"); return false; } } MangoEmailContent content = EmailContentUtils.createSmsContent(evt, notificationType, alias); String[] toAddrs = addresses.toArray(new String[0]); InternetAddress[] internetAddresses = SendMsgUtils.convertToInternetAddresses(toAddrs); validateAddresses(evt, notificationType, internetAddresses, alias); // Send the email. EmailNotificationWorkItem.queueMsg(internetAddresses, content, afterWork, sendEmailConfig); return true; } catch (Exception e) { LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}", getInfoEmail(evt,notificationType,alias), ExceptionUtils.getStackTrace(e))); return false; } } public static boolean sendEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias) { try { SendEmailConfig.validateSystemSettings(); validateEmail(evt, notificationType, addresses, alias); if (evt.getEventType().isSystemMessage()) { if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) { // Don't send email notifications about email send failures. LOG.info("Not sending email for event raised due to email failure"); return false; } } String[] toAddrs = addresses.toArray(new String[0]); MangoEmailContent content = EmailContentUtils.createContent(evt, notificationType, alias); validateAddresses(evt, notificationType, convertToInternetAddresses(toAddrs), alias); // Send the email. EmailWorkItem.queueEmail(toAddrs, content); return true; } catch (Exception e) { LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}", getInfoEmail(evt,notificationType,alias), ExceptionUtils.getStackTrace(e))); return false; } } public static boolean sendSms(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias) { try { SendEmailConfig.validateSystemSettings(); validateEmail(evt, notificationType, addresses, alias); if (evt.getEventType().isSystemMessage()) { if (((SystemEventType) evt.getEventType()).getSystemEventTypeId() == SystemEventType.TYPE_EMAIL_SEND_FAILURE) { // Don't send email notifications about email send failures. LOG.info("Not sending email for event raised due to email failure"); return false; } } MangoEmailContent content = EmailContentUtils.createSmsContent(evt, notificationType, alias); String[] toAddrs = addresses.toArray(new String[0]); validateAddresses(evt, notificationType, convertToInternetAddresses(toAddrs), alias); EmailWorkItem.queueEmail(toAddrs, content); return true; } catch (Exception e) { LOG.error(MessageFormat.format("Info about email: {0}, StackTrace: {1}", getInfoEmail(evt,notificationType,alias), ExceptionUtils.getStackTrace(e))); return false; } } private static String getInfoEmail(EventInstance evt, NotificationType notificationType, String alias) { String messageInfoAlias = MessageFormat.format("Alias: {0} \n", alias); String messageInfoEmail = MessageFormat.format("Event: {0} \n", evt.getId()); String messageInfoNotification = MessageFormat.format("Notification: {0} \n", notificationType.getKey()); String subject = ""; String messageExceptionWhenGetSubjectEmail = ""; try { LocalizableMessage subjectMsg; LocalizableMessage notifTypeMsg = new LocalizableMessage(notificationType.getKey()); if (StringUtils.isEmpty(alias)) { if (evt.getId() == Common.NEW_ID) subjectMsg = new LocalizableMessage("ftl.subject.default.log", notifTypeMsg); else subjectMsg = new LocalizableMessage("ftl.subject.default.id", notifTypeMsg, evt.getId()); } else { if (evt.getId() == Common.NEW_ID) subjectMsg = new LocalizableMessage("ftl.subject.alias", alias, notifTypeMsg); else subjectMsg = new LocalizableMessage("ftl.subject.alias.id", alias, notifTypeMsg, evt.getId()); } ResourceBundle bundle = Common.getBundle(); subject = subjectMsg.getLocalizedMessage(bundle); } catch (Exception e) { messageExceptionWhenGetSubjectEmail = MessageFormat.format("StackTrace for subjectMsg {0}",ExceptionUtils.getStackTrace(e)); } String messages = new StringBuilder() .append(messageInfoEmail) .append(messageInfoNotification) .append(messageInfoAlias) .append(subject) .append(messageExceptionWhenGetSubjectEmail).toString(); return messages; } private static void validateEmail(EventInstance evt, NotificationType notificationType, Set<String> addresses, String alias) throws Exception { String messageErrorEventInstance = "Event Instance null \n"; String messageErrorNotyficationType = "Notification type is null \n"; String messageErrorEmails = " Don't have e-mail \n"; String messageErrorAlias = " Don't have alias\n"; String messages = ""; if (evt == null || evt.getEventType() == null) messages += messageErrorEventInstance; if (notificationType == null) messages += messageErrorNotyficationType; if (addresses == null || addresses.size() == 0) messages += messageErrorEmails; if (alias == null) messages += messageErrorAlias; if (messages.length() > 0) { throw new Exception(getInfoEmail(evt, notificationType, alias) + messages ); } } private static void validateAddresses(EventInstance evt, NotificationType notificationType, InternetAddress[] internetAddresses, String alias) throws Exception { String messageErrorEmails = " Don't have e-mail \n"; String messages = ""; if (internetAddresses == null || internetAddresses.length == 0) messages += messageErrorEmails; if (!messages.isEmpty()) { throw new Exception(getInfoEmail(evt, notificationType, alias) + messages ); } } public static InternetAddress[] convertToInternetAddresses(String[] toAddresses) { Set<InternetAddress> addresses = new HashSet<>(); for (int i = 0; i < toAddresses.length; i++) { try { InternetAddress internetAddress = new InternetAddress(toAddresses[i]); addresses.add(internetAddress); } catch (AddressException e) { LOG.error(e.getMessage(), e); } } return addresses.toArray(new InternetAddress[]{}); } public static String getDataPointMessage(DataPointVO dataPoint, LocalizableMessage shortMsg) { if (shortMsg.getKey().equals("event.detector.shortMessage") && shortMsg.getArgs().length == 2) { return " " + shortMsg.getArgs()[1]; } else if (dataPoint.getDescription() != null && !dataPoint.getDescription().equals("")) return " " + dataPoint.getDescription(); else return " " + dataPoint.getName(); } }
SCADA-LTS/Scada-LTS
src/com/serotonin/mango/util/SendMsgUtils.java
Java
gpl-2.0
11,593
package doser.webclassify.dpo; import java.util.Set; import doser.entitydisambiguation.table.logic.Type; import doser.webclassify.algorithm.PageSimilarity; public class WebSite implements Cloneable, Comparable<WebSite> { private String name; private String text; private int objectId; private Set<Type> types; private PageSimilarity similarity; public WebSite() { super(); this.name = ""; this.text = ""; } public String getName() { return name; } public PageSimilarity getSimilarity() { return similarity; } public void setSimilarity(PageSimilarity similarity) { this.similarity = similarity; } public void setName(String name) { this.name = name; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Set<Type> getTypes() { return types; } public void setTypes(Set<Type> types) { this.types = types; } public void setObjectId(int objectId) { this.objectId = objectId; } @Override public int compareTo(WebSite o) { // System.out.println(this.name + " "+o.getName()); if (this.name.equalsIgnoreCase(o.getName()) && this.getText().hashCode() == o.getText().hashCode()) { return 0; } else { return -1; } } }
quhfus/DoSeR
doser-core/src/main/java/doser/webclassify/dpo/WebSite.java
Java
gpl-2.0
1,245
<?php /** * * * @category Mygento * @package Mygento_Simplepay * @copyright Copyright © 2015 NKS LLC. (http://www.mygento.ru) * @license GPLv2 */ class Mygento_Simplepay_Model_Source_Payment { public function toOptionArray() { return array( array('value' => 'CARDPSB', 'label' => Mage::helper('simplepay')->__('Банковские карты ')), array('value' => 'EUROSETPT', 'label' => Mage::helper('simplepay')->__('Евросеть')), array('value' => 'ALFACLICK', 'label' => Mage::helper('simplepay')->__('Альфа-Клик')), array('value' => 'WEBMONEY', 'label' => Mage::helper('simplepay')->__('Webmoney')), array('value' => 'CONTACT', 'label' => Mage::helper('simplepay')->__('CONTACT')), array('value' => 'ELEKSNETPT', 'label' => Mage::helper('simplepay')->__('Элекснет')), array('value' => 'FAKTURARUPT', 'label' => Mage::helper('simplepay')->__('Faktura.ru')), array('value' => 'PROMSVYAZBANKPT', 'label' => Mage::helper('simplepay')->__('Промсвязьбанк')), array('value' => 'RUSSTANDARTPT', 'label' => Mage::helper('simplepay')->__('Русский стандарт')), array('value' => 'NSYMBOLPT', 'label' => Mage::helper('simplepay')->__('HandyBank')), array('value' => 'PETROKOMMERCPT', 'label' => Mage::helper('simplepay')->__('Петрокоммерц')), array('value' => 'QIWIMAIN', 'label' => Mage::helper('simplepay')->__('QIWI Wallet')), array('value' => 'SP', 'label' => Mage::helper('simplepay')->__('Choose on merchant interface')), ); } }
mygento/simplepay
app/code/community/Mygento/Simplepay/Model/Source/Payment.php
PHP
gpl-2.0
1,685
# -*- coding: utf-8 -*- # Asymmetric Base Framework - A collection of utilities for django frameworks # Copyright (C) 2013 Asymmetric Ventures Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import absolute_import, division, print_function, unicode_literals from django.template.response import TemplateResponse from django.template.context import RequestContext from asymmetricbase.jinja import jinja_env from asymmetricbase.logging import logger #@UnusedImport class JinjaTemplateResponse(TemplateResponse): def resolve_template(self, template): if isinstance(template, (list, tuple)): return jinja_env.select_template(template) elif isinstance(template, basestring): return jinja_env.get_template(template) else: return template def resolve_context(self, context): context = super(JinjaTemplateResponse, self).resolve_context(context) if isinstance(context, RequestContext): context = jinja_env.context_to_dict(context) return context
AsymmetricVentures/asymmetricbase
asymmetricbase/jinja/response.py
Python
gpl-2.0
1,647
/* * dgMaster: A versatile, open source data generator. *(c) 2007 M. Michalakopoulos, mmichalak@gmail.com */ package generator.misc; import java.util.Vector; /** * * Represents the information used to create a new text output file. * It also holds a vector of DataFileItem which define what to output in the * text file. */ public class DataFileDefinition { private String name; private String description; private Vector outDataItems; //a place holder for DataFileItem private String outFilename; private String delimiter; private long numOfRecs; /** Creates a new instance of FileDefinition */ public DataFileDefinition() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Vector getOutDataItems() { return outDataItems; } public void setOutDataItems(Vector vOutData) { this.outDataItems = vOutData; } public String getOutFilename() { return outFilename; } public void setOutFilename(String outFilename) { this.outFilename = outFilename; } public String getDescription() { return this.description; } public String getDelimiter() { return delimiter; } public void setDelimiter(String delimiter) { this.delimiter = delimiter; } public long getNumOfRecs() { return numOfRecs; } public void setNumOfRecs(long numOfRecs) { this.numOfRecs = numOfRecs; } public void setDescription(String description) { this.description = description; } public String toString() { return name; } }
tspauld98/white-mercury-dg
src/main/java/generator/misc/DataFileDefinition.java
Java
gpl-2.0
1,890
#include "core\Singularity.Core.h" using namespace Singularity::Components; namespace Singularity { IMPLEMENT_OBJECT_TYPE(Singularity, BehaviorTask, Singularity::Threading::Task); #pragma region Static Variables BehaviorTask* BehaviorTask::g_pInstance = NULL; #pragma endregion #pragma region Constructors and Finalizers BehaviorTask::BehaviorTask() : Task("Game Task") { this->Set_Frequency(1 / 60.0f); } #pragma endregion #pragma region Methods void BehaviorTask::RegisterComponent(Component* component) { if(component == NULL) throw SingularityException("\"component\" cannot be null or empty."); if(component->GetType().Equals(Behavior::Type)) this->m_pBehaviors.insert((Behavior*)component); } void BehaviorTask::UnregisterComponent(Component* component) { if(component == NULL) throw SingularityException("\"component\" cannot be null or empty."); if(component->GetType().Equals(Behavior::Type)) this->m_pBehaviors.erase((Behavior*)component); } #pragma endregion #pragma region Overriden Methods void BehaviorTask::OnExecute() { DynamicSet<Behavior*>::iterator it; #if _DEBUG //printf("Behavior Call Frequency = %3.1f\n", this->Get_ActualFrequency()); #endif Behavior* behavior; for(it = this->m_pBehaviors.begin(); it != this->m_pBehaviors.end(); ++it) { behavior = *it; for(int i = 0; i < behavior->Update.Count(); ++i) if(behavior->Update[i]->GetType().Equals(BehaviorDelegate::Type)) ((BehaviorDelegate*)behavior->Update[i])->Invoke(behavior, this->Get_ElapsedTime()); } this->Recycle(); } #pragma endregion #pragma region Static Methods BehaviorTask* BehaviorTask::Instantiate() { if(!BehaviorTask::g_pInstance) BehaviorTask::g_pInstance = new BehaviorTask(); return BehaviorTask::g_pInstance; } #pragma endregion }
jobelobes/Singularity-GameEngine
src/core/components/BehaviorTask.cpp
C++
gpl-2.0
1,832
package com.mutar.libav.bridge.avformat; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Field; import org.bridj.ann.Library; /** * <i>native declaration : ffmpeg_build/include/libavformat/avio.h:49</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> or <a href="http://bridj.googlecode.com/">BridJ</a> . */ @Library("avformat") public class AVIODirEntry extends StructObject { static { BridJ.register(); } /** * < Filename<br> * C type : char* */ @Field(0) public Pointer<Byte > name() { return this.io.getPointerField(this, 0); } /** * < Filename<br> * C type : char* */ @Field(0) public AVIODirEntry name(Pointer<Byte > name) { this.io.setPointerField(this, 0, name); return this; } /** < Type of the entry */ @Field(1) public int type() { return this.io.getIntField(this, 1); } /** < Type of the entry */ @Field(1) public AVIODirEntry type(int type) { this.io.setIntField(this, 1, type); return this; } /** * < Set to 1 when name is encoded with UTF-8, 0 otherwise.<br> * Name can be encoded with UTF-8 even though 0 is set. */ @Field(2) public int utf8() { return this.io.getIntField(this, 2); } /** * < Set to 1 when name is encoded with UTF-8, 0 otherwise.<br> * Name can be encoded with UTF-8 even though 0 is set. */ @Field(2) public AVIODirEntry utf8(int utf8) { this.io.setIntField(this, 2, utf8); return this; } /** < File size in bytes, -1 if unknown. */ @Field(3) public long size() { return this.io.getLongField(this, 3); } /** < File size in bytes, -1 if unknown. */ @Field(3) public AVIODirEntry size(long size) { this.io.setLongField(this, 3, size); return this; } /** * < Time of last modification in microseconds since unix<br> * epoch, -1 if unknown. */ @Field(4) public long modification_timestamp() { return this.io.getLongField(this, 4); } /** * < Time of last modification in microseconds since unix<br> * epoch, -1 if unknown. */ @Field(4) public AVIODirEntry modification_timestamp(long modification_timestamp) { this.io.setLongField(this, 4, modification_timestamp); return this; } /** * < Time of last access in microseconds since unix epoch,<br> * -1 if unknown. */ @Field(5) public long access_timestamp() { return this.io.getLongField(this, 5); } /** * < Time of last access in microseconds since unix epoch,<br> * -1 if unknown. */ @Field(5) public AVIODirEntry access_timestamp(long access_timestamp) { this.io.setLongField(this, 5, access_timestamp); return this; } /** * < Time of last status change in microseconds since unix<br> * epoch, -1 if unknown. */ @Field(6) public long status_change_timestamp() { return this.io.getLongField(this, 6); } /** * < Time of last status change in microseconds since unix<br> * epoch, -1 if unknown. */ @Field(6) public AVIODirEntry status_change_timestamp(long status_change_timestamp) { this.io.setLongField(this, 6, status_change_timestamp); return this; } /** < User ID of owner, -1 if unknown. */ @Field(7) public long user_id() { return this.io.getLongField(this, 7); } /** < User ID of owner, -1 if unknown. */ @Field(7) public AVIODirEntry user_id(long user_id) { this.io.setLongField(this, 7, user_id); return this; } /** < Group ID of owner, -1 if unknown. */ @Field(8) public long group_id() { return this.io.getLongField(this, 8); } /** < Group ID of owner, -1 if unknown. */ @Field(8) public AVIODirEntry group_id(long group_id) { this.io.setLongField(this, 8, group_id); return this; } /** < Unix file mode, -1 if unknown. */ @Field(9) public long filemode() { return this.io.getLongField(this, 9); } /** < Unix file mode, -1 if unknown. */ @Field(9) public AVIODirEntry filemode(long filemode) { this.io.setLongField(this, 9, filemode); return this; } public AVIODirEntry() { super(); } public AVIODirEntry(Pointer pointer) { super(pointer); } }
mutars/java_libav
wrapper/src/main/java/com/mutar/libav/bridge/avformat/AVIODirEntry.java
Java
gpl-2.0
4,355
<?php /** * DokuWiki Plugin yourip (Syntax Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @author Artem Sidorenko <artem@2realities.com> * 2019-09 target urls changed by Hella Breitkopf, https://www.unixwitch.de */ // must be run within Dokuwiki if (!defined('DOKU_INC')) die(); if (!defined('DOKU_LF')) define('DOKU_LF', "\n"); if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t"); if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/'); require_once DOKU_PLUGIN.'syntax.php'; class syntax_plugin_yourip extends DokuWiki_Syntax_Plugin { public function getType() { return 'substition'; } public function getPType() { return 'block'; } public function getSort() { return 99; } public function connectTo($mode) { $this->Lexer->addSpecialPattern('~~YOURIP_.*?~~',$mode,'plugin_yourip'); } public function handle($match, $state, $pos, Doku_Handler $handler){ $data = array("yourip_type"=>""); $match = substr($match, 9, -2); if ($match == 'BOX') $data['yourip_type'] = 'box'; elseif ($match == 'LINE') $data['yourip_type'] = 'line'; elseif ($match == 'IPONLY') $data['yourip_type'] = 'iponlyline'; return $data; } public function render($mode, Doku_Renderer $renderer, $data) { if($mode != 'xhtml') return false; $ip = getenv ("REMOTE_ADDR"); $type=false; if (substr_count($ip,":") > 1 && substr_count($ip,".") == 0) $type='ipv6'; else $type='ipv4'; #show the things, here info in the box $text=false; if($data['yourip_type']=="box"){ $text="\n<div id='yourip' class='$type'>"; if($type=='ipv6') $text .= "You've got IPv6! <br/>IPv6 connection from $ip"; else $text .= "You use old fashioned IPv4<br/>IPv4 connection from $ip"; $text .="</div>\n"; $renderer->doc .= $text; return true; #info as line }elseif($data['yourip_type']=="line"){ $text="<p id='yourip' class='$type'>"; if($type=='ipv6') $text .= "IPv6 connection from $ip"; else $text .= "IPv4 connection from $ip"; $text .="</p>\n"; $renderer->doc .= $text; return true; #info without text }elseif($data['yourip_type']=="iponlyline"){ $text = "<p id='yourip' class='$type'>"; $text .= "$ip" ; $text .= "</p>\n" ; $renderer->doc .= $text; return true; } else return false; } // end function render } // end class // vim:ts=4:sw=4:et:
artem-sidorenko/dokuwiki-yourip
syntax.php
PHP
gpl-2.0
2,841
<?php namespace Drupal\openapi; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ServiceProviderBase; use Symfony\Component\DependencyInjection\Reference; /** * Service provider that creators OpenAPI generator services. */ class OpenapiServiceProvider extends ServiceProviderBase { /** * {@inheritdoc} */ public function register(ContainerBuilder $container) { $modules = $container->getParameter(('container.modules')); // @todo Add 'openapi_generator' tag? Can you just make up tags? if (isset($modules['rest'])) { $container->register('openapi.generator.rest', 'Drupal\openapi\OpenApiGenerator\OpenApiRestGenerator') ->addArgument(new Reference('entity_type.manager')) ->addArgument(new Reference('router.route_provider')) ->addArgument(new Reference('entity_field.manager')) ->addArgument(new Reference('schemata.schema_factory')) ->addArgument(new Reference('serializer')) ->addArgument(new Reference('plugin.manager.rest')); } if (isset($modules['jsonapi'])) { $container->register('openapi.generator.jsonapi', 'Drupal\openapi\OpenApiGenerator\OpenApiJsonapiGenerator') ->addArgument(new Reference('entity_type.manager')) ->addArgument(new Reference('router.route_provider')) ->addArgument(new Reference('entity_field.manager')) ->addArgument(new Reference('schemata.schema_factory')) ->addArgument(new Reference('serializer')); } } }
chriscalip/cdemo
web/modules/contrib/openapi/src/OpenapiServiceProvider.php
PHP
gpl-2.0
1,525
<?php /* Template name: Full Width */ get_header(); ?> <div class="wrapper _content"> <div class="container"> <div class="row-fluid"> <div class="span12 content"> <div class="main_full_width"> <?php while (have_posts()) : the_post(); ?> <?php the_title('<h2 class="ribbon"><span>','</span></h2>'); ?> <div class="box_post_full_width"> <?php the_content();?> </div> <?php endwhile; ?> </div><!-- end main --> </div> </div> </div> </div> <?php get_footer(); ?>
afftt/infos-ping
wp-content/themes/bzine/template-full-width.php
PHP
gpl-2.0
526
//-----------------------------------------------------------------------------+ // | // DehnenMcLaughlin.cc | // | // Copyright (C) 2004-2006 Walter Dehnen | // | // This program is free software; you can redistribute it and/or modify | // it under the terms of the GNU General Public License as published by | // the Free Software Foundation; either version 2 of the License, or (at | // your option) any later version. | // | // This program is distributed in the hope that it will be useful, but | // WITHOUT ANY WARRANTY; without even the implied warranty of | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // General Public License for more details. | // | // You should have received a copy of the GNU General Public License | // along with this program; if not, write to the Free Software | // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. | // | //-----------------------------------------------------------------------------+ // | // Versions | // 0.1 09/08/2006 WD use $NEMOINC/defacc.h | //-----------------------------------------------------------------------------+ #undef POT_DEF #include <iostream> #include <utils/WDMath.h> #include <defacc.h> // $NEMOINC/defacc.h //////////////////////////////////////////////////////////////////////////////// namespace { using namespace WDutils; ////////////////////////////////////////////////////////////////////////////// class DehnenMcLaughlin { const double GM,a,b0,e; // defininng parameters const double ia,nM,eta,kk,Pf; // derived parameters const BetaFunc BPs; // Beta_u( 1/eta, (1-beta0)/eta + 1/2 ) public: static const char* name() { return "DehnenMcLaughlin"; } DehnenMcLaughlin(const double*pars, int npar, const char *file) : GM ( npar>1? -std::abs(pars[1]) : -1. ), a ( npar>2? pars[2] : 1. ), b0 ( npar>3? pars[3] : 0. ), e ( npar>4? pars[4] : 3. ), ia ( 1./a ), nM ( (e+2)/(e-2) ), eta ( 2*(e-2)*(2-b0)/(6+e) ), kk ( eta*nM-3 ), Pf ( GM*ia/eta ), BPs ( 1./eta, (1-b0)/eta+0.5 ) { if(npar>5 || debug(2)) std::cerr<< "falcON Debug Info: acceleration \"DehnenMcLaughlin\"" "recognizing 5 parameters:\n" " omega pattern speed (ignored) [0]\n" " G*M mass; [1]\n" " a scale radius; [1]\n" " b0 inner halo anisotropy [0]\n" " e assume rho/sigma_r^e is power law [3]\n" " the potential is given by the density\n\n" " 4+eta-2b0 M -g0 eta -2e/(2-e)\n" " rho = - --------- --- x (1+x )\n" " 8 Pi a\n\n" " with x=r/a and\n\n" " eta= 2*(e-2)*(2-b0)/(6+e) [4/9]\n" " g0 = 1-eta/2+b0 [7/9]\n\n"; if(file) warning("acceleration \"%s\": file \"%s\" ignored",name(),file); if(a<=0.) error("acceleration \"%s\": a=%f <= 0\n",name(),a); if(e<=2.) error("acceleration \"%s\": e=%f <= 2\n",name(),e); if(b0>1.) error("acceleration \"%s\": b0=%f > 1\n",name(),b0); if(npar>5) warning("acceleration \"%s\":" " skipped parameters beyond 5",name()); } /// /// routine used by class SphericalPot<DehnenMcLaughlin> of defacc.h /// /// Note that the potential for a Dehnen & McLaughlin (2005, hereafter D&M) /// model is given by (in units of GM/a) /// /// Psi = Psi_0 - Beta_y ( (1-beta0)/eta + 1/2, 1/eta ) / eta /// /// with /// /// Psi_0 = Beta( (1-beta0)/eta + 1/2, 1/eta ) / eta /// /// and /// /// y = x^eta / (1 + x^eta). /// /// Here, Beta_u(p,q) the incomplete beta function, see eq (40h) of D&M. /// At small radii (note that there is a typo in eq 40j of D&M) /// /// Psi = Psi_0 - 2/(2+eta-2*beta0) x^(eta/2+1-beta0) /// template<typename scalar> void potacc(scalar const&rq, scalar &P, scalar &T) const { if(rq == 0.) { P = Pf * BPs(1.); T = 0; } else { double r = std::sqrt(rq); double u = std::pow(ia*r,eta); double u1 = 1./(1+u); P = Pf * BPs(u1); T = GM * std::pow(u*u1,nM) / (rq*r); } } }; } //------------------------------------------------------------------------------ __DEF__ACC(SphericalPot<DehnenMcLaughlin>) //------------------------------------------------------------------------------
jobovy/nemo
usr/dehnen/falcON/src/public/acc/DehnenMcLaughlin.cc
C++
gpl-2.0
6,388
#!/usr/bin/env python3 """ * Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT * software: you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. BEESOFT is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You * should have received a copy of the GNU General Public License along with * BEESOFT. If not, see <http://www.gnu.org/licenses/>. """ __author__ = "Marcos Gomes" __license__ = "MIT" import json import FileFinder import pygame class PrinterInfoLoader(): interfaceJson = None lblJson = None lblValJson = None lblFont = None lblFontColor = None lblXPos = None lblYPos = None lblText = None lblValFont = None lblValFontColor = None lblValXPos = None lblValFont = None lblValFontColor = None displayWidth = 480 displayHeight = 320 """************************************************************************* Init Method Inits current screen components *************************************************************************""" def __init__(self, interfaceJson, dispWidth, dispHeight): self.displayWidth = dispWidth self.displayHeight = dispHeight self.interfaceJson = interfaceJson self.lblJson = json.loads(json.dumps(self.interfaceJson['Labels'])) self.lblValJson = json.loads(json.dumps(self.interfaceJson['ValuesSettings'])) """ Values Labels Configuration "X":"220", "FontType":"Bold", "FontSize":"12", "FontColor":"0,0,0" """ self.lblValXPos = int(float(self.lblValJson['X'])*self.displayWidth) lblValFontType = self.lblValJson['FontType'] lblValFontSize = int(float(self.lblValJson['FontSize'])*self.displayHeight) self.lblValFont = self.GetFont(lblValFontType,lblValFontSize) lblValFColor = self.lblValJson['FontColor'] splitColor = lblValFColor.split(",") self.lblValFontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2])) """ Load Labels Configuration """ self.lblText = [] self.lblXPos = [] self.lblYPos = [] self.lblFont = [] self.lblFontColor = [] for lbl in self.lblJson: lblFontType = lbl['FontType'] lblFontSize = int(float(lbl['FontSize'])*self.displayHeight) lblFColor = lbl['FontColor'] self.lblXPos.append(int(float(lbl['X'])*self.displayWidth)) self.lblYPos.append(int(float(lbl['Y'])*self.displayHeight)) self.lblText.append(lbl['Text']) font = self.GetFont(lblFontType,lblFontSize) self.lblFont.append(font) splitColor = lblFColor.split(",") fontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2])) self.lblFontColor.append(fontColor) return """ GetFont """ def GetFont(self,fontType,fontSize): r""" GetFont method Receives as arguments: fontType - Regular,Bold,Italic,Light fontSize - font size Returns: pygame font object """ ff = FileFinder.FileFinder() font = None if fontType == "Regular": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Regular.ttf"),fontSize) elif fontType == "Bold": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Bold.ttf"),fontSize) elif fontType == "Italic": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Italic.ttf"),fontSize) elif fontType == "Light": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Light.ttf"),fontSize) return font """ GetlblText(self) returns the list with the label text """ def GetlblText(self): return self.lblText """ GetlblFont """ def GetlblFont(self): return self.lblFont """ GetlblFontColor """ def GetlblFontColor(self): return self.lblFontColor """ GetlblXPos """ def GetlblXPos(self): return self.lblXPos """ GetlblYPos """ def GetlblYPos(self): return self.lblYPos """ GetlblValFont """ def GetlblValFont(self): return self.lblValFont """ GetlblValFontColor """ def GetlblValFontColor(self): return self.lblValFontColor """ GetlblValXPos """ def GetlblValXPos(self): return self.lblValXPos
beeverycreative/beeconnect
Loaders/PrinterInfoLoader.py
Python
gpl-2.0
5,218
angular.module('app.controllers.ForgotPasswordCtrl', ['ngRoute']) .controller('ForgotPasswordCtrl', ['$scope', '$http', '$modalInstance', 'forgotPasswordService', function($scope, $http, $modalInstance, forgotPasswordService) { $scope.forgot_data = { email: "" }; $scope.ok = function () { forgotPasswordService.save($scope.forgot_data); $modalInstance.close($scope.forgot_data.email); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }]);
DazzleWorks/Premi
public/app/controllers/home/ForgotPasswordCtrl.js
JavaScript
gpl-2.0
570
package daos; import objects.Employee; import java.util.List; public interface EmployeeDao { void createEmployee(Employee employee); void deleteEmployee(String surname, String name); Employee searchForEmployee(String surname, String name); List<Employee> findAll(); }
sunknife/GoJavaOnline
EE Module 7 Part1/src/main/java/daos/EmployeeDao.java
Java
gpl-2.0
291
/* * OpenRPT report writer and rendering engine * Copyright (C) 2001-2007 by OpenMFG, LLC (info@openmfg.com) * Copyright (C) 2007-2008 by Adam Pigg (adam@piggz.co.uk) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "reportsectiondetail.h" #include "reportsectiondetailgroup.h" #include "reportsection.h" #include <QDomDocument> #include <kdebug.h> // // ReportSectionDetail // ReportSectionDetail::ReportSectionDetail(KoReportDesigner * rptdes) : QWidget(rptdes) { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_pageBreak = BreakNone; m_vboxlayout = new QVBoxLayout(this); m_vboxlayout->setSpacing(0); m_vboxlayout->setMargin(0); m_reportDesigner = rptdes; m_detail = new ReportSection(rptdes /*, this*/); m_vboxlayout->addWidget(m_detail); this->setLayout(m_vboxlayout); } ReportSectionDetail::~ReportSectionDetail() { // Qt should be handling everything for us m_reportDesigner = 0; } int ReportSectionDetail::pageBreak() const { return m_pageBreak; } void ReportSectionDetail::setPageBreak(int pb) { m_pageBreak = pb; } ReportSection * ReportSectionDetail::detailSection() const { return m_detail; } void ReportSectionDetail::buildXML(QDomDocument & doc, QDomElement & section) { if (pageBreak() != ReportSectionDetail::BreakNone) { QDomElement spagebreak = doc.createElement("pagebreak"); if (pageBreak() == ReportSectionDetail::BreakAtEnd) spagebreak.setAttribute("when", "at end"); section.appendChild(spagebreak); } foreach(ReportSectionDetailGroup* rsdg, groupList) { rsdg->buildXML(doc, section); } // detail section QDomElement gdetail = doc.createElement("report:section"); gdetail.setAttribute("report:section-type", "detail"); m_detail->buildXML(doc, gdetail); section.appendChild(gdetail); } void ReportSectionDetail::initFromXML(QDomNode & section) { QDomNodeList nl = section.childNodes(); QDomNode node; QString n; for (int i = 0; i < nl.count(); i++) { node = nl.item(i); n = node.nodeName(); //kDebug() << n; if (n == "pagebreak") { QDomElement eThis = node.toElement(); if (eThis.attribute("when") == "at end") setPageBreak(BreakAtEnd); } else if (n == "report:group") { ReportSectionDetailGroup * rsdg = new ReportSectionDetailGroup("unnamed", this, this); rsdg->initFromXML( node.toElement() ); insertGroupSection(groupSectionCount(), rsdg); } else if (n == "report:section" && node.toElement().attribute("report:section-type") == "detail") { //kDebug() << "Creating detail section"; m_detail->initFromXML(node); } else { // unknown element kWarning() << "while parsing section encountered and unknown element: " << n; } } } KoReportDesigner * ReportSectionDetail::reportDesigner() const { return m_reportDesigner; } int ReportSectionDetail::groupSectionCount() const { return groupList.count(); } ReportSectionDetailGroup * ReportSectionDetail::groupSection(int i) const { return groupList.at(i); } void ReportSectionDetail::insertGroupSection(int idx, ReportSectionDetailGroup * rsd) { groupList.insert(idx, rsd); rsd->groupHeader()->setParent(this); rsd->groupFooter()->setParent(this); idx = 0; int gi = 0; for (gi = 0; gi < (int) groupList.count(); gi++) { rsd = groupList.at(gi); m_vboxlayout->removeWidget(rsd->groupHeader()); m_vboxlayout->insertWidget(idx, rsd->groupHeader()); idx++; } m_vboxlayout->removeWidget(m_detail); m_vboxlayout->insertWidget(idx, m_detail); idx++; for (gi = ((int) groupList.count() - 1); gi >= 0; --gi) { rsd = groupList.at(gi); m_vboxlayout->removeWidget(rsd->groupFooter()); m_vboxlayout->insertWidget(idx, rsd->groupFooter()); idx++; } if (m_reportDesigner) m_reportDesigner->setModified(true); adjustSize(); } int ReportSectionDetail::indexOfGroupSection(const QString & column) const { // find the item by its name for (uint i = 0; i < (uint)groupList.count(); i++) { ReportSectionDetailGroup * rsd = groupList.at(i); if (column == rsd->column()) return i; } return -1; } void ReportSectionDetail::removeGroupSection(int idx, bool del) { ReportSectionDetailGroup * rsd = groupList.at(idx); m_vboxlayout->removeWidget(rsd->groupHeader()); m_vboxlayout->removeWidget(rsd->groupFooter()); groupList.removeAt(idx); if (m_reportDesigner) m_reportDesigner->setModified(true); if (del) delete rsd; adjustSize(); } QSize ReportSectionDetail::sizeHint() const { QSize s; foreach(ReportSectionDetailGroup* rsdg, groupList) { if (rsdg->groupHeaderVisible()) s += rsdg->groupHeader()->size(); if (rsdg->groupFooterVisible()) s += rsdg->groupFooter()->size(); } return s += m_detail->size(); } void ReportSectionDetail::setSectionCursor(const QCursor& c) { if (m_detail) m_detail->setSectionCursor(c); foreach(ReportSectionDetailGroup* rsdg, groupList) { if (rsdg->groupHeader()) rsdg->groupHeader()->setSectionCursor(c); if (rsdg->groupFooter()) rsdg->groupFooter()->setSectionCursor(c); } } void ReportSectionDetail::unsetSectionCursor() { if (m_detail) m_detail->unsetSectionCursor(); foreach(ReportSectionDetailGroup* rsdg, groupList) { if (rsdg->groupHeader()) rsdg->groupHeader()->unsetSectionCursor(); if (rsdg->groupFooter()) rsdg->groupFooter()->unsetSectionCursor(); } }
donniexyz/calligra
libs/koreport/wrtembed/reportsectiondetail.cpp
C++
gpl-2.0
6,405
<?php /******************************************************************************* Copyright 2010 Whole Foods Co-op This file is part of CORE-POS. CORE-POS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. CORE-POS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ // set a variable in the config file function confset($key, $value) { $FILEPATH = realpath(dirname(__FILE__).'/../'); $lines = array(); $found = false; $fptr = fopen($FILEPATH.'/config.php','r'); while($line = fgets($fptr)) { if (strpos($line,"\$$key ") === 0) { $lines[] = "\$$key = $value;\n"; $found = true; } elseif (strpos($line,"?>") === 0 && $found === false) { $lines[] = "\$$key = $value;\n"; $lines[] = "?>\n"; $found = true; break; // stop at closing tag } else { $lines[] = $line; } } fclose($fptr); // implies no closing tag was found so new settings // still needs to be added if ($found === false) { $lines[] = "\$$key = $value;\n"; } // verify first line is a proper opening php tag // if it contains an opening tag with differnet format, // just replace that line. Otherwise add one and scan // through to make sure there isn't another one later // in the file if (isset($lines[0]) && $lines[0] != "<?php\n") { if (strstr($lines[0], "<?php")) { $lines[0] = "<?php\n"; } else { $tmp = array("<?php\n"); for ($i=0; $i<count($lines); $i++) { if (!strstr($lines[$i], "<?php")) { $tmp[] = $lines[$i]; } } $lines = $tmp; } } $fptr = fopen($FILEPATH.'/config.php','w'); foreach($lines as $line) { fwrite($fptr,$line); } fclose($fptr); } function check_db_host($host,$dbms) { if (!function_exists("socket_create")) { return true; // test not possible } if (empty($host)) { return false; } $port = 0; switch (strtoupper($dbms)) { case 'MYSQL': case 'MYSQLI': case 'PDO_MYSQL': $port = 3306; break; case 'MSSQL': $port = 1433; break; case 'PGSQL': case 'POSTGRES9': $port = 5432; break; default: return false; } if (strstr($host,":")) { list($host,$port) = explode(":",$host,2); } $test = false; $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0)); socket_set_block($sock); try { $test = @socket_connect($sock,$host,$port); } catch(Exception $ex) {} socket_close($sock); return ($test ? true : false); } function db_test_connect($host,$type,$db,$user,$pw){ if (!check_db_host($host,$type)) return False; if (!class_exists('SQLManager')) include(dirname(__FILE__) . '/../src/SQLManager.php'); $sql = False; try { $sql = new SQLManager($host,$type,$db,$user,$pw); } catch(Exception $ex) {} if ($sql === False || $sql->connections[$db] === False) return False; else return $sql; } function showInstallTabs($current,$path='') { $ret = ""; $ret .= "<ul class='installTabList'>"; $installTabs = array( 'Necessities'=>'InstallIndexPage.php', 'Authentication' => 'InstallAuthenticationPage.php', 'Members' => 'InstallMembershipPage.php', 'Products' => 'InstallProductsPage.php', 'Stores' => 'InstallStoresPage.php', 'Updates' => 'InstallUpdatesPage.php', 'Plugins' => 'InstallPluginsPage.php', 'Menu' => 'InstallMenuPage.php', 'Theming' => 'InstallThemePage.php', 'Lane Config' => 'LaneConfigPages/index.php', 'Sample Data' => 'sample_data/InstallSampleDataPage.php' ); foreach($installTabs as $key => $loc) { if ( $key == $current ) { $ret .= "<li class='installTab'>$key</li>"; } else { $ret .= "<li class='installTab'><a href='$path$loc'>$key</a></li>"; } } $ret .= "</ul>"; $ret .= "<br style='clear:both;' />"; return $ret; // showInstallTabs() } function showInstallTabsLane($current,$path='') { $ret = ""; $ret .= "<ul class='installTabList2'>"; $url = FannieConfig::config('URL'); $installTabs = array( 'Lane Necessities'=>'LaneNecessitiesPage.php', 'Additional Configuration' => 'LaneAdditionalConfigPage.php', 'Scanning Options' => 'LaneScanningPage.php', 'Security' => 'LaneSecurityPage.php', 'Text Strings' => $url . '/admin/ReceiptText/LaneTextStringPage.php' ); /* Original $installTabs = array( 'Lane Necessities'=>'index.php', 'Additional Configuration' => 'extra_config.php', 'Scanning Options' => 'scanning.php', 'Security' => 'security.php', 'Text Strings' => 'text.php' ); */ foreach($installTabs as $key => $loc) { if ( $key == $current ) { $ret .= "<li class='installTab2'>$key</li>"; } else { $ret .= "<li class='installTab2'><a href='$path$loc'>$key</a></li>"; } } $ret .= "</ul>"; $ret .= "<br style='clear:both;' />"; return $ret; // showInstallTabsLane() } /* * Link "up" to home of next higher level of pages. * See also: showLinkUp(), which takes arguments. */ function showLinkToFannie() { $key = 'Up to Fannie Config'; $loc = 'index.php'; $path = '../'; $ret = "<ul class='installTabList'>"; $ret .= "<li class='installTab'><a href='$path$loc'>$key</a></li>"; $ret .= "</ul>"; $ret .= "<br style='clear:both;' />"; return $ret; } /* Link "up" to higher level of install pages. * Possibly up the file tree. */ function showLinkUp($label='None',$loc='',$path='') { if ( substr($path,-2,2) == '..' ) $path = "{$path}/"; $ret = "<ul class='installTabList'>"; $ret .= "<li class='installTab'><a href='$path$loc'>$label</a></li>"; $ret .= "</ul>"; $ret .= "<br style='clear:both;' />"; return $ret; } /** Get username for PHP process @return string username */ function whoami(){ if (function_exists('posix_getpwuid')){ $chk = posix_getpwuid(posix_getuid()); return $chk['name']; } else return get_current_user(); } /** Check if file exists and is writable by PHP @param $filename the file @param $optional boolean file is not required @param $template string template for creating file Known $template values: PHP Prints output */ function check_writeable($filename, $optional=False, $template=False){ $basename = basename($filename); $failure = ($optional) ? 'blue' : 'red'; $status = ($optional) ? 'Optional' : 'Warning'; if (!file_exists($filename) && !$optional && is_writable($filename)){ $fptr = fopen($filename,'w'); if ($template !== False){ switch($template){ case 'PHP': fwrite($fptr,"<?php\n"); fwrite($fptr,"\n"); break; } } fclose($fptr); } if (!file_exists($filename)){ echo "<span style=\"color:$failure;\"><b>$status</b>: $basename does not exist</span><br />"; if (!$optional){ echo "<b>Advice</b>: <div style=\"font-face:mono;background:#ccc;padding:8px;\"> touch \"".realpath(dirname($filename))."/".basename($filename)."\"<br /> chown ".whoami()." \"".realpath(dirname($filename))."/".basename($filename)."\"</div>"; } } elseif (is_writable($filename)) echo "<span style=\"color:green;\">$basename is writeable</span><br />"; else { echo "<span style=\"color:red;\"><b>Warning</b>: $basename is not writeable</span><br />"; echo "<b>Advice</b>: <div style=\"font-face:mono;background:#ccc;padding:8px;\"> chown ".whoami()." \"".realpath(dirname($filename))."/".basename($filename)."\"<br /> chmod 600 \"".realpath(dirname($filename))."/".basename($filename)."\"</div>"; } } function sanitizeFieldQuoting($current_value) { // quoted must not contain single quotes $current_value = str_replace("'", '', $current_value); // must not start with backslash while (strlen($current_value) > 0 && substr($current_value, 0, 1) == "\\") { $current_value = substr($current_value, 1); } // must not end with backslash while (strlen($current_value) > 0 && substr($current_value, -1) == "\\") { $current_value = substr($current_value, 0, strlen($current_value)-1); } return $current_value; } /** Render configuration variable as an <input> tag Process any form submissions Write configuration variable to config.php @param $name [string] name of the variable @param $current_value [mixed] the actual config variable @param $default_value [mixed, default empty string] default value for the setting @param $quoted [boolean, default true] write value to config.php with single quotes @param $attributes [array, default empty] array of <input> tag attribute names and values @return [string] html input field */ function installTextField($name, &$current_value, $default_value='', $quoted=true, $attributes=array()) { if (FormLib::get($name, false) !== false) { $current_value = FormLib::get($name); } else if ($current_value === null) { $current_value = $default_value; } // sanitize values: if (!$quoted) { // unquoted must be a number or boolean if (!is_numeric($current_value) && strtolower($current_value) !== 'true' && strtolower($current_value) !== false) { $current_value = (int)$current_value; } } elseif ($quoted) { $current_value = sanitizeFieldQuoting($current_value); } confset($name, ($quoted ? "'" . $current_value . "'" : $current_value)); $quote_char = strstr($current_value, '"') ? '\'' : '"'; $ret = sprintf('<input name="%s" value=%s%s%s', $name, $quote_char, $current_value, $quote_char); if (!isset($attributes['type'])) { $attributes['type'] = 'text'; } if (isset($attributes['class'])) { $attributes['class'] .= ' form-control'; } else { $attributes['class'] = 'form-control'; } foreach ($attributes as $name => $value) { if ($name == 'name' || $name == 'value') { continue; } $ret .= ' ' . $name . '="' . $value . '"'; } $ret .= " />\n"; return $ret; } /** Render configuration variable as an <select> tag Process any form submissions Write configuration variable to config.php @param $name [string] name of the variable @param $current_value [mixed] the actual config variable @param $options [array] list of options This can be a keyed array in which case the keys are what is written to config.php and the values are what is shown in the user interface, or it can simply be an array of valid values. @param $default_value [mixed, default empty string] default value for the setting @param $quoted [boolean, default true] write value to config.php with single quotes @return [string] html select field */ function installSelectField($name, &$current_value, $options, $default_value='', $quoted=true) { if (FormLib::get($name, false) !== false) { $current_value = FormLib::get($name); } else if ($current_value === null) { $current_value = $default_value; } // sanitize values: if (!$quoted) { // unquoted must be a number or boolean // convert booleans to strings for writing to config.php if (count($options) == 2 && is_bool($default_value)) { if ($current_value) { $current_value = 'true'; } else { $current_value = 'false'; } } if (!is_numeric($current_value) && strtolower($current_value) !== 'true' && strtolower($current_value) !== 'false') { $current_value = (int)$current_value; } } elseif ($quoted) { $current_value = sanitizeFieldQuoting($current_value); } confset($name, ($quoted ? "'" . $current_value . "'" : $current_value)); // convert boolean back from strings after writing config.php if (!$quoted && count($options) == 2 && is_bool($default_value)) { if (strtolower($current_value) == 'true') { $current_value = true; } elseif (strtolower($current_value) == 'false') { $current_value = false; } } $ret = '<select name="' . $name . '" class="form-control">' . "\n"; // array has non-numeric keys // if the array has meaningful keys, use the key value // combination to build <option>s with labels $has_keys = ($options === array_values($options)) ? false : true; foreach ($options as $key => $value) { $selected = ''; if ($has_keys && $current_value == $key) { $selected = 'selected'; } elseif (!$has_keys && $current_value == $value) { $selected = 'selected'; } $optval = $has_keys ? $key : $value; $ret .= sprintf('<option value="%s" %s>%s</option>', $optval, $selected, $value); $ret .= "\n"; } $ret .= '</select>' . "\n"; return $ret; }
CORE-POS/Office
fannie/install/util.php
PHP
gpl-2.0
14,367
<?php /** * WPBakery Visual Composer Shortcodes settings * * @package VPBakeryVisualComposer * */ WPBMap::map( 'vc_column_text', array( "name" => __("Text block", "js_composer"), "base" => "vc_column_text", "class" => "", "icon" => "icon-wpb-layer-shape-text", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "title", "value" => "", "description" => __("Heading text. Leave it empty if not needed.", "js_composer") ), array( "type" => "textfield", "heading" => __("Title icon", "js_composer"), "param_name" => "icon", "value" => "", "description" => __("Icon to the left of the title text. You can get the code from <a href='http://fortawesome.github.com/Font-Awesome/' target='_blank'>here</a>. E.g. icon-cloud", "js_composer") ), array( "type" => "textarea_html", "holder" => "div", "class" => "", "heading" => __("Text", "js_composer"), "param_name" => "content", "value" => __("<p>I am text block. click the edit button to change this text.</p>", "js_composer"), "description" => __("Enter your content.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Margin below widget", "js_composer"), "param_name" => "pb_margin_bottom", "value" => array(__('No', "js_composer") => "no", __('Yes', "js_composer") => "yes"), "description" => __("Add a bottom margin to the widget.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Border below widget", "js_composer"), "param_name" => "pb_border_bottom", "value" => array(__('No', "js_composer") => "no", __('Yes', "js_composer") => "yes"), "description" => __("Add a bottom border to the widget.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ) ) ); /* Boxed Content ---------------------------------------------------------- */ WPBMap::map( 'box', array( "name" => __("Boxed content", "js_composer"), "base" => "box", "class" => "", "icon" => "icon-wpb-layer-shape-box", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "title", "value" => "", "description" => __("Heading text. Leave it empty if not needed.", "js_composer") ), array( "type" => "textarea_html", "holder" => "div", "class" => "", "heading" => __("Text", "js_composer"), "param_name" => "content", "value" => __("<p>I am boxed content block. click the edit button to change this text.</p>", "js_composer"), "description" => __("Enter your content.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Box type", "js_composer"), "param_name" => "type", "value" => array(__('Coloured', "js_composer") => "coloured", __('White with stroke', "js_composer") => "whitestroke"), "description" => __("Choose the surrounding box type for this content", "js_composer") ), array( "type" => "textfield", "heading" => __("Custom background colour", "js_composer"), "param_name" => "custom_bg_colour", "value" => "", "description" => __("Provide a hex colour code here (include #). If blank, your chosen accent colour will be used.", "js_composer") ), array( "type" => "textfield", "heading" => __("Custom text colour", "js_composer"), "param_name" => "custom_text_colour", "value" => "", "description" => __("Provide a hex colour code here (include #) if you want to override the default (#ffffff).", "js_composer") ), array( "type" => "dropdown", "heading" => __("Margin below widget", "js_composer"), "param_name" => "pb_margin_bottom", "value" => array(__('No', "js_composer") => "no", __('Yes', "js_composer") => "yes"), "description" => __("Add a bottom margin to the widget.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ) ) ); // ///* Latest tweets //---------------------------------------------------------- */ //WPBMap::map( 'vc_twitter', array( // "name" => __("Twitter widget", "js_composer"), // "base" => "vc_twitter", // "class" => "wpb_vc_twitter_widget", // "icon" => 'icon-wpb-balloon-twitter-left', // "params" => array( // array( // "type" => "textfield", // "heading" => __("Widget title", "js_composer"), // "param_name" => "title", // "value" => "", // "description" => __("What text use as widget title. Leave blank if no title is needed.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Twitter name", "js_composer"), // "param_name" => "twitter_name", // "value" => "", // "description" => __("Type in twitter profile name from which load tweets.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Tweets count", "js_composer"), // "param_name" => "tweets_count", // "value" => array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), // "description" => __("How many recent tweets to load.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ) //) ); /* Separator (Divider) ---------------------------------------------------------- */ WPBMap::map( 'divider', array( "name" => __("Divider", "js_composer"), "base" => "divider", "class" => "wpb_divider wpb_controls_top_right", 'icon' => 'icon-wpb-ui-divider', "controls" => 'edit_popup_delete', "params" => array( array( "type" => "dropdown", "heading" => __("Divider type", "js_composer"), "param_name" => "type", "value" => array(__('Standard', "js_composer") => "standard", __('Thin', "js_composer") => "thin", __('Dotted', "js_composer") => "dotted", __('Go to top (text)', "js_composer") => "go_to_top", __('Go to top (Icon 1)', "js_composer") => "go_to_top_icon1", __('Go to top (Icon 2)', "js_composer") => "go_to_top_icon2"), "description" => __("Select divider type.", "js_composer") ), array( "type" => "textfield", "heading" => __("Go to top text", "js_composer"), "param_name" => "text", "value" => __("Go to top", "js_composer"), "description" => __("The text for the 'Go to top (text)' divider type.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Full width", "js_composer"), "param_name" => "full_width", "value" => array(__('No', "js_composer") => "no", __('Yes', "js_composer") => "yes"), "description" => __("Select yes if you'd like the divider to be full width (only to be used with no sidebars, and with Standard/Thin/Dotted divider types).", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "js_callback" => array("init" => "wpbTextSeparatorInitCallBack") ) ); /* Blank Spacer (Divider) ---------------------------------------------------------- */ WPBMap::map( 'blank_spacer', array( "name" => __("Blank Spacer", "js_composer"), "base" => "blank_spacer", "class" => "blank_spacer wpb_controls_top_right", 'icon' => 'icon-wpb-ui-blank-spacer', "controls" => 'edit_popup_delete', "params" => array( array( "type" => "textfield", "heading" => __("Height", "js_composer"), "param_name" => "height", "value" => __("30px", "js_composer"), "description" => __("The height of the spacer, in px (required).", "js_composer") ), array( "type" => "textfield", "heading" => __("Spacer ID", "js_composer"), "param_name" => "spacer_id", "value" => "", "description" => __("If you wish to add an ID to the spacer, then add it here. You can then use the id to deep link to this section of the page. NOTE: Make sure this is unique to the page!!", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "js_callback" => array("init" => "wpbBlankSpacerInitCallBack") ) ); // //* Textual block //---------------------------------------------------------- */ //WPBMap::map( 'vc_text_separator', array( // "name" => __("Separator (Divider) with text", "js_composer"), // "base" => "vc_text_separator", // "class" => "wpb_controls_top_right", // "controls" => "edit_popup_delete", // "icon" => "icon-wpb-ui-separator-label", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Title", "js_composer"), // "param_name" => "title", // "holder" => "div", // "value" => __("Title", "js_composer"), // "description" => __("Separator title.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Title position", "js_composer"), // "param_name" => "title_align", // "value" => array(__('Align center', "js_composer") => "separator_align_center", __('Align left', "js_composer") => "separator_align_left", __('Align right', "js_composer") => "separator_align_right"), // "description" => __("Select title location.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ), // "js_callback" => array("init" => "wpbTextSeparatorInitCallBack") //) ); /* Message box ---------------------------------------------------------- */ WPBMap::map( 'vc_message', array( "name" => __("Message box", "js_composer"), "base" => "vc_message", "class" => "wpb_vc_messagebox wpb_controls_top_right", "icon" => "icon-wpb-information-white", "wrapper_class" => "alert", "controls" => "edit_popup_delete", "params" => array( array( "type" => "dropdown", "heading" => __("Message box type", "js_composer"), "param_name" => "color", "value" => array(__('Informational', "js_composer") => "alert-info", __('Warning', "js_composer") => "alert-block", __('Success', "js_composer") => "alert-success", __('Error', "js_composer") => "alert-error"), "description" => __("Select message type.", "js_composer") ), array( "type" => "textarea_html", "holder" => "div", "class" => "messagebox_text", "heading" => __("Message text", "js_composer"), "param_name" => "content", "value" => __("<p>I am message box. click the edit button to change this text.</p>", "js_composer"), "description" => __("Message text.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "js_callback" => array("init" => "wpbMessageInitCallBack") ) ); // ///* Facebook like button //---------------------------------------------------------- */ //WPBMap::map( 'vc_facebook', array( // "name" => __("Facebook like", "js_composer"), // "base" => "vc_facebook", // "class" => "wpb_vc_facebooklike wpb_controls_top_right", // "icon" => "icon-wpb-balloon-facebook-left", // "controls" => "edit_popup_delete", // "params" => array( // array( // "type" => "dropdown", // "heading" => __("Button type", "js_composer"), // "param_name" => "type", // "value" => array(__("Standard", "js_composer") => "standard", __("Button count", "js_composer") => "button_count", __("Box count", "js_composer") => "box_count"), // "description" => __("Select button type.", "js_composer") // ) // ) //) ); // ///* Tweetmeme button //---------------------------------------------------------- */ //WPBMap::map( 'vc_tweetmeme', array( // "name" => __("Tweetmeme button", "js_composer"), // "base" => "vc_tweetmeme", // "class" => "wpb_controls_top_right", // "icon" => "icon-wpb-balloon-twitter-left", // "controls" => "edit_popup_delete", // "params" => array( // array( // "type" => "dropdown", // "heading" => __("Button type", "js_composer"), // "param_name" => "type", // "value" => array(__("Horizontal", "js_composer") => "horizontal", __("Vertical", "js_composer") => "vertical", __("None", "js_composer") => "none"), // "description" => __("Select button type.", "js_composer") // ) // ) //) ); // ///* Google+ button //---------------------------------------------------------- */ //WPBMap::map( 'vc_googleplus', array( // "name" => __("Google+ button", "js_composer"), // "base" => "vc_googleplus", // "class" => "wpb_vc_googleplus wpb_controls_top_right", // "icon" => "icon-wpb-application-plus", // "controls" => "edit_popup_delete", // "params" => array( // array( // "type" => "dropdown", // "heading" => __("Button size", "js_composer"), // "param_name" => "type", // "value" => array(__("Standard", "js_composer") => "", __("Small", "js_composer") => "small", __("Medium", "js_composer") => "medium", __("Tall", "js_composer") => "tall"), // "description" => __("Select button type.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Annotation", "js_composer"), // "param_name" => "annotation", // "value" => array(__("Inline", "js_composer") => "inline", __("Bubble", "js_composer") => "", __("None", "js_composer") => "none"), // "description" => __("Select annotation type.", "js_composer") // ) // ) //) ); // ///* Google+ button //---------------------------------------------------------- */ //WPBMap::map( 'vc_pinterest', array( // "name" => __("Pinterest button", "js_composer"), // "base" => "vc_pinterest", // "class" => "wpb_vc_pinterest wpb_controls_top_right", // "icon" => "icon-wpb-pinterest", // "controls" => "edit_popup_delete", // "params" => array( // array( // "type" => "dropdown", // "heading" => __("Button layout", "js_composer"), // "param_name" => "type", // "value" => array(__("Horizontal", "js_composer") => "", __("Vertical", "js_composer") => "vertical", __("No count", "js_composer") => "none"), // "description" => __("Select button type.", "js_composer") // ) // ) //) ); /* Toggle (FAQ) ---------------------------------------------------------- */ WPBMap::map( 'vc_toggle', array( "name" => __("Toggle", "js_composer"), "base" => "vc_toggle", "class" => "wpb_vc_faq", "icon" => "icon-wpb-toggle-small-expand", "params" => array( array( "type" => "textfield", "holder" => "h4", "class" => "toggle_title", "heading" => __("Toggle title", "js_composer"), "param_name" => "title", "value" => __("Toggle title", "js_composer"), "description" => __("Toggle block title.", "js_composer") ), array( "type" => "textarea_html", "holder" => "div", "class" => "toggle_content", "heading" => __("Toggle content", "js_composer"), "param_name" => "content", "value" => __("<p>Toggle content goes here, click the edit button.</p>", "js_composer"), "description" => __("Toggle block content.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Default state", "js_composer"), "param_name" => "open", "value" => array(__("Closed", "js_composer") => "false", __("Open", "js_composer") => "true"), "description" => __("Select this if you want toggle to be open by default.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ) ) ); /* Single image */ WPBMap::map( 'vc_single_image', array( "name" => __("Single image", "js_composer"), "base" => "vc_single_image", "class" => "wpb_vc_single_image_widget", "icon" => "icon-wpb-single-image", "params" => array( array( "type" => "attach_image", "heading" => __("Image", "js_composer"), "param_name" => "image", "value" => "", "description" => "" ), array( "type" => "dropdown", "heading" => __("Image Size", "js_composer"), "param_name" => "image_size", "value" => array(__("Full", "js_composer") => "full", __("Large", "js_composer") => "large", __("Medium", "js_composer") => "medium", __("Thumbnail", "js_composer") => "thumbnail"), "description" => __("Select the source size for the image (NOTE: this doesn't affect it's size on the front-end, only the quality).", "js_composer") ), array( "type" => "dropdown", "heading" => __("Image Frame", "js_composer"), "param_name" => "frame", "value" => array(__("No Frame", "js_composer") => "noframe", __("Border Frame", "js_composer") => "borderframe", __("Glow Frame", "js_composer") => "glowframe", __("Shadow Frame", "js_composer") => "shadowframe"), "description" => __("Select a frame for the image.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Full width", "js_composer"), "param_name" => "full_width", "value" => array(__("No", "js_composer") => "no", __("Yes", "js_composer") => "yes"), "description" => __("Select if you want the image to be the full width of the page. (Make sure the element width is 1/1 too).", "js_composer") ), array( "type" => "dropdown", "heading" => __("Enable lightbox link", "js_composer"), "param_name" => "lightbox", "value" => array(__("Yes", "js_composer") => "yes", __("No", "js_composer") => "no"), "description" => __("Select if you want the image to open in a lightbox on click", "js_composer") ), array( "type" => "textfield", "heading" => __("Add link to image", "js_composer"), "param_name" => "image_link", "value" => "", "description" => __("If you would like the image to link to a URL, then enter it here. NOTE: this will override the lightbox functionality if you have enabled it.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Link opens in new window?", "js_composer"), "param_name" => "link_target", "value" => array(__("Self", "js_composer") => "_self", __("New Window", "js_composer") => "_blank"), "description" => __("Select if you want the link to open in a new window", "js_composer") ), array( "type" => "textfield", "heading" => __("Image Caption", "js_composer"), "param_name" => "caption", "value" => "", "description" => __("If you would like a caption to be shown below the image, add it here.", "js_composer") ) ) )); // Gallery/Slideshow //---------------------------------------------------------- //WPBMap::map( 'vc_gallery', array( // "name" => __("Image gallery", "js_composer"), // "base" => "vc_gallery", // "class" => "wpb_vc_gallery_widget", // "icon" => "icon-wpb-images-stack", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Widget title", "js_composer"), // "param_name" => "title", // "value" => "", // "description" => __("What text use as widget title. Leave blank if no title is needed.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Gallery type", "js_composer"), // "param_name" => "type", // "value" => array(__("Flex slider fade", "js_composer") => "flexslider_fade", __("Flex slider slide", "js_composer") => "flexslider_slide", __("Nivo slider", "js_composer") => "nivo", __("Image grid", "js_composer") => "image_grid"), // "description" => __("Select gallery type. Note: Nivo slider is not fully responsive.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Auto rotate slides", "js_composer"), // "param_name" => "interval", // "value" => array(3, 5, 10, 15, 0), // "description" => __("Auto rotate slides each X seconds. Select 0 to disable.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("On click", "js_composer"), // "param_name" => "onclick", // "value" => array(__("Open prettyPhoto", "js_composer") => "link_image", __("Do nothing", "js_composer") => "link_no", __("Open custom link", "js_composer") => "custom_link"), // "description" => __("What to do when slide is clicked?.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Image size", "js_composer"), // "param_name" => "img_size", // "value" => "", // "description" => __("Enter image size. Example: thumbnail, medium, large, full or other sizes defined by current theme. Alternatively enter image size in pixels: 200x100 (Width x Height). Leave empty to use 'thumbnail' size.", "js_composer") // ), // array( // "type" => "attach_images", // "heading" => __("Images", "js_composer"), // "param_name" => "images", // "value" => "", // "description" => "" // ), // array( // "type" => "exploded_textarea", // "heading" => __("Custom links", "js_composer"), // "param_name" => "custom_links", // "description" => __('Select "Open custom link" in "On click" parameter and then enter links for each slide here. Divide links with linebreaks (Enter).', 'js_composer') // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ) //) ); /* Tabs This one is an advanced example. It has javascript callbacks in it. So basically in your theme you can do whatever you want. More detailed documentation located in the advanced documentation folder. ---------------------------------------------------------- */ WPBMap::map( 'vc_tabs', array( "name" => __("Tabs", "js_composer"), "base" => "vc_tabs", "controls" => "full", "class" => "wpb_tabs", "icon" => "icon-wpb-ui-tab-content", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "tab_asset_title", "value" => "", "description" => __("What text use as widget title. Leave blank if no title is needed.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "custom_markup" => ' <div class="tab_controls"> <button class="add_tab">'.__("Add tab", "js_composer").'</button> <button class="edit_tab">'.__("Edit current tab title", "js_composer").'</button> <button class="delete_tab">'.__("Delete current tab", "js_composer").'</button> </div> <div class="wpb_tabs_holder"> %content% </div>', 'default_content' => ' <ul> <li><a href="#tab-1"><span>'.__('Tab 1', 'js_composer').'</span></a></li> <li><a href="#tab-2"><span>'.__('Tab 2', 'js_composer').'</span></a></li> </ul> <div id="tab-1" class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] </div> <div id="tab-2" class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] </div>', "js_callback" => array("init" => "wpbTabsInitCallBack", "shortcode" => "wpbTabsGenerateShortcodeCallBack") //"js_callback" => array("init" => "wpbTabsInitCallBack", "edit" => "wpbTabsEditCallBack", "save" => "wpbTabsSaveCallBack", "shortcode" => "wpbTabsGenerateShortcodeCallBack") ) ); // Tour section //---------------------------------------------------------- //WPBMap::map( 'vc_tour', array( // "name" => __("Tour section", "js_composer"), // "base" => "vc_tour", // "controls" => "full", // "class" => "wpb_tour", // "icon" => "icon-wpb-ui-tab-content-vertical", // "wrapper_class" => "clearfix", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Widget title", "js_composer"), // "param_name" => "title", // "value" => "", // "description" => __("What text use as widget title. Leave blank if no title is needed.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Auto rotate slides", "js_composer"), // "param_name" => "interval", // "value" => array(0, 3, 5, 10, 15), // "description" => __("Auto rotate slides each X seconds. Select 0 to disable.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ), // "custom_markup" => ' // <div class="tab_controls"> // <button class="add_tab">'.__("Add slide", "js_composer").'</button> // <button class="edit_tab">'.__("Edit current slide title", "js_composer").'</button> // <button class="delete_tab">'.__("Delete current slide", "js_composer").'</button> // </div> // // <div class="wpb_tabs_holder clearfix"> // %content% // </div>', // 'default_content' => ' // <ul> // <li><a href="#tab-1"><span>'.__('Slide 1', 'js_composer').'</span></a></li> // <li><a href="#tab-2"><span>'.__('Slide 2', 'js_composer').'</span></a></li> // </ul> // // <div id="tab-1" class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> // [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] // </div> // // <div id="tab-2" class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> // [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] // </div>', // "js_callback" => array("init" => "wpbTabsInitCallBack", "shortcode" => "wpbTabsGenerateShortcodeCallBack") //) ); /* Accordion section ---------------------------------------------------------- */ WPBMap::map( 'vc_accordion', array( "name" => __("Accordion section", "js_composer"), "base" => "vc_accordion", "controls" => "full", "class" => "wpb_accordion", "icon" => "icon-wpb-ui-accordion", // "wrapper_class" => "clearfix", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "widget_title", "value" => "", "description" => __("What text use as widget title. Leave blank if no title is needed.", "js_composer") ), array( "type" => "textfield", "heading" => __("Active Section", "js_composer"), "param_name" => "active_section", "value" => "", "description" => __("You can set the section that is active here by entering the number of the section here. NOTE: The first section would be 0, second would be 1, and so on. Leave blank for all sections to be closed by default.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "custom_markup" => ' <div class="tab_controls"> <button class="add_tab">'.__("Add section", "js_composer").'</button> <button class="edit_tab">'.__("Edit current section title", "js_composer").'</button> <button class="delete_tab">'.__("Delete current section", "js_composer").'</button> </div> <div class="wpb_accordion_holder clearfix"> %content% </div>', 'default_content' => ' <div class="group"> <h3><a href="#">'.__('Section 1', 'js_composer').'</a></h3> <div> <div class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] </div> </div> </div> <div class="group"> <h3><a href="#">'.__('Section 2', 'js_composer').'</a></h3> <div> <div class="row-fluid wpb_column_container wpb_sortable_container not-column-inherit"> [vc_column_text width="1/1"] '.__('I am text block. click the edit button to change this text.', 'js_composer').' [/vc_column_text] </div> </div> </div>', "js_callback" => array("init" => "wpbAccordionInitCallBack", "shortcode" => "wpbAccordionGenerateShortcodeCallBack") ) ); // Teaser grid //---------------------------------------------------------- //WPBMap::map( 'vc_teaser_grid', array( // "name" => __("Teaser (posts) grid", "js_composer"), // "base" => "vc_teaser_grid", // "class" => "wpb_vc_teaser_grid_widget", // "icon" => "icon-wpb-application-icon-large", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Widget title", "js_composer"), // "param_name" => "title", // "value" => "", // "description" => __("Heading text. Leave it empty if not needed.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Columns count", "js_composer"), // "param_name" => "grid_columns_count", // "value" => array(4, 3, 2, 1), // "description" => __("Select columns count.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Teaser count", "js_composer"), // "param_name" => "grid_teasers_count", // "value" => "", // "description" => __('How many teasers to show? Enter number or "All".', "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Content", "js_composer"), // "param_name" => "grid_content", // "value" => array(__("Teaser (Excerpt)", "js_composer") => "teaser", __("Full Content", "js_composer") => "content"), // "description" => __("Teaser layout template.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Layout", "js_composer"), // "param_name" => "grid_layout", // "value" => array(__("Title + Thumbnail + Text", "js_composer") => "title_thumbnail_text", __("Thumbnail + Title + Text", "js_composer") => "thumbnail_title_text", __("Thumbnail + Text", "js_composer") => "thumbnail_text", __("Thumbnail + Title", "js_composer") => "thumbnail_title", __("Thumbnail only", "js_composer") => "thumbnail", __("Title + Text", "js_composer") => "title_text"), // "description" => __("Teaser layout.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Link", "js_composer"), // "param_name" => "grid_link", // "value" => array(__("Link to post", "js_composer") => "link_post", __("Link to bigger image", "js_composer") => "link_image", __("Thumbnail to bigger image, title to post", "js_composer") => "link_image_post", __("No link", "js_composer") => "link_no"), // "description" => __("Link type.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Template", "js_composer"), // "param_name" => "grid_template", // "value" => array(__("Grid", "js_composer") => "grid", __("Carousel", "js_composer") => "carousel"), // "description" => __("Teaser layout template.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Thumbnail size", "js_composer"), // "param_name" => "grid_thumb_size", // "value" => "", // "description" => __('Enter thumbnail size. Example: thumbnail, medium, large, full or other sizes defined by current theme. Alternatively enter image size in pixels: 200x100 (Width x Height).', "js_composer") // ), // array( // "type" => "posttypes", // "heading" => __("Post types", "js_composer"), // "param_name" => "grid_posttypes", // "description" => __("Select post types to populate posts from.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Post/Page IDs", "js_composer"), // "param_name" => "posts_in", // "value" => "", // "description" => __('Fill this field with page/posts IDs separated by commas (,) to retrieve only them. Use this in conjunction with "Post types" field.', "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Exclude Post/Page IDs", "js_composer"), // "param_name" => "posts_not_in", // "value" => "", // "description" => __('Fill this field with page/posts IDs separated by commas (,) to exclude them from query.', "js_composer") // ), // array( // "type" => "exploded_textarea", // "heading" => __("Categories", "js_composer"), // "param_name" => "grid_categories", // "description" => __("If you want to narrow output, enter category names here. Note: Only listed categories will be included. Divide categories with linebreaks (Enter).", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Order by", "js_composer"), // "param_name" => "orderby", // "value" => array( "", __("Date", "js_composer") => "date", __("ID", "js_composer") => "ID", __("Author", "js_composer") => "author", __("Title", "js_composer") => "title", __("Modified", "js_composer") => "modified", __("Random", "js_composer") => "rand", __("Comment count", "js_composer") => "comment_count", __("Menu order", "js_composer") => "menu_order" ), // "description" => __('Select how to sort retrieved posts. More at <a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>.', 'js_composer') // ), // array( // "type" => "dropdown", // "heading" => __("Order by", "js_composer"), // "param_name" => "order", // "value" => array( __("Descending", "js_composer") => "DESC", __("Ascending", "js_composer") => "ASC" ), // "description" => __('Designates the ascending or descending order. More at <a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>.', 'js_composer') // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ) //) ); // Teaser grid //---------------------------------------------------------- //WPBMap::map( 'vc_posts_slider', array( // "name" => __("Posts slider", "js_composer"), // "base" => "vc_posts_slider", // "class" => "wpb_vc_posts_slider_widget", // "icon" => "icon-wpb-slideshow", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Widget title", "js_composer"), // "param_name" => "title", // "value" => "", // "description" => __("Heading text. Leave it empty if not needed.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Slider type", "js_composer"), // "param_name" => "type", // "value" => array(__("Flex slider fade", "js_composer") => "flexslider_fade", __("Flex slider slide", "js_composer") => "flexslider_slide", __("Nivo slider", "js_composer") => "nivo"), // "description" => __("Select slider type. Note: Nivo slider is not fully responsive.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Slides count", "js_composer"), // "param_name" => "count", // "value" => "", // "description" => __('How many slides to show? Enter number or "All".', "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Auto rotate slides", "js_composer"), // "param_name" => "interval", // "value" => array(3, 5, 10, 15, 0), // "description" => __("Auto rotate slides each X seconds. Select 0 to disable.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Description", "js_composer"), // "param_name" => "slides_content", // "value" => array(__("No description", "js_composer") => "", __("Teaser (Excerpt)", "js_composer") => "teaser" ), // "description" => __("Some sliders support description text, what content use for it?", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Link", "js_composer"), // "param_name" => "link", // "value" => array(__("Link to post", "js_composer") => "link_post", __("Link to bigger image", "js_composer") => "link_image", __("Open custom link", "js_composer") => "custom_link", __("No link", "js_composer") => "link_no"), // "description" => __("Link type.", "js_composer") // ), // array( // "type" => "exploded_textarea", // "heading" => __("Custom links", "js_composer"), // "param_name" => "custom_links", // "description" => __('Select "Open custom link" in "Link" parameter and then enter links for each slide here. Divide links with linebreaks (Enter).', 'js_composer') // ), // array( // "type" => "textfield", // "heading" => __("Thumbnail size", "js_composer"), // "param_name" => "thumb_size", // "value" => "", // "description" => __('Enter thumbnail size. Example: thumbnail, medium, large, full or other sizes defined by current theme. Alternatively enter image size in pixels: 200x100 (Width x Height).', "js_composer") // ), // array( // "type" => "posttypes", // "heading" => __("Post types", "js_composer"), // "param_name" => "posttypes", // "description" => __("Select post types to populate posts from.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("Post/Page IDs", "js_composer"), // "param_name" => "posts_in", // "value" => "", // "description" => __('Fill this field with page/posts IDs separated by commas (,), to retrieve only them. Use this in conjunction with "Post types" field.', "js_composer") // ), // array( // "type" => "exploded_textarea", // "heading" => __("Categories", "js_composer"), // "param_name" => "categories", // "description" => __("If you want to narrow output, enter category names here. Note: Only listed categories will be included. Divide categories with linebreaks (Enter).", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Order by", "js_composer"), // "param_name" => "orderby", // "value" => array( "", __("Date", "js_composer") => "date", __("ID", "js_composer") => "ID", __("Author", "js_composer") => "author", __("Title", "js_composer") => "title", __("Modified", "js_composer") => "modified", __("Random", "js_composer") => "rand", __("Comment count", "js_composer") => "comment_count", __("Menu order", "js_composer") => "menu_order" ), // "description" => __('Select how to sort retrieved posts. More at <a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>.', 'js_composer') // ), // array( // "type" => "dropdown", // "heading" => __("Order by", "js_composer"), // "param_name" => "order", // "value" => array( __("Descending", "js_composer") => "DESC", __("Ascending", "js_composer") => "ASC" ), // "description" => __('Designates the ascending or descending order. More at <a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>.', 'js_composer') // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ) //) ); /* Button ---------------------------------------------------------- */ $icons_arr = array( __("None", "js_composer") => "none", __("Address book icon", "js_composer") => "wpb_address_book", __("Alarm clock icon", "js_composer") => "wpb_alarm_clock", __("Anchor icon", "js_composer") => "wpb_anchor", __("Application Image icon", "js_composer") => "wpb_application_image", __("Arrow icon", "js_composer") => "wpb_arrow", __("Asterisk icon", "js_composer") => "wpb_asterisk", __("Hammer icon", "js_composer") => "wpb_hammer", __("Balloon icon", "js_composer") => "wpb_balloon", __("Balloon Buzz icon", "js_composer") => "wpb_balloon_buzz", __("Balloon Facebook icon", "js_composer") => "wpb_balloon_facebook", __("Balloon Twitter icon", "js_composer") => "wpb_balloon_twitter", __("Battery icon", "js_composer") => "wpb_battery", __("Binocular icon", "js_composer") => "wpb_binocular", __("Document Excel icon", "js_composer") => "wpb_document_excel", __("Document Image icon", "js_composer") => "wpb_document_image", __("Document Music icon", "js_composer") => "wpb_document_music", __("Document Office icon", "js_composer") => "wpb_document_office", __("Document PDF icon", "js_composer") => "wpb_document_pdf", __("Document Powerpoint icon", "js_composer") => "wpb_document_powerpoint", __("Document Word icon", "js_composer") => "wpb_document_word", __("Bookmark icon", "js_composer") => "wpb_bookmark", __("Camcorder icon", "js_composer") => "wpb_camcorder", __("Camera icon", "js_composer") => "wpb_camera", __("Chart icon", "js_composer") => "wpb_chart", __("Chart pie icon", "js_composer") => "wpb_chart_pie", __("Clock icon", "js_composer") => "wpb_clock", __("Fire icon", "js_composer") => "wpb_fire", __("Heart icon", "js_composer") => "wpb_heart", __("Mail icon", "js_composer") => "wpb_mail", __("Play icon", "js_composer") => "wpb_play", __("Shield icon", "js_composer") => "wpb_shield", __("Video icon", "js_composer") => "wpb_video" ); //$colors_arr = array(__("Grey", "js_composer") => "button_grey", __("Yellow", "js_composer") => "button_yellow", __("Green", "js_composer") => "button_green", __("Blue", "js_composer") => "button_blue", __("Red", "js_composer") => "button_red", __("Orange", "js_composer") => "button_orange"); $colors_arr = array(__("Accent", "js_composer") => "accent", __("Blue", "js_composer") => "blue", __("Grey", "js_composer") => "grey", __("Light grey", "js_composer") => "lightgrey", __("Purple", "js_composer") => "purple", __("Light Blue", "js_composer") => "lightblue", __("Green", "js_composer") => "green", __("Lime Green", "js_composer") => "limegreen", __("Turquoise", "js_composer") => "turquoise", __("Pink", "js_composer") => "pink", __("Orange", "js_composer") => "orange"); $size_arr = array(__("Normal", "js_composer") => "normal", __("Large", "js_composer") => "large"); $type_arr = array(__("Standard", "js_composer") => "standard", __("Square with arrow", "js_composer") => "squarearrow", __("Slightly rounded", "js_composer") => "slightlyrounded", __("Slightly rounded with arrow", "js_composer") => "slightlyroundedarrow", __("Rounded", "js_composer") => "rounded", __("Rounded with arrow", "js_composer") => "roundedarrow", __("Outer glow effect", "js_composer") => "outerglow", __("Drop shadow effect", "js_composer") => "dropshadow"); $target_arr = array(__("Same window", "js_composer") => "_self", __("New window", "js_composer") => "_blank"); //WPBMap::map( 'vc_button', array( // "name" => __("Button", "js_composer"), // "base" => "vc_button", // "class" => "wpb_vc_button wpb_controls_top_right", // "icon" => "icon-wpb-ui-button", // "controls" => "edit_popup_delete", // "params" => array( // array( // "type" => "textfield", // "heading" => __("Text on the button", "js_composer"), // "holder" => "button", // "class" => "btn", // "param_name" => "title", // "value" => __("Text on the button", "js_composer"), // "description" => __("Text on the button.", "js_composer") // ), // array( // "type" => "textfield", // "heading" => __("URL (Link)", "js_composer"), // "param_name" => "href", // "value" => "", // "description" => __("Button link.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Color", "js_composer"), // "param_name" => "color", // "value" => $colors_arr, // "description" => __("Button color.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Size", "js_composer"), // "param_name" => "size", // "value" => $size_arr, // "description" => __("Button size.", "js_composer") // ), // array( // "type" => "dropdown", // "heading" => __("Type", "js_composer"), // "param_name" => "type", // "value" => $type_arr // ), // array( // "type" => "dropdown", // "heading" => __("Target", "js_composer"), // "param_name" => "target", // "value" => $target_arr // ), // array( // "type" => "textfield", // "heading" => __("Extra class name", "js_composer"), // "param_name" => "el_class", // "value" => "", // "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") // ) // ), // "js_callback" => array("init" => "wpbButtonInitCallBack", "save" => "wpbButtonSaveCallBack") //"js_callback" => array("init" => "wpbCallToActionInitCallBack", "shortcode" => "wpbCallToActionShortcodeCallBack") //) ); WPBMap::map( 'impact_text', array( "name" => __("Impact Text + Button", "js_composer"), "base" => "impact_text", "class" => "button_grey", "icon" => "icon-wpb-impact-text", "controls" => "edit_popup_delete", "params" => array( array( "type" => "dropdown", "heading" => __("Include button", "js_composer"), "param_name" => "include_button", "value" => array(__("Yes", "js_composer") => "yes", __("No", "js_composer") => "no"), "description" => __("Include a button in the asset.", "js_composer") ), array( "type" => "textfield", "heading" => __("Text on the button", "js_composer"), "param_name" => "title", "value" => __("Text on the button", "js_composer"), "description" => __("Text on the button.", "js_composer") ), array( "type" => "textfield", "heading" => __("URL (Link)", "js_composer"), "param_name" => "href", "value" => "", "description" => __("Button link.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Color", "js_composer"), "param_name" => "color", "value" => $colors_arr, "description" => __("Button color.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Size", "js_composer"), "param_name" => "size", "value" => $size_arr, "description" => __("Button size.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Type", "js_composer"), "param_name" => "type", "value" => $type_arr ), array( "type" => "dropdown", "heading" => __("Target", "js_composer"), "param_name" => "target", "value" => $target_arr ), array( "type" => "dropdown", "heading" => __("Button position", "js_composer"), "param_name" => "position", "value" => array(__("Align right", "js_composer") => "cta_align_right", __("Align left", "js_composer") => "cta_align_left", __("Align bottom", "js_composer") => "cta_align_bottom"), "description" => __("Select button alignment.", "js_composer") ), array( "type" => "textarea_html", "holder" => "div", "class" => "", "heading" => __("Text", "js_composer"), "param_name" => "content", "value" => __("click the edit button to change this text.", "js_composer"), "description" => __("Enter your content.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Show alt background", "js_composer"), "param_name" => "alt_background", "value" => array(__("None", "js_composer") => "none", __("Alt 1", "js_composer") => "alt-one", __("Alt 2", "js_composer") => "alt-two", __("Alt 3", "js_composer") => "alt-three", __("Alt 4", "js_composer") => "alt-four", __("Alt 5", "js_composer") => "alt-five", __("Alt 6", "js_composer") => "alt-six", __("Alt 7", "js_composer") => "alt-seven", __("Alt 8", "js_composer") => "alt-eight", __("Alt 9", "js_composer") => "alt-nine", __("Alt 10", "js_composer") => "alt-ten"), "description" => __("Show an alternative background around the asset. These can all be set in Flexform Options > Asset Background Options. NOTE: This is only available on a page with the no sidebar setup.", "js_composer") ), array( "type" => "altbg_preview", "heading" => __("Alt Background Preview", "js_composer"), "param_name" => "altbg_preview", "value" => "", "description" => __("", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ), "js_callback" => array("init" => "wpbCallToActionInitCallBack", "save" => "wpbCallToActionSaveCallBack") ) ); /* Video element ---------------------------------------------------------- */ WPBMap::map( 'vc_video', array( "name" => __("Video player", "js_composer"), "base" => "vc_video", "class" => "", "icon" => "icon-wpb-film-youtube", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "title", "value" => "", "description" => __("Heading text. Leave it empty if not needed.", "js_composer") ), array( "type" => "textfield", "heading" => __("Video link", "js_composer"), "param_name" => "link", "value" => "", "description" => __('Link to the video. More about supported formats at <a href="http://codex.wordpress.org/Embeds#Okay.2C_So_What_Sites_Can_I_Embed_From.3F" target="_blank">WordPress codex page</a>.', "js_composer") ), array( "type" => "textfield", "heading" => __("Video size", "js_composer"), "param_name" => "size", "value" => "", "description" => __('Enter video size in pixels. Example: 200x100 (Width x Height).', "js_composer") ), array( "type" => "dropdown", "heading" => __("Full width", "js_composer"), "param_name" => "full_width", "value" => array(__('No', "js_composer") => "no", __('Yes', "js_composer") => "yes"), "description" => __("Select this if you want the video to be the full width of the page container (leave the above size blank).", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ) ) ); /* Google maps element ---------------------------------------------------------- */ WPBMap::map( 'vc_gmaps', array( "name" => __("Google Map", "js_composer"), "base" => "vc_gmaps", "class" => "", "icon" => "icon-wpb-map-pin", "params" => array( array( "type" => "textfield", "heading" => __("Widget title", "js_composer"), "param_name" => "title", "value" => "", "description" => __("Heading text. Leave it empty if not needed.", "js_composer") ), array( "type" => "textfield", "heading" => __("Address", "js_composer"), "param_name" => "address", "value" => "", "description" => __('Enter the address that you would like to show on the map here, i.e. "Cupertino".', "js_composer") ), array( "type" => "textfield", "heading" => __("Map height", "js_composer"), "param_name" => "size", "value" => "300", "description" => __('Enter map height in pixels. Example: 300).', "js_composer") ), array( "type" => "dropdown", "heading" => __("Map type", "js_composer"), "param_name" => "type", "value" => array(__("Map", "js_composer") => "ROADMAP", __("Satellite", "js_composer") => "SATELLITE", __("Hybrid", "js_composer") => "HYBRID", __("Terrain", "js_composer") => "TERRAIN"), "description" => __("Select button alignment.", "js_composer") ), array( "type" => "dropdown", "heading" => __("Map Zoom", "js_composer"), "param_name" => "zoom", "value" => array(__("14 - Default", "js_composer") => 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20) ), array( "type" => "attach_image", "heading" => __("Custom Map Pin", "js_composer"), "param_name" => "pin_image", "value" => "", "description" => "Choose an image to use as the custom pin for the address on the map. Upload your custom map pin, the image size must be 150px x 75px." ), array( "type" => "dropdown", "heading" => __("Fullscreen Display", "js_composer"), "param_name" => "fullscreen", "value" => array(__("No", "js_composer") => "no", __("Yes", "js_composer") => "yes"), "description" => __("If yes, the map will be displayed from screen edge to edge.", "js_composer") ), array( "type" => "textfield", "heading" => __("Extra class name", "js_composer"), "param_name" => "el_class", "value" => "", "description" => __("If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.", "js_composer") ) ) ) ); WPBMap::map( 'vc_raw_html', array( "name" => __("Raw HTML", "js_composer"), "base" => "vc_raw_html", "class" => "div", "icon" => "icon-wpb-raw-html", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textarea_raw_html", "holder" => "div", "class" => "", "heading" => __("Raw HTML", "js_composer"), "param_name" => "content", "value" => base64_encode("<p>I am raw html block.<br/>click the edit button to change this html</p>"), "description" => __("Enter your HTML content.", "js_composer") ), ) ) ); WPBMap::map( 'vc_raw_js', array( "name" => __("Raw JS", "js_composer"), "base" => "vc_raw_js", "class" => "div", "icon" => "icon-wpb-raw-javascript", "wrapper_class" => "clearfix", "controls" => "full", "params" => array( array( "type" => "textarea_raw_html", "holder" => "div", "class" => "", "heading" => __("Raw js", "js_composer"), "param_name" => "content", "value" => __(base64_encode("alert('Enter your js here!');"), "js_composer"), "description" => __("Enter your Js.", "js_composer") ), ) ) ); WPBMap::layout(array('id'=>'column_12', 'title'=>'1/2')); WPBMap::layout(array('id'=>'column_12-12', 'title'=>'1/2 + 1/2')); WPBMap::layout(array('id'=>'column_13', 'title'=>'1/3')); WPBMap::layout(array('id'=>'column_13-13-13', 'title'=>'1/3 + 1/3 + 1/3')); WPBMap::layout(array('id'=>'column_13-23', 'title'=>'1/3 + 2/3')); WPBMap::layout(array('id'=>'column_23-13', 'title'=>'2/3 + 1/3')); WPBMap::layout(array('id'=>'column_14', 'title'=>'1/4')); WPBMap::layout(array('id'=>'column_12-14-14', 'title'=>'1/2 + 1/4 + 1/4')); WPBMap::layout(array('id'=>'column_14-12-14', 'title'=>'1/4 + 1/2 + 1/4')); WPBMap::layout(array('id'=>'column_14-14-12', 'title'=>'1/4 + 1/4 + 1/2')); WPBMap::layout(array('id'=>'column_14-14-14-14', 'title'=>'1/4 + 1/4 + 1/4 + 1/4')); WPBMap::layout(array('id'=>'column_11', 'title'=>'1/1'));
coogie/incoaching
wp-content/themes/flexform/includes/page-builder/config/map.php
PHP
gpl-2.0
63,839
<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly function mc_select_category($category, $type='event', $group='events' ) { $category = urldecode($category); global $wpdb; $mcdb = $wpdb; if ( get_option( 'mc_remote' ) == 'true' && function_exists('mc_remote_db') ) { $mcdb = mc_remote_db(); } $select_category = ''; $data = ($group=='category')?'category_id':'event_category'; if ( isset( $_GET['mcat'] ) ) { $category = $_GET['mcat']; } if ( preg_match('/^all$|^all,|,all$|,all,/i', $category) > 0 ) { return ''; } else { if ( strpos( $category, "|" ) || strpos( $category, "," ) ) { if ( strpos($category, "|" ) ) { $categories = explode( "|", $category ); } else { $categories = explode( ",", $category ); } $numcat = count($categories); $i = 1; foreach ($categories as $key) { if ( is_numeric($key) ) { $key = (int) $key; if ($i == 1) { $select_category .= ($type=='all')?" WHERE (":' ('; } $select_category .= " $data = $key"; if ($i < $numcat) { $select_category .= " OR "; } else if ($i == $numcat) { $select_category .= ($type=='all')?") ":' ) AND'; } $i++; } else { $key = esc_sql(trim($key)); $cat = $mcdb->get_row("SELECT category_id FROM " . my_calendar_categories_table() . " WHERE category_name = '$key'"); if ( $cat ) { $category_id = $cat->category_id; if ($i == 1) { $select_category .= ($type=='all')?" WHERE (":' ('; } $select_category .= " $data = $category_id"; if ($i < $numcat) { $select_category .= " OR "; } else if ($i == $numcat) { $select_category .= ($type=='all')?") ":' ) AND'; } $i++; } else { return; } } } } else { if ( is_numeric( $category ) ) { $select_category = ($type=='all')?" WHERE $data = $category":" event_category = $category AND"; } else { $cat = $mcdb->get_row("SELECT category_id FROM " . my_calendar_categories_table() . " WHERE category_name = '$category'"); if ( is_object($cat) ) { $category_id = $cat->category_id; $select_category = ($type=='all')?" WHERE $data = $category_id":" $data = $category_id AND"; } else { $select_category = ''; } } } return $select_category; } } function mc_select_author( $author, $type='event' ) { $author = urldecode($author); $key = ''; if ( $author == '' || $author == 'all' || $author == 'default' || $author == null ) { return; } global $wpdb; $mcdb = $wpdb; if ( get_option( 'mc_remote' ) == 'true' && function_exists('mc_remote_db') ) { $mcdb = mc_remote_db(); } $select_author = ''; $data = 'event_author'; if ( isset( $_GET['mc_auth'] ) ) { $author = $_GET['mc_auth']; } if ( preg_match( '/^all$|^all,|,all$|,all,/i', $author ) > 0 ) { return ''; } else { if ( strpos( $author, "|" ) || strpos( $author, "," ) ) { if ( strpos($author, "|" ) ) { $authors = explode( "|", $author ); } else { $authors = explode( ",", $author ); } $numauth = count($authors); $i = 1; foreach ($authors as $key) { if ( is_numeric($key) ) { $key = (int) $key; if ($i == 1) { $select_author .= ($type=='all')?" WHERE (":' ('; } $select_author .= " $data = $key"; if ($i < $numauth) { $select_author .= " OR "; } else if ($i == $numauth) { $select_author .= ($type=='all')?") ":' ) AND'; } $i++; } else { $key = esc_sql(trim($key)); $author = get_user_by( 'login', $key ); // get author by username $author_id = $author->ID; if ($i == 1) { $select_author .= ($type=='all')?" WHERE (":' ('; } $select_author .= " $data = $author_id"; if ($i < $numauth) { $select_author .= " OR "; } else if ($i == $numauth) { $select_author .= ($type=='all')?") ":' ) AND'; } $i++; } } } else { if ( is_numeric( $author ) ) { $select_author = ($type=='all')?" WHERE $data = $author":" event_author = $author AND"; } else { $author = esc_sql(trim($author)); $author = get_user_by( 'login', $author ); // get author by username if ( is_object($author) ) { $author_id = $author->ID; $select_author = ($type=='all')?" WHERE $data = $author_id":" $data = $author_id AND"; } else { $select_author = ''; } } } return $select_author; } } function mc_select_host( $host, $type='event' ) { $host = urldecode($host); $key = ''; if ( $host == '' || $host == 'all' || $host == 'default' || $host == null ) { return; } global $wpdb; $mcdb = $wpdb; if ( get_option( 'mc_remote' ) == 'true' && function_exists('mc_remote_db') ) { $mcdb = mc_remote_db(); } $select_author = ''; $data = 'event_host'; if ( isset( $_GET['mc_auth'] ) ) { $host = $_GET['mc_host']; } if ( preg_match( '/^all$|^all,|,all$|,all,/i', $host ) > 0 ) { return ''; } else { if ( strpos( $host, "|" ) || strpos( $host, "," ) ) { if ( strpos($host, "|" ) ) { $hosts = explode( "|", $host ); } else { $hosts = explode( ",", $host ); } $numhost = count($hosts); $i = 1; foreach ($hosts as $key) { if ( is_numeric($key) ) { $key = (int) $key; if ($i == 1) { $select_host .= ($type=='all')?" WHERE (":' ('; } $select_host .= " $data = $key"; if ($i < $numhost) { $select_host .= " OR "; } else if ($i == $numhost) { $select_host .= ($type=='all')?") ":' ) AND'; } $i++; } else { $key = esc_sql(trim($key)); $host = get_user_by( 'login', $key ); // get host by username $host_id = $host->ID; if ($i == 1) { $select_host .= ($type=='all')?" WHERE (":' ('; } $select_host .= " $data = $host_id"; if ($i < $numhost) { $select_host .= " OR "; } else if ($i == $numhost) { $select_host .= ($type=='all')?") ":' ) AND'; } $i++; } } } else { if ( is_numeric( $host ) ) { $select_host = ($type=='all')?" WHERE $data = $host":" event_host = $host AND"; } else { $host = esc_sql(trim($host)); $host = get_user_by( 'login', $host ); // get author by username if ( is_object($host) ) { $host_id = $host->ID; $select_host = ($type=='all')?" WHERE $data = $host_id":" $data = $host_id AND"; } else { $select_host = ''; } } } return $select_host; } } function mc_limit_string($type='',$ltype='',$lvalue='') { global $user_ID; $user_settings = get_option('mc_user_settings'); $limit_string = ""; if ( ( get_option('mc_user_settings_enabled') == 'true' && isset( $user_settings['my_calendar_location_default']['enabled'] ) && $user_settings['my_calendar_location_default']['enabled'] == 'on' ) || isset($_GET['loc']) && isset($_GET['ltype']) || ( $ltype !='' && $lvalue != '' ) ) { if ( !isset($_GET['loc']) && !isset($_GET['ltype']) ) { if ( $ltype == '' && $lvalue == '' ) { if ( is_user_logged_in() ) { get_currentuserinfo(); $current_settings = get_user_meta( $user_ID, 'my_calendar_user_settings' ); $current_location = $current_settings['my_calendar_location_default']; $location = get_option('mc_location_type'); } } else if ( $ltype !='' && $lvalue != '' ) { $location = $ltype; $current_location = esc_sql( $lvalue ); } } else { $current_location = urldecode($_GET['loc']); $location = urldecode($_GET['ltype']); } switch ($location) { case "name":$location_type = "event_label"; break; case "city":$location_type = "event_city"; break; case "state":$location_type = "event_state"; break; case "zip":$location_type = "event_postcode"; break; case "country":$location_type = "event_country"; break; case "region":$location_type = "event_region"; break; default:$location_type = $location; break; } if ($current_location != 'all' && $current_location != '') { $limit_string = "$location_type='$current_location' AND"; //$limit_string .= ($type=='all')?' AND':""; } } if ( $limit_string != '' ) { if ( isset($_GET['loc2']) && isset($_GET['ltype2']) ) { $limit_string .= mc_secondary_limit( $_GET['ltype2'],$_GET['loc2'] ); } } return $limit_string; } // set up a secondary limit on location function mc_secondary_limit($ltype='',$lvalue='') { $limit_string = ""; $current_location = urldecode( $lvalue ); $location = urldecode( $ltype ); switch ($location) { case "name":$location_type = "event_label"; break; case "city":$location_type = "event_city"; break; case "state":$location_type = "event_state"; break; case "zip":$location_type = "event_postcode"; break; case "country":$location_type = "event_country"; break; case "region":$location_type = "event_region"; break; default:$location_type = "event_label"; break; } if ($current_location != 'all' && $current_location != '') { $limit_string = " $location_type='$current_location' AND "; //$limit_string .= ($type=='all')?' AND':""; } return $limit_string; }
swolverton/WEStoryEngine
wp-content/plugins/my-calendar/my-calendar-limits.php
PHP
gpl-2.0
8,900
/* break-align-interface.cc -- implement Break_alignment_interface source file of the GNU LilyPond music typesetter (c) 1997--2007 Han-Wen Nienhuys <hanwen@xs4all.nl> */ #include "break-align-interface.hh" #include "align-interface.hh" #include "axis-group-interface.hh" #include "dimensions.hh" #include "international.hh" #include "output-def.hh" #include "paper-column.hh" #include "pointer-group-interface.hh" #include "self-alignment-interface.hh" #include "side-position-interface.hh" #include "warn.hh" /* This is tricky: we cannot modify 'elements, since callers are iterating the same list. Reordering the list in-place, or resetting 'elements will skip elements in the loops of callers. So we return the correct order as an array. */ SCM Break_alignment_interface::break_align_order (Item *me) { SCM order_vec = me->get_property ("break-align-orders"); if (!scm_is_vector (order_vec) || scm_c_vector_length (order_vec) < 3) return SCM_BOOL_F; SCM order = scm_vector_ref (order_vec, scm_from_int (me->break_status_dir () + 1)); return order; } vector<Grob*> Break_alignment_interface::ordered_elements (Grob *grob) { Item *me = dynamic_cast<Item *> (grob); extract_grob_set (me, "elements", elts); SCM order = break_align_order (me); if (order == SCM_BOOL_F) return elts; vector<Grob*> writable_elts (elts); /* Copy in order specified in BREAK-ALIGN-ORDER. */ vector<Grob*> new_elts; for (; scm_is_pair (order); order = scm_cdr (order)) { SCM sym = scm_car (order); for (vsize i = writable_elts.size (); i--;) { Grob *g = writable_elts[i]; if (g && sym == g->get_property ("break-align-symbol")) { new_elts.push_back (g); writable_elts.erase (writable_elts.begin () + i); } } } return new_elts; } void Break_alignment_interface::add_element (Grob *me, Grob *toadd) { Align_interface::add_element (me, toadd); } MAKE_SCHEME_CALLBACK (Break_alignment_interface, calc_positioning_done, 1) SCM Break_alignment_interface::calc_positioning_done (SCM smob) { Grob *grob = unsmob_grob (smob); Item *me = dynamic_cast<Item *> (grob); me->set_property ("positioning-done", SCM_BOOL_T); vector<Grob*> elems = ordered_elements (me); vector<Interval> extents; int last_nonempty = -1; for (vsize i = 0; i < elems.size (); i++) { Interval y = elems[i]->extent (elems[i], X_AXIS); extents.push_back (y); if (!y.is_empty ()) last_nonempty = i; } vsize idx = 0; while (idx < extents.size () && extents[idx].is_empty ()) idx++; vector<Real> offsets; offsets.resize (elems.size ()); for (vsize i = 0; i < offsets.size ();i++) offsets[i] = 0.0; Real extra_right_space = 0.0; vsize edge_idx = VPOS; while (idx < elems.size ()) { vsize next_idx = idx + 1; while (next_idx < elems.size () && extents[next_idx].is_empty ()) next_idx++; Grob *l = elems[idx]; Grob *r = 0; if (next_idx < elems.size ()) r = elems[next_idx]; SCM alist = SCM_EOL; /* Find the first grob with a space-alist entry. */ extract_grob_set (l, "elements", elts); for (vsize i = elts.size (); i--;) { Grob *elt = elts[i]; if (edge_idx == VPOS && (elt->get_property ("break-align-symbol") == ly_symbol2scm ("left-edge"))) edge_idx = idx; SCM l = elt->get_property ("space-alist"); if (scm_is_pair (l)) { alist = l; break; } } SCM rsym = r ? SCM_EOL : ly_symbol2scm ("right-edge"); /* We used to use #'cause to find out the symbol and the spacing table, but that gets icky when that grob is suicided for some reason. */ if (r) { extract_grob_set (r, "elements", elts); for (vsize i = elts.size (); !scm_is_symbol (rsym) && i--;) { Grob *elt = elts[i]; rsym = elt->get_property ("break-align-symbol"); } } if (rsym == ly_symbol2scm ("left-edge")) edge_idx = next_idx; SCM entry = SCM_EOL; if (scm_is_symbol (rsym)) entry = scm_assq (rsym, alist); bool entry_found = scm_is_pair (entry); if (!entry_found) { string sym_string; if (scm_is_symbol (rsym)) sym_string = ly_symbol2string (rsym); string orig_string; if (unsmob_grob (l->get_property ("cause"))) orig_string = unsmob_grob (l->get_property ("cause"))->name (); programming_error (_f ("No spacing entry from %s to `%s'", orig_string.c_str (), sym_string.c_str ())); } Real distance = 1.0; SCM type = ly_symbol2scm ("extra-space"); if (entry_found) { entry = scm_cdr (entry); distance = scm_to_double (scm_cdr (entry)); type = scm_car (entry); } if (r) { if (type == ly_symbol2scm ("extra-space")) offsets[next_idx] = extents[idx][RIGHT] + distance - extents[next_idx][LEFT]; /* should probably junk minimum-space */ else if (type == ly_symbol2scm ("minimum-space")) offsets[next_idx] = max (extents[idx][RIGHT], distance); } else { extra_right_space = distance; if (idx + 1 < offsets.size ()) offsets[idx+1] = extents[idx][RIGHT] + distance; } idx = next_idx; } Real here = 0.0; Interval total_extent; Real alignment_off = 0.0; for (vsize i = 0; i < offsets.size (); i++) { here += offsets[i]; if (i == edge_idx) alignment_off = -here; total_extent.unite (extents[i] + here); } if (total_extent.is_empty ()) return SCM_BOOL_T; if (me->break_status_dir () == LEFT) alignment_off = -total_extent[RIGHT] - extra_right_space; else if (edge_idx == VPOS) alignment_off = -total_extent[LEFT]; here = alignment_off; for (vsize i = 0; i < offsets.size (); i++) { here += offsets[i]; elems[i]->translate_axis (here, X_AXIS); } return SCM_BOOL_T; } MAKE_SCHEME_CALLBACK (Break_alignable_interface, self_align_callback, 1) SCM Break_alignable_interface::self_align_callback (SCM grob) { Grob *me = unsmob_grob (grob); Item *alignment = dynamic_cast<Item*> (me->get_parent (X_AXIS)); if (!Break_alignment_interface::has_interface (alignment)) return scm_from_int (0); SCM symbol_list = me->get_property ("break-align-symbols"); vector<Grob*> elements = Break_alignment_interface::ordered_elements (alignment); if (elements.size () == 0) return scm_from_int (0); int break_aligned_grob = -1; for (; scm_is_pair (symbol_list); symbol_list = scm_cdr (symbol_list)) { SCM sym = scm_car (symbol_list); for (vsize i = 0; i < elements.size (); i++) { if (elements[i]->get_property ("break-align-symbol") == sym) { if (Item::break_visible (elements[i]) && !elements[i]->extent (elements[i], X_AXIS).is_empty ()) { break_aligned_grob = i; goto found_break_aligned_grob; /* ugh. need to break out of 2 loops */ } else if (break_aligned_grob == -1) break_aligned_grob = i; } } } found_break_aligned_grob: if (break_aligned_grob == -1) return scm_from_int (0); Grob *alignment_parent = elements[break_aligned_grob]; Grob *common = me->common_refpoint (alignment_parent, X_AXIS); Real anchor = robust_scm2double (alignment_parent->get_property ("break-align-anchor"), 0); return scm_from_double (alignment_parent->relative_coordinate (common, X_AXIS) - me->relative_coordinate (common, X_AXIS) + anchor); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_average_anchor, 1) SCM Break_aligned_interface::calc_average_anchor (SCM grob) { Grob *me = unsmob_grob (grob); Real avg = 0.0; int count = 0; /* average the anchors of those children that have it set */ extract_grob_set (me, "elements", elts); for (vsize i = 0; i < elts.size (); i++) { SCM anchor = elts[i]->get_property ("break-align-anchor"); if (scm_is_number (anchor)) { count++; avg += scm_to_double (anchor); } } return scm_from_double (count > 0 ? avg / count : 0); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_extent_aligned_anchor, 1) SCM Break_aligned_interface::calc_extent_aligned_anchor (SCM smob) { Grob *me = unsmob_grob (smob); Real alignment = robust_scm2double (me->get_property ("break-align-anchor-alignment"), 0.0); Interval iv = me->extent (me, X_AXIS); if (isinf (iv[LEFT]) && isinf (iv[RIGHT])) /* avoid NaN */ return scm_from_double (0.0); return scm_from_double (iv.linear_combination (alignment)); } MAKE_SCHEME_CALLBACK (Break_aligned_interface, calc_break_visibility, 1) SCM Break_aligned_interface::calc_break_visibility (SCM smob) { /* a BreakAlignGroup is break-visible iff it has one element that is break-visible */ Grob *me = unsmob_grob (smob); SCM ret = scm_c_make_vector (3, SCM_EOL); extract_grob_set (me, "elements", elts); for (int dir = 0; dir <= 2; dir++) { bool visible = false; for (vsize i = 0; i < elts.size (); i++) { SCM vis = elts[i]->get_property ("break-visibility"); if (scm_is_vector (vis) && to_boolean (scm_c_vector_ref (vis, dir))) visible = true; } scm_c_vector_set_x (ret, dir, scm_from_bool (visible)); } return ret; } ADD_INTERFACE (Break_alignable_interface, "Object that is aligned on a break aligment.", /* properties */ "break-align-symbols " ); ADD_INTERFACE (Break_aligned_interface, "Items that are aligned in prefatory matter.\n" "\n" "The spacing of these items is controlled by the" " @code{space-alist} property. It contains a list" " @code{break-align-symbol}s with a specification of the" " associated space. The space specification can be\n" "\n" "@table @code\n" "@item (minimum-space . @var{spc}))\n" "Pad space until the distance is @var{spc}.\n" "@item (fixed-space . @var{spc})\n" "Set a fixed space.\n" "@item (semi-fixed-space . @var{spc})\n" "Set a space. Half of it is fixed and half is stretchable." " (does not work at start of line. fixme)\n" "@item (extra-space . @var{spc})\n" "Add @var{spc} amount of space.\n" "@end table\n" "\n" "Special keys for the alist are @code{first-note} and" " @code{next-note}, signifying the first note on a line, and" " the next note halfway a line.\n" "\n" "Rules for this spacing are much more complicated than this." " See [Wanske] page 126--134, [Ross] page 143--147.", /* properties */ "break-align-anchor " "break-align-anchor-alignment " "break-align-symbol " "space-alist " ); ADD_INTERFACE (Break_alignment_interface, "The object that performs break aligment. See" " @ref{break-aligned-interface}.", /* properties */ "positioning-done " "break-align-orders " );
drewm1980/lilypond-an
lily/break-alignment-interface.cc
C++
gpl-2.0
11,006
<?php namespace App\Model; abstract class Model { /** * Database connection * @var \DBConnection */ protected $db; /** * Table name * @var string */ protected $table; /** * ID field * @var string */ protected $idField = 'id'; public function __construct(\DBConnection $connection) { $this->db = $connection; } /** * Returns key/value list * @param string $key key field * @param string $value value field * @param string $where where constraint * @return array */ public function getList($key, $value, $where = null) { $query = "SELECT {$key}, {$value} FROM {$this->table}"; if (!empty($where)) { $query .= " WHERE $where"; } $res = $this->db->rq($query); $list = array(); while (($row = $this->db->fetch($res)) !== false) { $list[$row[$key]] = $row[$value]; } return $list; } /** * Returns list of field names * @param string $query * @return array */ public function getColumns($query) { $res = $this->db->rq($query); $list = array(); while (($row = mysql_fetch_field($res)) !== false) { $list[]= $row->name; } return $list; } /** * Returns record based on id * @param int $id * @return array */ public function getRecord($id) { $query = "SELECT * FROM {$this->table} WHERE {$this->idField} = {$this->db->string_escape($id)}"; $res = $this->db->rq($query); return $this->db->fetch($res); } /** * Returns list of records * @param string $where * @return array */ public function getRecords($where = null) { $query = "SELECT * FROM {$this->table}"; if (!empty($where)) { $query .= " WHERE $where"; } $res = $this->db->rq($query); $result = array(); if ($this->db->num_rows($res)) { while(false !== ($row = $this->db->fetch($res))) { $result[] = $row; } } return $result; } /** * Updates record * @param int $id * @param array $data * @return boolean */ public function update($id, $data) { $query = "UPDATE {$this->table} SET "; foreach ($data as $name => $value) { $query .= "$name = '{$this->db->string_escape($value)}', "; } $query = rtrim($query, ', '); $query .= " WHERE {$this->idField} = {$this->db->string_escape($id)}"; $this->db->rq($query); return $this->db->affected_rows() > 0; } /** * Adds record to the database * @param array $data * @return integer */ public function insert($data = array()) { $query = "INSERT INTO {$this->table} ("; $query .= implode(', ', array_keys($data)); $query .= ') VALUES ('; foreach ($data as $key => $value) { $query .= "'{$this->db->string_escape($value)}', "; } $query = rtrim($query, ', '); $query .= ')'; $this->db->rq($query); return $this->db->last_id(); } /** * Deletes record * @param int|array $where * @return boolean */ public function delete($where) { if (is_numeric($where)) { $where = array( $this->idField => $where ); } $query = "DELETE FROM {$this->table} WHERE "; foreach ($where as $name => $value) { $query .= "$name = '{$this->db->string_escape($value)}' AND "; } $query = rtrim($query, ' AND '); $this->db->rq($query); return $this->db->affected_rows() > 0; } }
sahartak/v1poject
src/App/Model/Model.php
PHP
gpl-2.0
4,053
# # $Id: authority_record_display.rb 324 2009-03-06 04:26:22Z nicb $ # # # display collection of authority records # # require File.dirname(__FILE__) + '/authority_record_collection' module DocumentParts module AuthorityRecordDisplay def authority_record_collection collection = [ AuthorityRecordCollection::PersonName.new(1, self), AuthorityRecordCollection::CollectiveName.new(2, self), AuthorityRecordCollection::SiteName.new(3, self), AuthorityRecordCollection::ScoreTitle.new(4, self), ] return collection end end end
nicb/fishrdb
app/models/document/authority_record_display.rb
Ruby
gpl-2.0
583
// CS8037: `S.S(long)': Instance constructor of type with primary constructor must specify `this' constructor initializer // Line: 6 // Compiler options: -langversion:experimental class S (int arg) { public S (long l) { } }
hardvain/mono-compiler
errors/cs8037.cs
C#
gpl-2.0
228
<?php /** * The template for displaying product category thumbnails within loops. * * Override this template by copying it to yourtheme/woocommerce/content-product_cat.php * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce_loop; // Store loop count we're currently on if ( empty( $woocommerce_loop['loop'] ) ) $woocommerce_loop['loop'] = 0; // Store column count for displaying the grid if ( empty( $woocommerce_loop['columns'] ) ) $woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 4 ); // Increase loop count $woocommerce_loop['loop']++; ?> <div class="product-category tile product"> <div class="tile-block clearfix"> <?php do_action( 'woocommerce_before_subcategory', $category ); ?> <div class="product-image-container"> <div class="product-image overlay"> <a href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>"> <?php /** * woocommerce_before_subcategory_title hook * * @hooked woocommerce_subcategory_thumbnail - 10 */ do_action( 'woocommerce_before_subcategory_title', $category ); ?> <span class="overlay-block"> <span class="overlay-icon"></span> </span> </a> </div> </div> <h3> <a href="<?php echo get_term_link( $category->slug, 'product_cat' ); ?>" class="underline no-bg"> <?php echo $category->name; if ( $category->count > 0 ) echo apply_filters( 'woocommerce_subcategory_count_html', ' <mark class="count">(' . $category->count . ')</mark>', $category ); ?> </a> </h3> <?php /** * woocommerce_after_subcategory_title hook */ do_action( 'woocommerce_after_subcategory_title', $category ); ?> <?php do_action( 'woocommerce_after_subcategory', $category ); ?> </div> </div>
eddiewangmw/cff
wp-content/themes/metric/woocommerce/content-product_cat.php
PHP
gpl-2.0
2,502
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['admindirname'] = 'Yönetici Dizini'; $string['availablelangs'] = 'Kullanılabilir diller'; $string['chooselanguagehead'] = 'Bir dil seçin'; $string['chooselanguagesub'] = 'Lütfen, SADECE kurulum için bir dil seçin. Site ve kullanıcı dillerini sonraki ekranda seçebilirsiniz.'; $string['clialreadyconfigured'] = 'config.php halihazırda mevcut, lütfen eğer bu siteyi yüklemek istiyorsanız şu dizini kullanın: admin/cli/install_database.php'; $string['clialreadyinstalled'] = 'Config.php zaten var. Sitenizi güncellemek istiyorsanız bu adresi kullanın: admin/cli/upgrade.php'; $string['cliinstallheader'] = 'Moodle {$a} komut satırı kurulum programı'; $string['databasehost'] = 'Veritabanı sunucusu'; $string['databasename'] = 'Veritabanı adı'; $string['databasetypehead'] = 'Veritabanı sürücünü seçin'; $string['dataroot'] = 'Veri Dizini'; $string['datarootpermission'] = 'Veri dizinleri izni'; $string['dbprefix'] = 'Tablo öneki'; $string['dirroot'] = 'Moodle Dizini'; $string['environmenthead'] = 'Ortam kontrol ediliyor...'; $string['environmentsub2'] = 'Her Moodle dağıtımı, bazı PHP versiyon gereksinimi ve bir takım PHP uzantılarının yüklü olmalı zorunluluğuna sahiptir. Tüm ortam denetimi her yükleme ve güncellemeden önce yapılmalıdır. Eğer PHP \'nin yeni versiyonunu veya PHP uzantılarını nasıl yükleyeceğinizi bilmiyorsanız lütfen sunucu yöneticiniz ile iletişime geçiniz.'; $string['errorsinenvironment'] = 'Ortam kontrolu başarısız oldu!'; $string['installation'] = 'Kurulum'; $string['langdownloaderror'] = 'Maalesef "{$a}" dil paketi kurulamadı. Kuruluma İngilizce olarak devam edilecek.'; $string['memorylimithelp'] = '<p>Sunucunuz için PHP bellek limiti şu anda {$a} olarak ayarlanmış durumda.</p> <p>Özellikle bir çok modülü etkinleştirilmiş ve/veya çok fazla kullanıcınız varsa bu durum daha sonra bazı bellek sorunlarına sebep olabilir.</p> <p>Mümkünse size PHP\'e daha yüksek limitli bir bellek ayarı yapmanızı, örneğin, 40M, öneriyoruz. İşte bunu yapabilmeniz için size bir kaç yol:</p> <ol> <li>Bunu yapmaya yetkiliyseniz, PHP\'yi <i>--enable-memory-limit</i> ile yeniden derleyin. Bu, Moodle\'nın kendi kendine bellek limitini ayarlasına izin verecek.</li> <li>php.ini dosyasına erişim hakkınız varsa, <b>memory_limit</b> ayarını 40M gibi bir ayarla değiştirin. Erişim hakkınız yoksa, bunu sistem yöneticinizden sizin için yapmasını isteyin.</li> <li>Bazı PHP sunucularında Moodle klasörü içinde şu ayarı içeren bir .htaccess dosyası oluşturabilirsiniz: <p><blockquote>php_value memory_limit 40M</blockquote></p> <p>Ancak, bazı sunucularda bu durum çalışan <b>bütün</b> PHP sayfalarını engelleyecektir. (sayfanız altına baktığınızda bazı hatalar göreceksiniz) Böyle bir durumda .htaccess dosyasını silmeniz gerekiyor.</p></li> </ol>'; $string['paths'] = 'Yollar'; $string['pathserrcreatedataroot'] = 'Veri Klasörü ({$a->dataroot}) kurulum tarafından oluşturulamıyor.'; $string['pathshead'] = 'Yolları doğrulayın'; $string['pathsrodataroot'] = 'Veri yolu yazılabilir değil.'; $string['pathsroparentdataroot'] = 'Ana klasör ({$a->parent}) yazılabilir değil. Veri Klasörü ({$a->dataroot}) kurulum tarafından oluşturulamıyor.'; $string['pathssubadmindir'] = 'Pek az web sunucusu /admin adresini kontrol paneline yada benzeri birşeye erişmek için kullanır. Ne yazık ki bu Moodle admin sayfalarının standart konumuyla bir karışıklık yaratır. Bu durumu düzeltmek için kurulumunuzdaki admin dizinini yeniden isimlendirip buraya yeni ismi yazınız. Örneğin: <em>moodleadmin</em>. Bu Moodle\'daki admin bağlantısını düzeltecektir.'; $string['pathssubdataroot'] = 'Moodle\'ın yüklenen dosyaları kayıt etmesi için bir yere ihtiyacınız var. Bu dizin/klasör web sunucusunun kullanıcı hesabı tarafından okunabilir ve yazılabilir olmalıdır. Bu okuma, yazma izinlerini klasöre vermelisiniz. Fakat bu klasör aynı zamanda web üzerinden direk erişilebilir olmamalıdır. Yükleyici eğer klasör yok ise oluşturmayı deneyecektir.'; $string['pathssubdirroot'] = 'Moodle kurulumu için tam klasör yolu. Sadece sembolik linkleri kullanmaya gereksinim duyuyorsanız değiştirin.'; $string['pathssubwwwroot'] = 'Moodle\'a erişlecek tam web adresi. Moodle\'ın birden çok adres kullanması mümkün değildir. Eğer siteniz birden fazla adrese sahip ise bu adres harici diğerlerinin yönlendirme ayarlarını yapılandırın. Eğer siteniz Intranet ve İnternet üzerinden erişilebilirse burada genel bir adres kullanın ve DNS\'iniz ayarlayın. Bu şekilde Intranet kullanıcları da genel adresi kullanabilirler. Eğer adres doğru değilse lütfen kurulumu tekrar başlatmak için tarayıcınızdaki URL\'i değiştirin.'; $string['pathsunsecuredataroot'] = 'Veri yolu güvenli değil'; $string['pathswrongadmindir'] = 'Yönetici klasörü yok'; $string['phpextension'] = '{$a} PHP eklentisi'; $string['phpversion'] = 'PHP sürümü'; $string['phpversionhelp'] = '<p>Moodle, PHP sürümünün en az 4.3.0 veya 5.1.0 olmasını gerektirir (5.0.x sürümünde çok fazla hata var).</p> <p>Şu anda çalışan sürüm: {$a}</p> <p>PHP\'yi güncellemeli veya PHP\'nin yeni sürümünü kullananan bir hostinge taşınmalısınız!</p>'; $string['welcomep10'] = '{$a->installername} ({$a->installerversion})'; $string['welcomep20'] = 'Bilgisayarınıza <strong>{$a->packname} {$a->packversion}</strong> paketini başarıyla kurdunuz. Tebrikler!'; $string['welcomep30'] = '<strong>{$a->installername}</strong>\'nin bu sürümü <strong>Moodle</strong>\'da bir ortam oluşturmak için uygulamaları içerir:'; $string['welcomep40'] = 'Bu paket <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong> sürümünü de içerir.'; $string['welcomep50'] = 'Bu paketteki tüm uygulamaların kullanımı her biri kendine ait olan lisanslar tarafından yönetilir. <strong>{$a->installername}</strong> paketinin tamamı <a href="http://www.opensource.org/docs/definition_plain.html">açık kaynak</a> kodludur ve <a href="http://www.gnu.org/copyleft/gpl.html">GPL</a> lisansı altında dağıtılır.'; $string['welcomep60'] = 'Aşağıdaki sayfalar <strong>Moodle</strong>ın kurulumu ve yapılandırılması için size basitçe yol gösterecektir. Varsayılan ayarları kabul edebilir veya ihtiyaçlarınıza göre bunları değiştirebilirsiniz.'; $string['welcomep70'] = '<strong>Moodle</strong> kurulumu için aşağıdaki "İleri" tuşuna basın.'; $string['wwwroot'] = 'Web adresi';
nasebanal/nb-moodle
chef-repo/site-cookbooks/moodle/files/default/moodle/install/lang/tr/install.php
PHP
gpl-2.0
7,837
<?php /* @var $this UserController */ /* @var $model User */ /* @var $form CActiveForm */ ?> <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'user-form', // Please note: When you enable ajax validation, make sure the corresponding // controller action is handling ajax validation correctly. // There is a call to performAjaxValidation() commented in generated controller code. // See class documentation of CActiveForm for details on this. 'enableAjaxValidation'=>false, )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model,'username'); ?> <?php echo $form->textField($model,'username',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'username'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'email'); ?> <?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'email'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'passwd'); ?> <?php echo $form->passwordField($model,'passwd',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'passwd'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'salt'); ?> <?php echo $form->textField($model,'salt',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'salt'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'openid'); ?> <?php echo $form->textField($model,'openid',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'openid'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'agent'); ?> <?php echo $form->textField($model,'agent'); ?> <?php echo $form->error($model,'agent'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'denezhka_id'); ?> <?php echo $form->textField($model,'denezhka_id'); ?> <?php echo $form->error($model,'denezhka_id'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'state'); ?> <?php echo $form->textField($model,'state'); ?> <?php echo $form->error($model,'state'); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?> </div> <?php $this->endWidget(); ?> </div><!-- form -->
Calc86/clsupport
protected/views/user/_form.php
PHP
gpl-2.0
2,390
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.glass.events; import java.lang.annotation.Native; public class MouseEvent { //mymod @Native final static public int BUTTON_NONE = 211; @Native final static public int BUTTON_LEFT = 212; @Native final static public int BUTTON_RIGHT = 213; @Native final static public int BUTTON_OTHER = 214; @Native final static public int DOWN = 221; @Native final static public int UP = 222; @Native final static public int DRAG = 223; @Native final static public int MOVE = 224; @Native final static public int ENTER = 225; @Native final static public int EXIT = 226; @Native final static public int CLICK = 227; // synthetic /** * Artificial WHEEL event type. * This kind of mouse event is NEVER sent to an app. * The app must listen to Scroll events instead. * This identifier is required for internal purposes. */ @Native final static public int WHEEL = 228; }
lostdj/Jaklin-OpenJFX
modules/graphics/src/main/java/com/sun/glass/events/MouseEvent.java
Java
gpl-2.0
2,312
<?php /** * The Header for our theme. * * Displays all of the <head> section and everything up till <div id="main"> * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?><!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page" class="hfeed site"> <header id="masthead" class="site-header" role="banner"> <hgroup> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2> </hgroup> <nav id="site-navigation" class="main-navigation" role="navigation"> <h3 class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></h3> <a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?>"><?php _e( 'Skip to content', 'twentytwelve' ); ?></a> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?> </nav><!-- #site-navigation --> <?php /* if ( function_exists( 'useful_banner_manager_banners' ) ) { useful_banner_manager_banners( '1', 1 ); } //,2,4*/ if ( function_exists( 'useful_banner_manager_banners_rotation' ) ) { useful_banner_manager_banners_rotation( '1,2,4', 1, 468, 120, 'rand' ); } $header_image = get_header_image(); if ( ! empty( $header_image ) ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $header_image ); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a> <?php endif; ?> </header><!-- #masthead --> <div id="main" class="wrapper">
nayanjogi/sbi
wp-content/themes/twentytwelve/header_new.php
PHP
gpl-2.0
2,613
<?php /** * You are allowed to use this API in your web application. * * Copyright (C) 2013 by customweb GmbH * * This program is licenced under the customweb software licence. With the * purchase or the installation of the software in your application you * accept the licence agreement. The allowed usage is outlined in the * customweb software licence which can be found under * http://www.customweb.ch/en/software-license-agreement * * Any modification or distribution is strictly forbidden. The license * grants you the installation in one application. For multiuse you will need * to purchase further licences at http://www.customweb.com/shop. * * See the customweb software licence agreement for more details. * */ require_once 'Customweb/Core/Charset/TableBasedCharset.php'; class Customweb_Core_Charset_WINDOWS860 extends Customweb_Core_Charset_TableBasedCharset{ private static $conversionTable = array( "\x80" => "\xc3\x87", "\x81" => "\xc3\xbc", "\x82" => "\xc3\xa9", "\x83" => "\xc3\xa2", "\x84" => "\xc3\xa3", "\x85" => "\xc3\xa0", "\x86" => "\xc3\x81", "\x87" => "\xc3\xa7", "\x88" => "\xc3\xaa", "\x89" => "\xc3\x8a", "\x8a" => "\xc3\xa8", "\x8b" => "\xc3\x8d", "\x8c" => "\xc3\x94", "\x8d" => "\xc3\xac", "\x8e" => "\xc3\x83", "\x8f" => "\xc3\x82", "\x90" => "\xc3\x89", "\x91" => "\xc3\x80", "\x92" => "\xc3\x88", "\x93" => "\xc3\xb4", "\x94" => "\xc3\xb5", "\x95" => "\xc3\xb2", "\x96" => "\xc3\x9a", "\x97" => "\xc3\xb9", "\x98" => "\xc3\x8c", "\x99" => "\xc3\x95", "\x9a" => "\xc3\x9c", "\x9b" => "\xc2\xa2", "\x9c" => "\xc2\xa3", "\x9d" => "\xc3\x99", "\x9e" => "\xe2\x82\xa7", "\x9f" => "\xc3\x93", "\xa0" => "\xc3\xa1", "\xa1" => "\xc3\xad", "\xa2" => "\xc3\xb3", "\xa3" => "\xc3\xba", "\xa4" => "\xc3\xb1", "\xa5" => "\xc3\x91", "\xa6" => "\xc2\xaa", "\xa7" => "\xc2\xba", "\xa8" => "\xc2\xbf", "\xa9" => "\xc3\x92", "\xaa" => "\xc2\xac", "\xab" => "\xc2\xbd", "\xac" => "\xc2\xbc", "\xad" => "\xc2\xa1", "\xae" => "\xc2\xab", "\xaf" => "\xc2\xbb", "\xb0" => "\xe2\x96\x91", "\xb1" => "\xe2\x96\x92", "\xb2" => "\xe2\x96\x93", "\xb3" => "\xe2\x94\x82", "\xb4" => "\xe2\x94\xa4", "\xb5" => "\xe2\x95\xa1", "\xb6" => "\xe2\x95\xa2", "\xb7" => "\xe2\x95\x96", "\xb8" => "\xe2\x95\x95", "\xb9" => "\xe2\x95\xa3", "\xba" => "\xe2\x95\x91", "\xbb" => "\xe2\x95\x97", "\xbc" => "\xe2\x95\x9d", "\xbd" => "\xe2\x95\x9c", "\xbe" => "\xe2\x95\x9b", "\xbf" => "\xe2\x94\x90", "\xc0" => "\xe2\x94\x94", "\xc1" => "\xe2\x94\xb4", "\xc2" => "\xe2\x94\xac", "\xc3" => "\xe2\x94\x9c", "\xc4" => "\xe2\x94\x80", "\xc5" => "\xe2\x94\xbc", "\xc6" => "\xe2\x95\x9e", "\xc7" => "\xe2\x95\x9f", "\xc8" => "\xe2\x95\x9a", "\xc9" => "\xe2\x95\x94", "\xca" => "\xe2\x95\xa9", "\xcb" => "\xe2\x95\xa6", "\xcc" => "\xe2\x95\xa0", "\xcd" => "\xe2\x95\x90", "\xce" => "\xe2\x95\xac", "\xcf" => "\xe2\x95\xa7", "\xd0" => "\xe2\x95\xa8", "\xd1" => "\xe2\x95\xa4", "\xd2" => "\xe2\x95\xa5", "\xd3" => "\xe2\x95\x99", "\xd4" => "\xe2\x95\x98", "\xd5" => "\xe2\x95\x92", "\xd6" => "\xe2\x95\x93", "\xd7" => "\xe2\x95\xab", "\xd8" => "\xe2\x95\xaa", "\xd9" => "\xe2\x94\x98", "\xda" => "\xe2\x94\x8c", "\xdb" => "\xe2\x96\x88", "\xdc" => "\xe2\x96\x84", "\xdd" => "\xe2\x96\x8c", "\xde" => "\xe2\x96\x90", "\xdf" => "\xe2\x96\x80", "\xe0" => "\xce\xb1", "\xe1" => "\xc3\x9f", "\xe2" => "\xce\x93", "\xe3" => "\xcf\x80", "\xe4" => "\xce\xa3", "\xe5" => "\xcf\x83", "\xe6" => "\xc2\xb5", "\xe7" => "\xcf\x84", "\xe8" => "\xce\xa6", "\xe9" => "\xce\x98", "\xea" => "\xce\xa9", "\xeb" => "\xce\xb4", "\xec" => "\xe2\x88\x9e", "\xed" => "\xcf\x86", "\xee" => "\xce\xb5", "\xef" => "\xe2\x88\xa9", "\xf0" => "\xe2\x89\xa1", "\xf1" => "\xc2\xb1", "\xf2" => "\xe2\x89\xa5", "\xf3" => "\xe2\x89\xa4", "\xf4" => "\xe2\x8c\xa0", "\xf5" => "\xe2\x8c\xa1", "\xf6" => "\xc3\xb7", "\xf7" => "\xe2\x89\x88", "\xf8" => "\xc2\xb0", "\xf9" => "\xe2\x88\x99", "\xfa" => "\xc2\xb7", "\xfb" => "\xe2\x88\x9a", "\xfc" => "\xe2\x81\xbf", "\xfd" => "\xc2\xb2", "\xfe" => "\xe2\x96\xa0", "\xff" => "\xc2\xa0", ); private static $aliases = array( 'IBM860', '860', 'cp860', 'ibm-860', 'csIBM860', 'ibm860', ); protected function getConversionTable() { return self::$conversionTable; } protected function getNoChangesRanges() { return array( array( 'start' => 0x20, 'end' => 0x7E, ), ); } public function getName() { return 'WINDOWS-860'; } public function getAliases() { return self::$aliases; } }
luongtran/shop
wp-content/plugins/woocommerce_barclaycardcw/lib/Customweb/Core/Charset/WINDOWS860.php
PHP
gpl-2.0
4,698
#include <iostream> #include <string> using namespace std; int main() { cout<<"**************************************************"<<endl; cout<<"»¶Ó­Ê¹ÓöþÑõ»¯Ì¼ÅÅ·ÅÁ¿¼ÆËãÆ÷"<<endl; cout<<"¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿¼ÆË㹫ʽ £º"<<endl; cout<<"¼ÒÍ¥ÓõçµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿£¨Ç§¿Ë£©=ºÄµç¶ÈÊý¡Á0.785"<<endl; cout<<"ʳÈâµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿£¨Ç§¿Ë£©=ʳÈâǧ¿ËÊý¡Á1.24"<<endl; double eco2; //¼ÒÍ¥ÓõçµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿ double mco2; //ʳÈâµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿ double electricity; //ºÄµç¶ÈÊý double meat; //ʳÈâǧ¿ËÊý cout<<"ÇëÊäÈëÄãµÄ¼ÒÍ¥ÓõçºÄµç¶ÈÊý(¶È)£º "; cin>>electricity; cout<<"ÇëÊäÈëÄãµÄʳÈâǧ¿ËÊý£¨Ç§¿Ë£©£º "; cin>>meat; cout<<0<<endl; eco2 = electricity * 0.785; mco2 = meat * 1.24; cout<<1<<endl; cout<<"ÄãµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÊý¾Ý£º"<<endl; cout<<"¼ÒÍ¥ÓõçµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿£º"<<eco2<<endl; cout<<"ʳÈâµÄ¶þÑõ»¯Ì¼ÅÅ·ÅÁ¿£º"<<mco2<<endl; cout<<"°´ÈÎÒâ¼ü¼ÌÐø..."; system("Pause"); return 0; }
kylin1702/linyk-app
socket/exe1.cpp
C++
gpl-2.0
1,012
<?php namespace FedEx\ShipService\ComplexType; use FedEx\AbstractComplexType; /** * The descriptive data for the monetary compensation given to FedEx for services rendered to the customer. * * @author Jeremy Dunn <jeremy@jsdunn.info> * @package PHP FedEx API wrapper * @subpackage Ship Service * * @property \FedEx\ShipService\SimpleType\PaymentType|string $PaymentType * @property Payor $Payor */ class Payment extends AbstractComplexType { /** * Name of this complex type * * @var string */ protected $name = 'Payment'; /** * Identifies the method of payment for a service. See PaymentType for list of valid enumerated values. * * @param \FedEx\ShipService\SimpleType\PaymentType|string $paymentType * @return $this */ public function setPaymentType($paymentType) { $this->values['PaymentType'] = $paymentType; return $this; } /** * Descriptive data identifying the party responsible for payment for a service. * * @param Payor $payor * @return $this */ public function setPayor(Payor $payor) { $this->values['Payor'] = $payor; return $this; } }
rswyatt/kittypooclub
sites/all/modules/custom/kittypooclub_chargify/includes/fedex/src/FedEx/ShipService/ComplexType/Payment.php
PHP
gpl-2.0
1,220
package org.egyptscholars.momken.text2phoneme; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import edu.stanford.nlp.international.arabic.Buckwalter; /** * Text2Phonem * * @author Amgad Madkour <amgad.madkour@egyptscholars.org> * */ public class App { private static ArrayList<String> createPhonemes(HashMap<String,String> lookupTable,String text){ ArrayList<String> phonemeEntries=new ArrayList<String>(); System.out.println(text); //String lastChar = ""; for(int i=0 ; i < text.length()-1; i++){ String currentChar = lookupTable.get(Character.toString(text.charAt(i))); if (currentChar != null){ //Add the current character phonemeEntries.add(currentChar); String nextCh = lookupTable.get(Character.toString(text.charAt(i+1))); //Handle Special Case of aa if(nextCh != null && (currentChar.startsWith("d.") || currentChar.startsWith("t.")|| currentChar.startsWith("z.")|| currentChar.startsWith("s."))){ if(nextCh.charAt(0) == 'a'){ phonemeEntries.add("a. 70 28 109 71 104"); i++; }else if(nextCh.charAt(0) == 'i'){ phonemeEntries.add("i. 70 28 109 71 104"); i++; }else if(nextCh.charAt(0) == 'u'){ phonemeEntries.add("u. 61 35 101 83 102"); i++; } } //lastChar = currentChar; } } System.out.println("---"+text); if(lookupTable.get(Character.toString(text.charAt(text.length()-1)))!=null) phonemeEntries.add(lookupTable.get(Character.toString(text.charAt(text.length()-1)))); //Cleanup redundant entries due to Tashkeel (i.e. i. followed by i etc.) int sz = phonemeEntries.size(); for(int i = 0 ; i < sz-1; i++){ if(phonemeEntries.get(i).charAt(0) == phonemeEntries.get(i+1).charAt(0)){ phonemeEntries.remove(i+1); sz -= 1; } if(phonemeEntries.get(i).startsWith("u.") && phonemeEntries.get(i+1).startsWith("a")){ phonemeEntries.remove(i+1); sz -= 1; } } System.out.println(phonemeEntries); return phonemeEntries; } public static String cleanBuckwalter(String buck){ System.out.println("Before: "+buck); StringBuffer buff=new StringBuffer(); String lst = "A'btvjHxd*rzs$SDTZEgfqklmnhwyaiu}p><O"; for(int i = 0 ; i < buck.length() ; i++){ if(lst.contains(String.valueOf(buck.charAt(i)))){ buff.append(String.valueOf(buck.charAt(i))); } } return buff.toString(); } public static void main( String[] args ){ String temp; BufferedReader lookupRdr; BufferedReader txtRdr; PrintWriter phonemeWrt; HashMap<String,String> lookupTable; String[] parts; ArrayList<String> phonemeEntries= new ArrayList<String>(); try { //TODO Replace with Apache command Line handling later (cleaner) lookupRdr = new BufferedReader(new FileReader(args[0])); txtRdr = new BufferedReader(new FileReader(args[1])); phonemeWrt = new PrintWriter(new FileWriter(args[2])); lookupTable = new HashMap<String,String>(); //Load lookup table while((temp = lookupRdr.readLine())!= null){ parts = temp.split("\t"); lookupTable.put(parts[0], parts[1]); } //Load text Buckwalter b = new Buckwalter(); String words; while((temp = txtRdr.readLine())!= null){ temp = temp.replace(".", ""); words = b.unicodeToBuckwalter(temp); parts = words.split(" "); for (int i=0 ; i<parts.length; i++){ String cleaned = cleanBuckwalter(parts[i]); if(cleaned.length()>0){ ArrayList<String> ph = createPhonemes(lookupTable, cleaned); phonemeEntries.addAll(ph); phonemeEntries.add("_ 5"); } } } //Output the results to file for(String entry:phonemeEntries){ phonemeWrt.println(entry); } System.out.println("Phoneme File Created"); phonemeWrt.close(); lookupRdr.close(); txtRdr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
egyptscholarsinc/momken-text2phoneme
src/main/java/org/egyptscholars/momken/text2phoneme/App.java
Java
gpl-2.0
4,240
package com.htl_villach.tatue_rater.Classes; /** * Created by simon on 10.03.2016. */ public class Rechteck { public Punkt a; public Punkt b; public Rechteck() { } public Rechteck(Punkt a, Punkt b) { this.a = a; this.b = b; } }
Joniras/Tatue-Organiser
Code/Android-Project/Tatue-Rater2/app/src/main/java/com/htl_villach/tatue_rater/Classes/Rechteck.java
Java
gpl-2.0
273
<?php session_start(); header ("Content-Type: text/html; charset=UTF-8"); /* * srboard 40.60 * ------------------------------- * Developed By 사리 (sariputra3@naver.com) * License : GNU Public License (GPL) * Homepage : http://srboard.styx.kr */ //if($_SERVER['HTTP_REFERER'] == "http://{$_SERVER['HTTP_HOST']}/") exit; include("include/common.php"); $title = $sett[0]; $flo = ''; $memb = ''; $onload = ''; $vtrpc = array(0,0,0); if(_GET('keyword')) {$gkeyword = trim($_GET['keyword']);$_GET['keyword'] = stripslashes($gkeyword);} else $gkeyword = ''; if($id && ($sss[23] == 'a' || $sss[23] > $mbr_level)) $authority_read = 3; else $authority_read = 0; if($id && (_GET('no') || _GET('link'))) {include("include/view.php");$title = "[{$wdth[1]}] ".$flo[3];} ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="ko" xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo $title?></title> <meta name="generator" content="<?php echo $srboard?>" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <?php if($ismobile) {?> <meta name="viewport" content="user-scalable=yes, initial-scale=1.0, maximum-scale=1.5, minimum-scale=0.5, width=device-width" /> <?php } if($sett[31]) {?> <link rel="shortcut icon" type="image/x-icon" href="http://<?php echo $_SERVER['HTTP_HOST']?>/favicon.ico" /> <?php } if(_GET('count_add') || _GET('view')) include("include/referer.php"); function getmicrotime() { $msec = microtime(); return substr($msec,19) + substr($msec,0,10); } function strcut($str, $len){ $str = trim($str); if($len){ $str = str_replace("<br />"," ",$str); $str = strip_tags($str); if(strlen($str) > $len) { $str = substr($str, 0, $len + 1); $end = $len; if(ord($str[$end -2]) < 224 && ord($str[$end]) > 126) { while(ord($str[$end]) < 194 && ord($str[$end]) > 126) $end--; $str = substr($str, 0, $end).".."; } else $str .= ".."; } $isa = strpos(substr($str,-8),"&"); if($isa) $str = substr($str,0,-8 + $isa); $str = str_replace("\\", "\", $str); } if($end = strpos($str,"\x1b")) $str = substr($str,0,$end); return trim($str); } $time_start = getmicrotime(); function name($name, $mn, $target, $ico, $url) { global $sett,$sss,$fmm; if($sss[64]) $namee = $name; else { $name = trim($name); if($target == 1) $adtarget="_parent"; else $adtarget="_self"; $namee = $is80 = $m = ''; if($mn) { if(file_exists("icon/m20_".$mn)) { if($sett[44] == 2 || $sett[44] == 3) $is80 = 1; if($sett[44] == 1 || $sett[44] == 3) $is60 = 1; $umg = 'icon/m20_'.$mn; $isumg = 1; } else {$umg = 'icon/noimg.gif';$isumg = 0;} if($sett[91][0] == '4' && $ico) $ico = 0;else if($sett[91][0] == '5' && !$ico) $ico = 1; if(!$ico || $sett[91][0] == '1' || $sett[91][0] == '3') { if($sett[90]) $namee .= "<img class='icolv' src='icon/pointlevel/".(($sett[91][1] && $fmm[$mn][2] == '9')? 'm':$fmm[$mn][16]).".gif' alt='' />"; else $namee .= "<img src='icon/v".$fmm[$mn][2].".gif' class='mblv' alt='' />"; } if($ico || ($isumg && ($sett[91][0] == '2' || $sett[91][0] == '3'))) { if($is60) $namee .= "<img src='{$umg}' onmouseover='imgview(this.src,9)' onmouseout='imgview(0)' class='icos' alt='' />"; else $namee .= "<img src='{$umg}' class='icos' alt='' />"; } $m = 'mb'; } $namee .= "<a href='#none' class='{$m}nick' onclick=\"wwname('".urlencode($name)."','{$mn}','{$adtarget}','{$url}','{$is80}')\">"; $namee .= ($_GET['search'] == 'n')? str_replace($_GET['keyword'], "<span class='keyword'>{$_GET['keyword']}</span>",$name):$name; $namee .="</a>"; } return $namee; } function tagcut($tag, $rkin) { $glen = strpos($rkin,"<sr_".$tag.">"); if($glen !== false) { $head = $glen + strlen($tag) + 5; return substr($rkin, $head, strpos($rkin,"</sr_".$tag.">") - $head); } else return ''; } function inclvde($data) { if(strpos($data,'<;>') !== false) $data = preg_replace("`<;>(.+)<!--/-->`sU","",$data); $data = str_replace("<!--/-->","",$data); if(strpos($data,'<#') !== false) { $data = preg_replace("`<#[^#]+#>`","",$data); $gtis = strpos($data,'<##'); if($gtis !== false) { echo substr($data,0,$gtis); $gtin = explode('<##',substr($data,$gtis)); $gtinc = count($gtin); for($igt = 1;$igt < $gtinc;$igt++) { $gtine = strpos($gtin[$igt],'##>'); $gtinf = substr($gtin[$igt],0,$gtine); if($gtinf[0] == '#') $return[] = array(1,substr($gtinf,1,-1)); else if(@filesize($gtinf)) $return[] = array(2,$gtinf); $return[] = array(0,substr($gtin[$igt],$gtine + 3)); }} else $return[] = array(0,$data); } else $return[] = array(0,$data); return $return; } if($id && !$sss) { scrhref('?',0,0); exit; } if($slss[4]) $fz = $slss[4]; if(_COOKIE('cfsz')) $fz = $_COOKIE['cfsz']; else if(!_VAR($fz)) $fz = '9'; $faz = array('Gulim','Dotum','Batang','Gungsuh','Malgun Gothic','Arial','Tahoma','Verdana','Trebuchet MS','sans-serif'); $faze = (isset($wdth[8][0]) && $wdth[8][0])? $faz[$wdth[8][0]]:$faz[0]; if(_GET('signup') || _POST('join') || _GET('mbr_info')) $mbrphp = 1;else $mbrphp = 0; if($id) { if($csf = @fopen($dxr.$id."/set.dat","r")) {$csff[0] = trim(fgets($csf));$csff[1] = trim(fgets($csf));$csff[2] = trim(fgets($csf));$csff[3] = (int)fgets($csf);fclose($csf);if($csff[3]) $sett[21] = $csff[3];} if($_GET['comment'] && $csff[0]) $srk = $csff[0]; else $srk = ($slss[2])? $slss[2]:$wdth[2]; } else $srk = ($slss[2])? $slss[2]:$sett[1]; if($ismobile == 2) $srk = 'mobile'; if($id && $sss[29]) echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"[{$sett[0]}] - {$bdidnm[$id]}\" href=\"{$sett[14]}exe.php?rss={$id}\" />\n"; if($sect[$section][2]) echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"[{$sett[0]}] - {$sect[$section][0]} -\" href=\"{$sett[14]}exe.php?rssfeed={$section}\" />\n"; $sectcss = "module/sectcss_".$section.".css"; if(!file_exists($sectcss) || !filesize($sectcss)) $sectcss = ''; ?> <link rel="alternate" type="application/rss+xml" title="[<?php echo $sett[0]?>] - 전체" href="<?php echo $sett[14]?>exe.php?rssfeed=all" /> <style type='text/css'> <?php if($_GET['comment']) {?> body {overflow:hidden; font-family:Gulim; font-size:9pt; margin:0} <?php } else {?> body {font-family:Gulim; font-size:9pt; margin:0} <?php }?> .bdo, .bdo div {font-size:<?php echo $fz?>pt; font-family:<?php echo $faze?>;} </style> <link rel='stylesheet' type='text/css' href='include/srboard.css' /> <?php if($sett[26]){?><link rel='stylesheet' type='text/css' href='module/<?php echo $sett[26]?>.css' /> <?php } if(!$id && $sett[45]){?><link rel='stylesheet' type='text/css' href='widget/<?php echo $sett[45]?>.css' /> <?php } if($sectcss){?><link rel='stylesheet' type='text/css' href='<?php echo $sectcss?>' /> <?php }?> <link rel='stylesheet' type='text/css' href='skin/<?php echo $srk?>/style.css' /> <!--[if IE]> <style type='text/css'> td, div {word-break:break-all; text-overflow:ellipsis} </style> <![endif]--> <!--[if lte IE 6]> <link rel='stylesheet' type='text/css' href='include/ie6.css' /> <![endif]--> <?php if($ismobile == 2) {?> <style type='text/css'> </style> <?php } if($sett[77]) {?> <style type='text/css'>.nobr {white-space:normal} <?php if(!$id) {?>#srgate dt span, #srgate .nL4 {float:none; display:inline} #srgate span.lnkrp a.rp {display:inline-block} <?php } else {?>#bd_main dt span {float:none; display:inline}<?php }?> </style><?php } if($sett[24]) {?> <link rel='stylesheet' type='text/css' href='<?php echo $sett[24]?>' /><?php } if(file_exists('icon/style.css')) {?> <link rel='stylesheet' type='text/css' href='icon/style.css' /><?php } if(_VAR($csff[2])) {?> <link rel='stylesheet' type='text/css' href='<?php echo $csff[2]?>' /> <?php }?> <script type='text/javascript'> var wopen = 1; var setop = Array('<?php echo $isie?>','<?php echo $bwr?>',<?php echo (int)$srwtpx?>,'<?php echo $sett[55]?>','<?php echo (($sett[8] != 'a' && $sett[8] <= $mbr_level)?1:0)?>','<?php echo (($sett[57] != 'a' && $sett[57] <= $mbr_level)?1:0)?>','<?php echo $id?>',<?php echo (int)$sett[11]?>,<?php echo $ismobile?>,'<?php echo $bdidnm[$id]?>'); </script> </head> <?php if($_GET['comment']) { ?> <body class='cbody' onclick="if(pxxx.wopen==2) pxxx.imgview(0);"> <?php } else if($aview) { ?> <body class='bbody' onselectstart="return false" style="-moz-user-select:none"> <?php } else { ?> <body class='bbody'> <?php if($sett[2]) include($sett[2]); } ?> <span id='img' style='position:absolute'></span> <div id='pview' style='display:none;padding:5px; line-height:130%;position:absolute'></div> <script type="text/javascript" src="include/top.js"></script> <script type='text/javascript'> //<![CDATA[ function searchc(val) { if(document.sform.keyword.value != '' && document.sform.keyword.value == '<?php echo $gkeyword?>') location.href='?<?php echo $_SERVER['QUERY_STRING']?>'.replace(/&search=[a-z]/i,'&search=' + val).replace(/&p=[0-9]+/i,'&p=1'); } function ckprohibit(ths) { var prhbw = new Array(''<?php if($fp=@fopen($dxr."prohibit","r")){ while($fpo = trim(fgets($fp))) echo ",'{$fpo}'"; fclose($fp); } ?>); for(var i=prhbw.length -1;i > 0;i--) { if(ths.indexOf(prhbw[i]) != -1) return prhbw[i]; }} <?php if($dxr && $_GET['block5']) { if($sss[22] == 'a' || $sss[22] > $mbr_level) exit; if($isie == 1) {?> setTimeout("$('bdo-1').innerHTML = dialogArguments.ajaxx;img_resize();document.body.style.overflowX = 'hidden';document.body.style.background = '#FFFFFF';",500); <?php }}?> //]]> </script> <?php if($dxr && _GET('block5')) {echo "<div id='bdo-1' class='bdo block5' style='padding:20px 10px 10px 30px'></div></body></html>";exit;} if($dxr && !$_GET['comment']) { if(_GET('type') && $sss[53]) $_GET['type'] = ''; if($_GET['type']) $type= $_GET['type']; else if($id) $type = $sss[26];else $type = ''; $length = strlen(_GET('date')); if($length < 4 || $length%2) $_GET['date'] = ''; if($type == 'k') { $otype = 'k'; $mcnt = 1; if($length > 6) $_GET['date'] = substr($_GET['date'],0,6); else if($length == 4) $_GET['date'] .= "01"; $fr = fopen($dxr.$id."/date.dat","r"); while(!feof($fr)){ if($fro = trim(fgets($fr))){ $ymdn = substr($fro, 0, 4)."년 ".substr($fro, 4, 2)."월 (".substr($fro, 6).")"; if(!$_GET['date'] && ($_GET['p'] == $mcnt || !$_GET['p'] && $mcnt == 1)) {$calp = $mcnt;$_GET['date'] = substr($fro,0,6);$isnt = substr($fro,6);$months .= "<option value='{$mcnt}' selected='selected'>$ymdn</option>";} else if($_GET['date'] && substr($_GET['date'],0,6) == substr($fro,0,6)) {$calp = $mcnt;$isnt = substr($fro,6);$months .= "<option value='{$mcnt}' selected='selected'>$ymdn</option>";} else $months .= "<option value='{$mcnt}'>$ymdn</option>"; $mcnt++; }} fclose($fr); $_GET['p'] = 1; $mcnt--; } if(!$sett[41] || $sett[41] == 1) $bhlct = ''; else { $bhlct = "<a href='{$index}'>HOME</a>"; if($sett[41] != 2 && $sett[41] != 6 && $sett[41] != 7 && $grp[$sgp]) $bhlct .= " &gt; <a href='{$index}?group={$sgp}'>{$grp[$sgp][0]}</a>"; if($sett[41] != 3 && $sett[41] != 5 && $sett[41] != 7 && $section && (count($bfsb[$section]) > 1 || $sett[40])) $bhlct .= " &gt; <a href='{$index}?section={$section}'>{$sect[$section][0]}</a>"; if($sett[41] != 4 && $sett[41] != 5 && $sett[41] != 6) $bhlct .= " &gt; <a href='{$dxpt}&amp;p=1'>{$wdth[1]}</a>"; } if($sett[26]) include('module/'.$sett[26].'.php'); if($ismobile == 2 || $sett[77] == 1) $srwdthx = '100%'; else $srwdthx = $srwdth.'px'; if($id && $sett[41]){?><div class='bd_name'><h2><?php if($sss[29]){?><a target='_blank' href='exe.php?rss=<?php echo $id?>'><img src='icon/rss.gif' alt='' border='0' /></a><?php } else {?><img src='icon/norss.gif' alt='' border='0' /><?php }?><a href='<?php echo $dxpt?>'><?php echo $bdidnm[$id]?></a></h2><div><?php echo $bhlct?>&nbsp;</div></div><?php } if($_GET['signup'] || $_POST['join'] || $_GET['mbr_info'] || _GET('findw')) {?><div class='bd_name'><h2><img src='icon/sy.gif' alt='' /><?php if($_GET['signup']) echo "이용약관과 개인정보 취급방침";else if($_POST['join']) echo "회원가입";else if($_GET['mbr_info']) echo "회원정보";else echo "검색어 : ". $_GET['findw'];?></h2><div></div></div><?php } else if(!$ismobile && (($sett[16][0] && !$id) || ($id && (($sett[16][2] && $_GET['no']) || ($sett[16][1] && !$_GET['no'])))) && @filesize($dxr."head")) {if($sett[32]) @readfile($dxr."head");else include($dxr."head");} } if($mbrphp) {echo "<center>";include("include/mbr.php");echo "</center>";} else { $rt = ""; $rrt = ""; if($_GET['keyword']) $rt .= "&amp;search=".$_GET['search']."&amp;keyword=".urlencode($_GET['keyword']); if(_GET('c')) $rrt .= "&amp;c=".$_GET['c']; if(_GET('arrange')) $rrt .= "&amp;arrange=".$_GET['arrange']."&amp;desc="._GET('desc'); if(_GET('m')) $rrt .= "&amp;m=".$_GET['m']; if($type != 'k' && $_GET['date']) $rrt .= "&amp;date=".$_GET['date']; $rt .= $rrt; if(_GET('ct')) $rt .= "&amp;ct=".$_GET['ct']; if($_GET['type']) $rt .= "&amp;type=".$_GET['type']; if(_GET('xx')) $rt .= "&amp;xx=".$_GET['xx']; $crt = preg_replace('`&amp;ct=[0-9]+`', '', $rt)."&amp;p=1"; if(!$_GET['comment']) { $day = date("d",$time); if(_COOKIE('visit') != $day) { $onload .= "mkcookie('visit','{$day}',1);\n"; if($_SESSION['visit'] != $day) { $_SESSION['visit'] = $day; $countadd = $index."?count_add=".base64_encode(str_pad($_SERVER['REMOTE_ADDR'], 15)."\x1b".$_SERVER['QUERY_STRING']."\x1b".$_SERVER['HTTP_REFERER']); }} ?> <iframe name="exe" style="display:none;width:0;height:0" src="<?php echo $countadd?>"></iframe> <?php } $srkn = ''; $sr = fopen("skin/".$srk."/skin.html","r"); while($sro = fgets($sr)) $srkn .= $sro; fclose($sr); $srkn = str_replace("<#index#>",$index,$srkn); $srkn = str_replace("<#exe#>","exe.php",$srkn); /* 38.20에서 삭제된 부분*/ $srkn = str_replace("<#bd_width#>",$srwdthx,$srkn); $srkn = str_replace("<#bd_url#>",$sett[14],$srkn); if($mbr_no >= 1) { $srkn = str_replace('<#ismbr#>','',$srkn); $srkn = str_replace('<#isxmbr#>','<;>',$srkn); } else { $srkn = str_replace('<#ismbr#>','<;>',$srkn); $srkn = str_replace('<#isxmbr#>','',$srkn); } $skv = tagcut('top',$srkn); if($sett[62]) $sett[62] = $time - $sett[62]*21600; else $sett[62] = 9999999999; if($id) { function uplist($uno) { global $dxr, $id, $du, $wdth; $drctry = ($wdth[7][33])? "icon/".$id."/":$dxr.$id."/files/"; $fu = fopen($du ,"r"); while(!feof($fu)) { $fuo = fgets($fu); if((int)substr($fuo, 0, 6) == $uno) { $nfile = substr($fuo, 6, -13); if($nfile[20] == '/') {$mfile = $drctry.substr($nfile,0,20);$nfile = substr($nfile,21);} else $mfile = $drctry.str_replace("%","",urlencode($nfile)); if($sfile = @filesize($mfile)) { $ufile = "exe.php?sls=".$id."/down/".(int)substr($fuo, -7, 6); $sfile = ($sfile >= 1048576)? sprintf("%.2f", ($sfile / 1048576))."mb":sprintf("%.2f", ($sfile / 1024))."kb"; $sfile .= " : ".(int)substr($fuo, -13, 6)."회"; $memx .= "<img src='icon/f.png' style='width:13px;height:13px;vertical-align:middle;margin-right:3px' alt='' /><a target='_blank' href='".$ufile."'>".$nfile." ( ".$sfile." )</a> &nbsp; "; } } } fclose($fu); if($memx) return "<div class='uplist'><b>첨부파일</b> : ".$memx."</div>"; } $keyw = array(); if($_GET['search'] == 'n' || $_GET['search'] == 'ip' || $_GET['search'] == 't' || $_GET['search'] == 'r' || $_GET['search'] == 'rip') $keyw[0] = $_GET['keyword']; else { $keywrd2 = str_replace('\'','"',$_GET['keyword']); $keyu = array();$keyy = array(); if(strpos($keywrd2,'"') !== false) { while(($kew = strpos($keywrd2,'"')) !== false) { $keywrd = substr($keywrd2,0,$kew); $keywrd2 = substr($keywrd2,$kew + 1); if(($kex = strpos($keywrd2,'"')) !== false) { $keyv = explode(" ",$keywrd); $keyv[] = substr($keywrd2,0,$kex); $keywrd2 = substr($keywrd2,$kex + 1); $keyu = array_merge($keyu, $keyv); } else {if(!count($keyu)) $keywrd = $_GET['keyword'];if($keywrd) {$keyv = explode(" ",$keywrd);$keyu = array_merge($keyu, $keyv);}} } if($keywrd2) {$keyv = explode(" ",$keywrd2);$keyu = array_merge($keyu, $keyv);} } else $keyy = explode(" ",$_GET['keyword']); if(count($keyu)) $keyy = array_merge($keyu,$keyy); foreach($keyy as $key => $value) {if($value) $keyw[] = $value;}} $keywc = count($keyw) - 1; $srkin = tagcut('id',$srkn); $srkin = str_replace("<#id#>",$id,$srkin); $srkin = str_replace("<#eid#>",$id,$srkin); $srkin = str_replace("<#bd_name#>",$wdth[1],$srkin); if(!$_GET['comment']) { $skv .= tagcut('head',$srkin); if($inclwt=inclvde($skv)) foreach($inclwt as $inxv) {if($inxv[0] == 1) eval($inxv[1]);else if($inxv[0] == 2) {if($sett[92][0] == '2' || $sett[92][0] == '3') $gmtime = getmicrotime();include($inxv[1]);if($sett[92][0] == '2' || $sett[92][0] == '3') echo "<!--".$inxv[1]." 처리시간:: ".(getmicrotime() - $gmtime)." -->";}else {?><?php echo $inxv[1]?><?php }} function nocopy($txt) { global $aview, $noright; if($aview && !$noright) { if($aview < 3) $txt = "<div onselectstart='return false' style='-moz-user-select:none'>".$txt."</div>"; else if($aview == 3) $txt = "<div id='ifr_bdo' onselectstart='return false' style='-moz-user-select:none'></div>"; else if($aview == 4) $txt = "<iframe id='ifr_bdo' style='border:0' frameborder='0'></iframe>"; else if($aview >= 5) $txt = "<div style='padding:120px 0px 100px 0;margin-right:20px'><div style='background:#000;color:#FFF;font-size:25px;line-height:40px;padding:25px'>본문은 팝업으로 뜹니다<br />IE에서만 보입니다.</div></div>"; } return $txt; } } if(!$xx && $_GET['xx']) $xx = $_GET['xx']; if($slss[5]) $isnt= $slss[5]; if(($sss[26] === 'a'||$sss[63]||$sss[26] == 'g') && ($_GET['type'] == 'b'||$_GET['type'] == 'c'||$_GET['type'] == 'd')) $isnt = (int)($isnt/2); if(!$_GET['comment'] && (!$ismobile || $sss[70]) && @filesize($dxr.$id."/head.dat")) {if($sett[32]) @readfile($dxr.$id."/head.dat");else include($dxr.$id."/head.dat");} if(_POST('edit') == "unlock") $_GET['no'] = $_POST['no']; if(!_GET('p')) $gp = 1; else $gp = $_GET['p']; if($sss[22] != 'a' && $sss[22] <= $mbr_level){ function imn($mm,$mddlt,$body,$nn,$xx,$isdoc) { global $mbr_no,$mbr_level,$sett; if(!$mm) {$vmd = 3;$vlt = 3;} else if($mm == $mbr_no || $mbr_level == 9) {$vmd = 4;$vlt = 4;} else {$vmd = 2;$vlt = 2;} if($mddlt[0] === 4) $vmd = 0; if($mddlt[1] === 4) $vlt = 0; if($isdoc) { if($vlt == 0 && $sett[72] < 2) $body = str_replace('<#is_delete#>','<;>',$body); else $body = str_replace("<#jsdelete#>","'delete',{$vlt},'{$nn}','{$xx}'",$body); if($vmd == 0 && $sett[72] < 2) $body = str_replace('<#is_edit#>','<;>',$body); else $body = str_replace("<#jsedit#>","'edit',{$vmd},'{$nn}','{$xx}'",$body); } else { if($vlt == 0 && (!$sett[72] || $sett[72] == 2)) $body = str_replace('<#isrdlnk#>','<;>',$body); else $body = str_replace("<#rdlnk#>","rfpass('del_reple','{$vlt}','a',{$nn})",$body); if($vmd == 0 && (!$sett[72] || $sett[72] == 2)) $body = str_replace('<#isrmlnk#>','<;>',$body); else $body = str_replace("<#rmlnk#>","rpmod('{$vmd}',{$nn})",$body); } return $body; } function skword($kword) { global $keyw; for($k = 0;$keyw[$k];$k++) {$kword = str_replace($keyw[$k], "<span class='keyword'>{$keyw[$k]}</span>",$kword);} return $kword; } $appo = ($mbr_level < $wdth[9][0] || $authority_read || ($vtrpc[0] && $sett[72] < 2))? 1:0; if(!$sss[60] || $appo === 1) $srkin = str_replace('<#is_appr#>','<;>',$srkin); if(!$sss[61] || $appo === 1) $srkin = str_replace('<#is_oppo#>','<;>',$srkin); if($mbr_level < $wdth[9][0] || $authority_read || $sss[49] != '2') $srkin = str_replace('<#is_accs#>','<;>',$srkin); if($_GET['c'] || $_GET['m'] || $_GET['keyword'] || $_GET['date']) $cmkd = 2; else $cmkd = 0; if($cmkd == 2 || $_GET['ct'] || $_GET['arrange'] || $sss[65]) $schphp = 1; else $schphp = 0; $ida = ''; if($_GET['no']) { // 게시물 본문 출력 if($ismobile == 2) $sss[30] = 0; include("include/view2.php"); } else if($_GET['comment'] || $_GET['rp_view']) { include("include/comment.php"); if($_GET['comment']) exit; else { $_GET['comment'] = ''; $_GET['no'] = $_GET['rp_view']; }} else { $sss[30] = 1; $crtime = $time - $cuttime[$sett[71][17]]; ?> <script type='text/javascript'>document.title="[<?php echo $sett[0]?>] <?php echo $wdth[1]?>";</script> <?php } // 게시판 목록 시작 if(!$_GET['p']) $_GET['p'] = 1;$newwin = '';$nscc = 0; if($sss[30]){ if($type == 'k') { if($_GET['type'] == 'a' || $_GET['c'] || $_GET['m'] || $_GET['keyword'] || $_GET['arrange'] || $_GET['no']) $type = 'a'; $_SERVER['QUERY_STRING'] = preg_replace("`&(amp;)?date=[0-9]+`i","",$_SERVER['QUERY_STRING']); } else if($sss[26] == 'e') { if($_GET['type'] == 'a' || $cmkd == 2 || $_GET['ct'] || $_GET['arrange']) {$type = 'a'; $isnt = $isnt*$sett[19];} else if($_GET['no']) $type = 'a'; else $type = 'b'; } if($type == 'c') $len = 320; else if($type == 'b'||$type == 'd') $len = 0; else $len = 256; if($_GET['xx'] > 0) $idd = $id."/^".$_GET['xx']; else $idd = $id; if(!$ismobile && ($sss[28] == 1 || $sss[28] == 3) && ($type == 'a' || $type == 'g')) $sss[28] = 4;else if($type == 'g') $onload .= "thtcg = 1;"; if($sss[32] == 1 || $sss[32] == 3) $sss[32] = 4; if($sss[71] == 1 || $sss[71] == 3) $sss[71] = 4; if($sss[72] == 1 || $sss[72] == 3) $sss[72] = 4; if($sss[73] == 1 || $sss[73] == 3) $sss[73] = 4; if($sss[73] != 4 && $_GET['search'] != 'b' && (!$sss[54] || !$wdth[7][0])) $bodd = ""; else $bodd = "/body.dat"; $uuu = ""; if($sss[64] && $_GET['m']) {scrhref($dxpt,0,'익명게시판에서는 회원검색이 안됩니다');exit;} if($schphp) { if($type != 'g' && ($sett[10] == '1' || $sett[10] == '2')) $newwin = '" target="_blank" rel="'; if(!$_GET['arrange'] && $sss[65] && $cmkd != 2) $_GET['arrange'] = 'hot'; if($sss[65] || (_COOKIE($docoo) && $_COOKIE[$docoo] == $dockie)) include("include/search.php"); } else { if(!$_GET['xx']) { $start = $isnt*($gp - 1); if($fnt < $start) { $ftt = $start - $fnt; $ih = $start - $fnt; if($wdth[6]) { for($i = $wdth[6];$i > 0;$i--) { $fnnt = substr($do[$i], 12, 6); $ftt -= $fnnt; if($ftt < 0) { $ida = $i; $start = $ih; break; } else $ih -= $fnnt; }} } else $ida = ""; if($ida > 0) {$idd = $id."/^".$ida;$xx = $ida;} else $idd = $id; } else { $idd = $id."/^".$_GET['xx']; $start = $isnt*($_GET['p'] - 1); $fct = $fnt; } $end = $start + $isnt; $n = $isnt; if($type == 'a' && $wdth[4]) { if(!$nscc) { $nss = explode('^', $wdth[4]); $nsc = count($nss) -1; $nscc = $nsc; } if($_GET['p'] > 1) $start = $start - $nsc; $end = $end - $nsc; if($_GET['p'] == 1) { $a = fopen($dxr.$id."/notice.dat","r"); for($aa=0;!feof($a);$aa++) $fns[$aa] = fgets($a); fclose($a); $ncc = 0; while($ncc < $nsc && $fns[$ncc]) { $fdl[$n] = substr($fns[$ncc], 6); $fdn[$n] = substr($fns[$ncc], 0, 6); $fda[$n] = $ida; $n--; $ncc++; } } } $i = 0; $fn = fopen($dxr.$idd."/no.dat","r"); $fl = fopen($dxr.$idd."/list.dat","r"); if($bodd) $fb = fopen($dxr.$idd.$bodd,"r");else $fb = 0; while($i < $end) { $fno = fgets($fn); if($n == 0) break; if($fno == "" || $fno == "\n") { list($ida,$fn,$fl,$fb) = data6($ida,array($fn,$fl,$fb),0); if($ida == 'q') break;else $xx = $ida; } else { if($i >= $start && $fno[6] != 'a') { $fda[$n] = $ida; $fdn[$n] = $fno; $fdl[$n] = fgets($fl); if($bodd) {$fbo = fgets($fb);$fdb[$n] = strcut($fbo, $len);if($sss[54] && $wdth[7][0]) $faf[$n] = substr($fbo,strpos($fbo,"\x1b"));} $fdu[substr($fno,0,6)] = 1; $n--; } else { if($fno[6] == 'a') $end++; fgets($fl); if($bodd) fgets($fb); } $i++; } } fclose($fn); fclose($fl); if($bodd) fclose($fb); }} // 415 $ida = ''; $fu = fopen($dxr.$id."/upload.dat","r"); while($fuo = substr(fgets($fu),0,6)) {if(isset($fdu[$fuo]) && $fdu[$fuo] == 1) $fdu[$fuo] = 3;} fclose($fu); if($wdth[7][4]) { $fr = fopen($dxr.$id."/new_rp.dat","r"); while(!feof($fr)){ $fro = fgets($fr); $frn = substr($fro,0,6); if(trim($frn) && (_VAR($fdu[$frn]) == 1 || $fdu[$frn] == 3)) { if(substr($fro,34,10) > $sett[62]) $fdu[$frn] += 1; }} fclose($fr); } // 게시판 목록 윗부분 if(_VAR($fcct)) $fct=$fcct; if(!_VAR($sum)) $sum=$fct; else $fct--; if(_VAR($fno) !== 'a') { if(_GET('desc') == 'asc') $fno = $isnt*($gp-1) + 1; else $fno = $fct - $isnt*($gp-1); if(_VAR($nsc)) $fno = $fno + $nsc; } $ctgs = ""; if($type != 'd') { if($wdth[7][30]) { if(!$sss[53]) { $ctgs .= "<a href=\"#\" title=\"제목형 목록\" class=\"aabcg\" onclick=\"this.blur();locato('type','a')\"><img src=\"icon/al.gif\" alt=\"목록형\" class=\"abcg\" /></a> <a href=\"#\" title=\"본문형 목록\" class=\"aabcg\" onclick=\"this.blur();locato('type','b')\"><img src=\"icon/bl.gif\" alt=\"본문형\" class=\"abcg\" /></a> <a href=\"#\" title=\"요약형 목록\" class=\"aabcg\" onclick=\"this.blur();locato('type','c')\"><img src=\"icon/cl.gif\" alt=\"요약형\" class=\"abcg\" /></a> <a href=\"#\" title=\"갤러리형 목록\" class=\"aabcg\" onclick=\"this.blur();locato('type','g')\"><img src=\"icon/gl.gif\" alt=\"갤러리형\" class=\"abcg\" /></a> <a href=\"#\" title=\"달력형 목록\" class=\"aabcg\" onclick=\"this.blur();locato('type','k')\"><img src=\"icon/kl.gif\" alt=\"달력형\" class=\"abcg\" /></a>"; } if($wdth[7][35]) $ctgs .= "\n<a href=\"#\" title=\"로그인\" class=\"aabcg\" onclick=\"this.blur();rhref('?member_login=' + encodeURIComponent(document.passe.request.value))\"><img src=\"icon/ml.gif\" alt=\"로그인\" class=\"abcg\" /></a>"; if($wdth[7][34] == '1') { $ctgs .= "\n<select class='t8' onchange='locato(\"date\",this.options[this.selectedIndex].value)'><option value=''>월별목록</option>"; $fr = fopen($dxr.$id."/date.dat","r"); while(!feof($fr)){ if($fro = trim(fgets($fr))){ $ymdn = substr($fro, 0, 4)."·".substr($fro, 4, 2)." (".substr($fro, 6).")"; $ym = substr($fro,0,6); if($_GET['date'] && substr($_GET['date'],0,6) == $ym) $ctgs .= "<option value='{$ym}' selected='selected' style='background:#000;color:#fff'>$ymdn</option>"; else $ctgs .= "<option value='{$ym}'>$ymdn</option>"; }} $ctgs .= "</select>"; } if($ctg && $sss[27] == '1') { $ctgs .= "\n<select id='ctt' class='t8' onchange=\"locato('ct',this.options[this.selectedIndex].value)\">"; $ctgs .= " <option value='' class='t8'>분류</option>"; for($i = 1; $i <= $ctl; $i++){ $it = str_pad($i,2,0,STR_PAD_LEFT); if($ctg[$it]) $ctgs .= " <option value='{$it}' class='t8'>".preg_replace("`<[^>]+>`","",$ctg[$it])." ({$ctgn[$it]})</option>"; } $ctgs .= "</select>"; } if($sss[45] && $sss[47] && !$_GET['keyword'] && !$_GET['c']) { function arraydsp($odr) { if($_GET['arrange'] == $odr) { if($_GET['desc'] == 'asc') return "style='background:#7df;'"; else return "style='background:#000;color:#fff'"; }} $ctgs .= "\n<select class='t8' onchange='arrange(this.options[this.selectedIndex].value);'> <option value='' class='t8'>정렬</option> <option value='no' class='t8' ".arraydsp('no').">번호</option> <option value='subject' class='t8' ".arraydsp('subject').">제목</option> <option value='name' class='t8' ".arraydsp('name').">이름</option> <option value='date' class='t8' ".arraydsp('date').">날짜</option> <option value='view' class='t8' ".arraydsp('view').">조회</option> <option value='rp' class='t8' ".arraydsp('rp').">덧글</option>"; if($sss[60]) $ctgs .= "\n<option value='appr' class='t8' ".arraydsp('appr').">추천</option>"; if($sss[61]) $ctgs .= "\n<option value='oppo' class='t8' ".arraydsp('oppo').">비추</option>"; if($wdth[7][5]) $ctgs .= "\n<option value='point' class='t8' ".arraydsp('point').">평점</option>"; $ctgs .= "\n<option value='hot' class='t8' ".arraydsp('hot').">활성</option>\n</select>"; } } if($sss[27] == '2' && $ctg) { $ct_list = "<div class='ct_vtc'>"; foreach($ctg as $ii => $category) { if($category) { if($_GET['ct'] && $_GET['ct'] == $ii) $linK = 'slctd'; else $linK = ''; $ct_list .= "<input type='button' class='{$linK}' title='{$ctgn[$ii]}' onclick='locato(\"ct\",\"{$ii}\")' value='".preg_replace("`<[^>]*>`","",$category)."' />"; }} $ct_list .= "</div>"; }} else $wdth[7][30] = 0; /* 목록공통 상단 시작 */ $wtdh = $srwdth - 6; if(_VAR($otype) && $otype == 'k') $_GET['p'] = $calp; if($type == 'k') { include('include/list_calendar.php'); } else { $sr_list = tagcut('list',$srkin); $list_top = tagcut('list_top',$sr_list); if(_VAR($ct_list)) $list_top = str_replace("<#ct_list#>",$ct_list,$list_top); if($wdth[7][30] == '1') $list_top = str_replace("<#icoselect#>",$ctgs,$list_top); $srkiin = preg_replace("`<#[^#]+#>`","",$list_top); $sr_cols = tagcut('list_head_cols',$sr_list); if($sr_cols) { function listr($xt) { global $sss; $s3859['no'] = $sss[38]; $s3859['name'] = $sss[39]; $s3859['date'] = $sss[40]; $s3859['visit'] = $sss[41]; $s3859['appr'] = $sss[42]; $s3859['oppo'] = $sss[59]; return $s3859[$xt]; } $srcl = explode("<col ",$sr_cols); for($i=0;isset($srcl[$i]);$i++) { if($srcp = strpos($srcl[$i],'px')) { $srcw = substr($srcl[$i],7,$srcp - 7); if($srcw < 200) { if(substr($srcl[$i-1],-2) == '#>') $srclw[substr($srcl[$i-1],-6,4)] = $srcw; else $wtdh -= $srcw; }} if($i > 0) {$ix = $i -1;if(substr($srcl[$ix],-2) == '#>') {if(strpos($srcl[$i],'<!--/-->') !== false) {if($xtd = strpos($srcl[$ix],'<#x_')) {$xtd = substr($srcl[$ix],$xtd+4,-2);if(listr($xtd)) {if(!_VAR($xtx)) $xtx = $xtd;$xxt = $xtd;}}} else $xxt = '';}} } } else $srclw = array('isct'=>0,'x_no'=>0,'name'=>0,'date'=>0,'isit'=>0,'appr'=>0,'oppo'=>0); if($ctg && $sss[48]) {$isct = 1;$wtdh -= $srclw['isct'];} // 게시판에 설정된 분류이름이 있으면 else {$sr_list = str_replace("<#isct#>","<;>",$sr_list);$isct = 0;} $cols = $i - 7 + $sss[38] +$sss[39] +$sss[40] +$sss[41] +$sss[42] + $isct; $sr_list = str_replace("<#cols#>",$cols,$sr_list); if($type == 'b') $list_head = tagcut('list_head_b',$sr_list); else if($type == 'c') $list_head = tagcut('list_head_c',$sr_list); else if($type == 'g') $list_head = tagcut('list_head_g',$sr_list); else if($type == 'd') { $list_head = tagcut('list_head_d',$sr_list); if($sss[24] != 'a' && $sss[24] <= $mbr_level) { if($sett[82] < 3 || ($mbr_no && $sett[82] != 5)) $list_head = str_replace("<#isatspm#>","<;>",$list_head); else {$list_head = str_replace("<#pno#>",$uzip,$list_head);} $list_head = str_replace("<#yname#>",$uzname,$list_head); $list_head = str_replace("<#ypass#>",$uzpass,$list_head); $gwrt = "<input type='hidden' name='id' value='{$id}' />"; $gwrt .= "<input type='hidden' name='p' value='{$_POST['p']}{$_GET['p']}' />"; $gwrt .= "<input type='hidden' name='pno' value='{$uzip}' />"; $gwrt .= "<input type='hidden' name='spm' value='{$uzip}' />"; $list_head = str_replace("<#gwrt#>",$gwrt,$list_head); } else $list_head = str_replace("<#gwrt#>","<script type='text/javascript'>document.guest_.style.display='none';</script>",$list_head); ?> <script type="text/javascript" src="include/guest.js"></script> <?php } if(!_VAR($list_head) || $type === 'a'){ if($type !== 'a') {$type = 'a';if($_GET['type']) $_GET['type'] = 'a';} if(!$sss[38]) $sr_list = str_replace('<#x_no#>','<;>',$sr_list);else $wtdh -= $srclw['x_no']; if(!$sss[39]) $sr_list = str_replace('<#x_name#>','<;>',$sr_list);else $wtdh -= $srclw['name']; if(!$sss[40]) $sr_list = str_replace('<#x_date#>','<;>',$sr_list);else $wtdh -= $srclw['date']; if(!$sss[41]) $sr_list = str_replace('<#x_visit#>','<;>',$sr_list);else $wtdh -= $srclw['isit']; if(!$sss[42]) $sr_list = str_replace('<#x_appr#>','<;>',$sr_list);else $wtdh -= $srclw['appr']; if(!$sss[59]) $sr_list = str_replace('<#x_oppo#>','<;>',$sr_list);else $wtdh -= $srclw['oppo']; $list_a = tagcut('list_head_a',$sr_list); if($xtx) $list_a = str_replace('<#x_'.$xtx.'#><td','<td class="list_tf"',$list_a); else $list_a = str_replace('<td ','<td class="list_tf" ',$list_a); if($xxt) $list_a = str_replace('<#x_'.$xxt.'#><td','<td class="list_th"',$list_a); else $list_a = str_replace('<td ','<td class="list_th" ',$list_a); $sr_cols = tagcut('list_head_cols',$sr_list); $list_head = $sr_cols.$list_a; } $srkiin .= $list_head; if($newwin) {$rrt = $rt;$rt = $newwin;} if($fct > 0){ if(_VAR($fdn) && count($fdn) > 0){ $ii = 0; $iii = 0; if($type == 'c') $list_bodyy = tagcut('list_body_c',$sr_list); else if($type == 'b') $list_bodyy = tagcut('list_body_b',$sr_list); else if($type == 'g') $list_bodyy = tagcut('list_body_g',$sr_list); else if($type == 'd') $list_bodyy = tagcut('list_body_d',$sr_list); if(!_VAR($list_bodyy) || $type === 'a') $list_bodyy = tagcut('list_body_a',$sr_list); $mn = ''; for($i = $isnt; $i > 0; $i--) { if($fdn[$i][9] != "\x1b") { $mn[] = substr($fdn[$i],9,strpos($fdn[$i],"\x1b") - 9); } } $fmm = array(); if(is_array($mn)) { $fim = fopen($dim,"r"); while($fm = fgets($fim)) { $fmo = (int)substr($fm,0,5); if(in_array($fmo, $mn)) { $fmm[$fmo] = explode("\x1b",$fm); } } fclose($fim); } if($sss[54] && $wdth[7][0]) { function addlist($return,$val) { $val = explode("\x1b",$val); $addf = count($val); for($d = 1;$d < $addf;$d++) { $return = str_replace("<#addfield_".$d."#>",$val[$d],$return); } return $return; }} for($i = $isnt; $i > 0; $i--) { if(trim($fdn[$i])){ $zzz = explode("\x1b",$fdn[$i]); $flo = explode("\x1b", $fdl[$i]); $no6 = substr($zzz[0], 0, 6); $ctn = substr($zzz[0], 6, 2); $mn = substr($zzz[0], 9); if($sss[64]) $flo[1] = '익명'; $name = $flo[1]; $list_body = str_replace("<#xx#>",$fda[$i],$list_bodyy); $wdtt = 0; if($mbr_level == 9) $list_body = str_replace("<#no_check#>","<input type='checkbox' name='cart' value='".$no6."' onclick='uchoice(this)' class='cart' /><input type='hidden' name='ixx' value='".$fda[$i]."' /> ",$list_body); if($type === 'a'){if($flo[4]) {$list_body = str_replace("<#isimg#>","<img src='icon/img.gif' class='mL4 wh13' alt='' />",$list_body);$wdtt += 20;} if($fdu[$no6] > 2) {$list_body = str_replace("<#isfile#>","<img src='icon/f.png' class='mL4 wh13' alt='' />",$list_body);$wdtt += 20;}} $no = (int)$no6; $flo[3] = andamp($flo[3]); if($flo[5]) $flo[5] = str_replace("&","&amp;",$flo[5]); $re_depth = ''; $date = substr($flo[0], 0, 10); $notx = 0; if($sss[54] && $wdth[7][0]) $list_body = addlist($list_body,$faf[$i]); if(false !== strpos($wdth[4], $no."^") && $nsc > 0 && $_GET['p'] == 1) { $notx = ($ii > 0)? 1:2; $list_body = str_replace("<#notice#>","notice",$list_body); $list_body = str_replace("<#fnno#>","<b> 공지</b>",$list_body); $list_body = str_replace("<#nHit#>","-",$list_body); $list_body = str_replace("<#nAppr#>","-",$list_body); $list_body = str_replace("<#nOppo#>","-",$list_body); $ii--; $nsc--; $isntc = 1; } else { $isntc = 0; if($_GET['no'] == $no) { if($type == 'g') $name = "<u>".$name."</u>"; else $fnno = "<img src='icon/slct.gif' border='0' alt='' />"; } else if($fno === 'a') $fnno = $no; else $fnno = $fno; $list_body = str_replace("<#fnno#>",$fnno,$list_body); $list_body = str_replace("<#nHit#>",(int)$zzz[1],$list_body); if($type == 'd') $list_body = imn($mn,ckmdfx(2,3,$zzz,$flo[0]),$list_body,$no,$fda[$i],1); $notxx = ''; if($sss[60] || $sss[61] || $wdth[7][5]) { $nvote = explode('|',$zzz[5]); if($sss[60] || $wdth[7][5]) { if($sss[60]) $ratng = (int)$nvote[0]; else $ratng = ($nvote[0] && $nvote[1])? sprintf("%.1f",$nvote[0]/$nvote[1]*2):0; $list_body = str_replace("<#nAppr#>",$ratng,$list_body); } if($sss[61]) $list_body = str_replace("<#nOppo#>",(int)$nvote[1],$list_body); if($wdth[8][1] && (($wdth[8][1] == 3 && substr($wdth[8],2) <= $nvote[0]) || ($wdth[8][1] == 4 && substr($wdth[8],2) <= $ratng) || ($wdth[8][1] == 5 && ($wdth[7][5] && substr($wdth[8],2) <=$nvote[1] || !$wdth[7][5] && substr($wdth[8],2) <=$nvote[0] + $nvote[1])))) $notxx = 2; } if($notxx == 2 || ($wdth[8][1] == 1 && substr($wdth[8],2) <= $zzz[1]) || ($wdth[8][1] == 2 && substr($wdth[8],2) <= $zzz[2])) {$notxx = "<img src='icon/hot.gif' class='mL4' alt='' />";$wdtt += 25;} else $notxx = ''; if($wdth[7][4] && ($date >= $sett[62] || $fdu[$no6] == 2 || $fdu[$no6] == 4)) {$list_body = str_replace("<#isnew#>","<img src='icon/new.gif' class='mL4' alt='' />".$notxx,$list_body);$wdtt += 25;} else if($notxx) $list_body = str_replace("<#isnew#>",$notxx,$list_body); } if(_GET('search') == 's') $flo[3] = skword($flo[3]); $zzz08 = (int)$zzz[0][8]; $secret = $authority_read; if($zzz08 > 0) { if(($zzz08 <= $mbr_level) || ($mn && $mn == $mbr_no) || (!$mn && $_COOKIE["scrt_".$no.$id] == md5($no."_".$sessid.$id))) { if($type == 'g') $flo[3] = "[풀림] ".$flo[3];else $re_depth .= "<img src='icon/unlock.gif' alt='' class='lock' />"; } else { $secret = 2; if($type == 'g') $flo[3] = "[잠김] ".$flo[3];else $re_depth .= "<img src='icon/lock.gif' alt='' class='lock' />"; } } $njtnl = 0; if($secret == 2 || $sss[73] != 4) $fdb[$i] = ''; if($wdth[5][4] == 1 && $secret != 2 && $authority_read && $flo[5]) { $njtnl = 1; $list_body = str_replace("<#no_jslink#>","onclick=\"nwopn('{$flo[5]}')\"",$list_body); $list_body = str_replace("<#target#>","target='_blank'",$list_body); $list_body = str_replace("<#no_link#>",$flo[5],$list_body); $fdb[$i] .= "<div class='dv_ea'>링크주소로 연결됩니다</div>"; if($sss[32] == 4) $list_body = str_replace("<#isnlink#>","<;>",$list_body); } else if($secret == 2 || ($secret && $sss[73] != 4)) { if($sss[28] == 4) $fdb[$i] .= "[비밀글]"; else if($type != 'a') {$list_body = str_replace("<#memb#>","<div class='dv_pass' id='lock_{$id}_{$no}'>비밀글입니다.</div>",$list_body); if(!$mn) $onload .= "\nsetTimeout(\"ffpass('{$no}','{$fda[$i]}')\",50);"; }} if(!$isntc && ($zzz[2] > 0 || $zzz[3] > 0 ||($wdth[0][49] != '2' && $zzz[4] > 0))) {$nrp = (int)$zzz[2];if($wdth[9][11]) $nrp += (int)$zzz[3]; if($wdth[0][49] != '2') $nrp += (int)$zzz[4]; if($type === 'a') $wdtt += $sett[28] + strlen($nrp)*5;} else {$list_body = str_replace("<#isnrp#>","<;>",$list_body);$nrp = 0;} if(!$isntc) { if($secret != 2 && $notx != 2 && $sss[28] == 4) $list_body = str_replace("<#oprvw#>","name=\"pv{$ii}\"",$list_body);else if($type == 'g') $list_body = str_replace("<#oprvw#>","name=\"thumb100\"",$list_body); if(!$notx && !$secret && $nrp && $sss[71] == 4) $list_body = str_replace("<#ispvrp#>","<a href='?id={$id}&amp;rp_view={$no}' class='rp'>",$list_body); else $list_body = str_replace("<#ispvrp#>","<a href='#none' class='rp'>",$list_body); if($sss[71] == 4) $cmtlv = "'"; $rsimg = 1; $rissimg = 1; if($secret == 2 || $sss[72] != 4) { if($type == 'g') {$list_body = str_replace("<#simg#>","icon/noimg.gif",$list_body);$rsimg = 0;} else if($type == 'c') {$list_body = str_replace("<#issimg#>","<;>",$list_body);$rissimg = 0;} $flo[4] = ''; } if($secret != 2 && $flo[5]) {$list_body = str_replace("<#rlink#>",$flo[5],$list_body);$wdtt += 22;} if($flo[4]) { if(substr($flo[4], 0, 5) != "http:") { if(substr($flo[4],0,1) == "/") $flo[4] = "exe.php?sls=".$id.$flo[4]; else if(strpos($flo[4],"exe.php") === false) $flo[4] = "exe.php?sls=".$id."/file/".str_replace(" ","+",$flo[4]); } if($rsimg) $list_body = str_replace("<#simg#>",$flo[4],$list_body); if($sss[28] != 4) $flo[4] = ''; } else if($type == 'g' && $rsimg) $list_body = str_replace("<#simg#>","icon/noimg.gif",$list_body); else if($type == 'c' && $rissimg) $list_body = str_replace("<#issimg#>","<;>",$list_body); if($sss[28] == 4 && $notx != 2) $memb .= "\npretxt[{$ii}] = [\"".str_replace('"','\\"',$flo[4])."\",\"\",\"".str_replace('"','\\"',$flo[1])."\",\"".(int)$nrp."\",\"".str_replace('"','\\"',$fdb[$i])."\"];"; if(!$njtnl) $list_body = str_replace("<#no_jslink#>","onclick=\"rhref('{$index}?id={$id}&amp;no={$no}&amp;p={$_GET['p']}{$rt}')\"",$list_body); if($type == 'b') { if(!$_GET['no']) $onload .= "vtrpc[{$no}] = ".(($date < $crtime)? 3:2).";\n"; if(!$wdth[7][32] && $flo[6]) { $tagg = explode(",",$flo[6]); $tag = "<div class='tagg'><img src='icon/tag.gif' alt='' /> "; for($j = 0; trim($tagg[$j]); $j++){ if($_GET['search'] == 't' && $_GET['keyword'] == $tagg[$j]) $tagg[$j] = "<span class='keyword'>{$tagg[$j]}</span>"; $tag .= "<a href='{$index}?id={$id}&amp;search=t&amp;keyword=".urlencode($tagg[$j])."&amp;p=1'>{$tagg[$j]}</a>, "; } $tag = substr($tag, 0, -2)."</div>"; $list_body = str_replace("<#tag#>",$tag,$list_body); } $list_body = str_replace("<#nReply#>",(int)$zzz[2],$list_body); $list_body = str_replace("<#nTrb_out#>",(int)$zzz[3],$list_body); $list_body = str_replace("<#nTrb_in#>",(int)$zzz[4],$list_body); $list_body = str_replace("<#uplist#>",uplist($no),$list_body); } else if($type == 'd') { if((!$mn || $sss[44] < 3) && ($mbr_level == 9 || ($sss[44] != 2 && $sss[44] != 9 && ($mbr_level || $sss[44] == 0 || $sss[44] == 7)))) $list_body = str_replace("<#ipr#>",trim(substr($flo[0], 10, 15)),$list_body); else $list_body = str_replace('<#isipr#>','<;>',$list_body); $list_body = str_replace('<#scrt#>',$zzz[0][8],$list_body); } } if($flo[5] == '' || $secret == 2 || $sss[32] != 4) $list_body = str_replace("<#isnlink#>","<;>",$list_body); if(!$njtnl) { if($aview == 6) { if($isie == 1) $list_body = str_replace("<#no_link#>","#\" onclick=\"aview('{$id}','{$no}','{$xx}')",$list_body); else $list_body = str_replace("<#no_link#>","#\" onclick=\"alert('IE에서만 보입니다')",$list_body); } else $list_body = str_replace("<#no_link#>","{$index}?id={$id}&amp;no={$no}&amp;p={$_GET['p']}{$rt}",$list_body); } if(isset($zzz[6][0]) && $zzz[6][0] > 0) { for($r = $zzz[6][0];$r > 0; $r--) $re_depth = "&nbsp;&nbsp; {$re_depth}re:"; $re_depth = "<span class='t8'>{$re_depth}</span> "; } if($isct && $ctg[$ctn]) { $list_body = str_replace("<#ct_no#>","{$ctn}",$list_body); $list_body = str_replace("<#ct_name#>","{$ctg[$ctn]}",$list_body); } else $list_body = str_replace("<#isnct#>","<;>",$list_body); $list_body = str_replace("<#subject#>",$flo[3],$list_body); $list_body = str_replace("<#re_depth#>",$re_depth,$list_body); $list_body = str_replace("<#no#>",$no,$list_body); $list_body = str_replace("<#ii#>",$ii,$list_body); if($mn) $hmpg = $fmm[$mn][10];else if($type == 'd' && $flo[5]) $hmpg = $flo[5];else $hmpg = ''; $list_body = str_replace("<#name#>",name($name, $mn, 0, 1, $hmpg),$list_body); $list_body = str_replace("<#tname#>",name($name, $mn, 0, 0, $hmpg),$list_body); if($type === 'a'){ if($date > 0) $list_body = str_replace("<#date#>",date("Y.m.d", $date),$list_body); $list_body = str_replace("<#nrp#>",$nrp,$list_body); $list_body = str_replace("<#cno#>",$iii %2,$list_body); if($ismobile != 2 && !$sett[77]) { $wdtt = $wtdh - $wdtt; if($bwr == 'ie6') $list_body = str_replace("<#wtdh#>","width:expression((this.scrollWidth < {$wdtt})? '':'{$wdtt}px')",$list_body); else $list_body = str_replace("<#wtdh#>","max-width:{$wdtt}px",$list_body); }} else { if($date > 0) $list_body = str_replace("<#date#>",date("Y.m.d H:i", $date),$list_body); $list_body = str_replace("<#memb#>",nocopy($fdb[$i]),$list_body); $list_body = str_replace("<#nrp#>",(int)$nrp,$list_body); } $srkiin .= $list_body; $ii++; $iii++; } if($fno !== 'a') { if($_GET['desc'] == 'asc') $fno++; else $fno--; } } } else if($_GET['p'] > 1) $onload .= "locato('p','".($_GET['p'] - 1)."','');\n"; } // 게시판 목록 아랫부분 $srkin = tagcut('list_tail',$sr_list); if($type != 'g' && $type != 'b' && $type != 'd') $srkin = str_replace('<#gdb#>','<;>',$srkin); else if($type == 'g') $srkin = str_replace('<#gdb#>','</td></tr>',$srkin); else $srkin = str_replace('<#surl#>','?section='.$section,$srkin); if($wdth[7][32] || $sss[26] == 'd') $srkin = str_replace('<#sss26#>','<;>',$srkin); if($sss[26] == 'd' || $sss[24] === 'a' || ($sss[63] && $mbr_level != 9) || $sss[24] > $mbr_level) { $srkin = str_replace('<#isrss#>','<;>',$srkin); $srkin = str_replace('<#isnrss#>','<;>',$srkin); } else if($sss[63]) $srkin = str_replace('<#isnrss#>','<;>',$srkin); else $srkin = str_replace('<#isrss#>','<;>',$srkin); if($wdth[7][30] == '2') $srkin = str_replace("<#icoselect#>",$ctgs,$srkin); $srkiin .= $srkin; if($inclwt=inclvde($srkiin)) foreach($inclwt as $inxv) {if($inxv[0] == 1) eval($inxv[1]);else if($inxv[0] == 2) {if($sett[92][0] == '2' || $sett[92][0] == '3') $gmtime = getmicrotime();include($inxv[1]);if($sett[92][0] == '2' || $sett[92][0] == '3') echo "<!--".$inxv[1]." 처리시간:: ".(getmicrotime() - $gmtime)." -->";}else {?><?php echo $inxv[1]?><?php }} } // 610 ?> <table cellpadding='0px' cellspacing='0px' width='<?php echo $srwdthx?>'> <?php if($sss[30]) { if($_GET['keyword'] && $_GET['search'] != 'ip' && $_GET['search'] != 'rip') $onload .= "document.sform.keyword.value = '{$gkeyword}';\ndocument.sform.search.value = '{$_GET['search']}';\n"; ?> <tr><td> <?php // 목록번호 출력 if($newwin) $rt = $rrt; $fct += (int)$nscc; if($otype == 'k') $allp = $mcnt; else $allp = (int)(($fct - 1)/ $isnt) + 1; if($ismobile == 2) pagen('p',$allp,5,$sum); else pagen('p',$allp,10,$sum); ?> </td></tr> <tr><td align="center"> <form method="get" name="sform" class="sform" action="?" style="display:inline"><input type="hidden" name="id" value="<?php echo $id?>" /><input type="hidden" name="ct" value="<?php echo $_GET['ct']?>" /><input type="hidden" name="p" value="1" /> <select name="search" onchange="searchc(this.options[this.selectedIndex].value)" class="sform"><option value="s">제목</option><option value="b">본문</option><option value="t">태그</option><option value="n">이름</option><option value="r">덧글</option></select>&nbsp; <input type="text" name="keyword" class="sform" value="" /> <input type="submit" id="submit" value=" 검색 " class="srbt" /></form> <?php } $rrt = str_replace('amp;','',$rt); if($mbr_level == 9) { if(!$sss[30]) {?><tr><td><?php } if($ismobile == 2) {?><div class='fcler' style='height:10px'></div><?php } ?> <script type="text/javascript" src="include/admin.js"></script> <form name="adselect" method="post" class="sform" action="exe.php" style="float:right;margin-left:-154px"> <input type="hidden" name="selected" /> <input type="hidden" name="idn" value="<?php echo $idn?>" /> <input type="hidden" name="id" value="<?php echo $id?>" /> <input type="hidden" name="p" value="<?php echo $gp?>" /> <input type="hidden" name="xx" value="<?php echo $xx?>" /> <input type="hidden" name="request" value="<?php echo $_SERVER["REQUEST_URI"]?>" /> <select name="perm_vw" onchange="choiced(1)" style="display:none;"><option value="">::권한변경</option><option value="0">모두허용</option><option value="r">rss출력제한</option><option value="1">레벨1</option><option value="2">레벨2</option><option value="3">레벨3</option><option value="4">레벨4</option><option value="5">레벨5</option><option value="6">레벨6</option><option value="7">레벨7</option><option value="8">레벨8</option><option value="9">관리자</option></select> <div style="display:none">번호로 선택 <input type="text" name="ifno" style="width:40px" maxlength="6" /> 부터 <input type="text" name="ifend" style="width:40px" maxlength="6" /> 까지<?php if($_GET['ct']) {?><div class='tr'><span title='분류제한 해제하려면 다음 값을 0으로 바꾸세요.'>분류제한 </span><input type='text' name='ifct' value='<?php echo str_pad($_GET['ct'],2,0,STR_PAD_LEFT);?>' style='width:20px' maxlength='2' /></div><?php }?></div> <div style="display:none"><input type="text" name="newct" onkeyup="if(ekc == 13) submit()" /><input type="button" value=" 생성 " onclick="submit()" class="srbt" /></div> <select name="changeto" onchange="choiced(1)" style="display:none;"> <option value="">분류선택</option> <option value="00">::분류없음</option> <?php for($i = 1; $i <= $ctl; $i++){ $i = str_pad($i, 2, 0, STR_PAD_LEFT); if(!$ctg[$i]) $ctg[$i] = '_새 분류_'; ?> <option value="<?php echo $i?>"><?php echo preg_replace('`<[^>]+>`','',$ctg[$i])?></option> <?php } ?> </select> <select name="moveto" onchange="choiced(1)" style="display:none;"> <option value="">게시판선택</option> <?php foreach($fsbs as $mid => $val) { if($mid != $id) { ?> <option value="<?php echo $mid?>"><?php echo $mid?></option> <?php } } ?> </select> <div id="addtagdv" style="display:none;"><input type="text" name="addtag" value="" style="width:100px" /> <input type="button" onclick="choiced(1)" value="태그추가" class="srbt" /></div> <input type="button" onclick="choice()" value="전체선택" class="srbt" /> <select name="exc" onchange="choiced(0)"> <option value=""></option> <option value="manage">게시판 관리</option> <option value="datafile">파일 관리</option> <option value="cteditwin" class="FC">분류 편집창</option> <option value="hundred">목록 갯수 100</option> <option value="range">번호로 범위선택</option> <option value="change" class="FC">분류 이동</option> <option value="move" class="EA">게시판 이동</option> <option value="copy" class="EA">게시판 복사</option> <option value="delete" class="FC">게시물 삭제</option> <option value="delete_rp" class="FC">덧글 삭제</option> <option value="delete_rtb" class="FC">엮인글 삭제</option> <option value="delete_stb" class="FC">엮은글 삭제</option> <option value="delete_body" class="FC">본문 삭제</option> <?php if($_GET['ct']) {?> <option value="deletect" class="FC">분류글 모두 삭제</option><?php }?> <option value="view_info" class="EA">선택 게시물 정보</option> <option value="limit">읽기권한 변경</option> <?php if($xx == 0){ ?> <option value="notc_add">공지 등록</option> <option value="notc_dell">공지 제거</option> <?php } ?> <option value="modify_rp" class="EA">덧글 정리</option> <option value="modify_newrp" class="EA">최근덧글정리</option> <option value="modify_tag" class="EA">태그 정리</option> <option value="modify_date" class="EA">날짜 정리</option> <option value="modify_ct" class="EA">분류 정리</option> <option value="modify_upload" class="EA">업로드 정리</option> <option value="modify_cnt" class="EA">게시물수 정리</option> <option value="modify_link" class="FC">링크 중복글 삭제</option> <option value="delete_thumb">썸네일 삭제</option> <option value="delete_lnk">링크 삭제</option> <option value="delete_tag">태그 삭제</option> <option value="delete_ip">본문IP 삭제</option> <option value="modify_time" class="FC">게시물 재배치</option> <option value="add_tag" class="FC">태그 추가</option> </select></form><div class="fcler"></div></td></tr> <?php } ?> <tr><td> <?php if(@filesize("skin/".$wdth[2]."/maker.txt")) { ?><div style='text-align:right' class='f8'>skin by <?php echo join('',file("skin/".$wdth[2]."/maker.txt"))?></div><?php } ?> </td></tr> <tr><td><iframe id='tag' src='' style='display:none;width:<?php echo $srwdthx?>;height:30px' frameborder='0'></iframe> </td></tr> </table> <?php } else { // 363 ?><div class='dv_login' id='authority_list'></div><?php $onload .= "\nsetTimeout(\"$('authority_list').innerHTML=$('srlogin').innerHTML + '<br />목록 보기 권한이 없습니다.<br />'\",100);"; $srlogin = 1; } ?> <script type='text/javascript'> //<![CDATA[ function frite(reply) { <?php if($sss[24] === 'a' || $sss[24] > $mbr_level) {?>alert('게시물 작성권한이 없습니다.'); <?php } else { if($_GET['ct']) $tmp = "&amp;ct=".$_GET['ct']; else $tmp = ''; ?> if(reply && '<?php echo $sss[54]?>' == '0' && '<?php echo $sss[55]?>' == '1') { <?php if($s7116 === 1 && $dctime > $cuttime[$sett[71][20]]) {?>alert('시간 경과로 차단되었습니다.');return;<?php }?> rhref('exe.php?id=<?php echo $id?>&amp;depth=' + reply + '&amp;p=<?php echo $_GET['p']?><?php echo $tmp?>&amp;write=<?php echo $_GET['no']?>'); } else if(!reply) rhref('exe.php?id=<?php echo $id?>&amp;p=<?php echo $_GET['p']?><?php echo $tmp?>&amp;write=new'); <?php }?> } <?php if($sss[63] && $sss[24] !== 'a' && $sss[24] <= $mbr_level){ ?> function rss(x) { if(x == 1) location.href='exe.php?id=<?php echo $id?>&read=1'; else popup('admin.php?rss=<?php echo $id?>',480,200); } <?php } ?> function arrange(xx) { <?php if($sss[47]){?> var yy; if(('<?php echo $gkeyword?>' == '' && '<?php echo $_GET['c']?>' == '') || confirm('검색을 중단하고 항목별 정렬로 전환하시겠습니까')) { if('<?php echo $_GET['arrange']?>' == xx && '<?php echo $_GET['desc']?>' == 'desc') yy = 'asc'; else yy = 'desc'; var x = location.search.slice(1).replace(/&keyword=[^&]*/gi,'').replace(/&search=[^&]*/gi,'').replace(/&arrange=[^&]*/gi,'').replace(/&desc=[^&]*/gi,'').replace(/&p=[^&]*/gi,'&p=1'); location.href='?' + x + '&desc=' + yy+ '&arrange=' + xx; } <?php }?> } function vwrp(no) { var comx = $('comment_' + no); if(comx) { if(comx.style.display == 'block') { comx.style.display = 'none'; } else { comx.contentWindow.location.replace('<?php echo $index?>?id=<?php echo $id?><?php echo $rrt?>&comment=' + no); comx.style.display = 'block'; }}} if('<?php echo $_GET['p']?>' && '<?php echo $sss[30]?>' && $('ctt')) $('ctt').value='<?php echo $_GET['ct']?>'; if('<?php echo $xx?>' != '' && $('xxx')) $('xxx').value='<?php echo $xx?>'; if('<?php echo $_GET['date']?>' && $('mmm')) $('mmm').value='<?php echo $_GET['date']?>'; <?php if(!$wdth[7][32] && $_GET['search'] == 't' && $_GET['keyword'] && $_GET['p'] == '1') $onajax = "&tglus=".urlencode($_GET['keyword']); if($type=='d' && $_GET['rp']) $onload .= "\nvwrp('{$_GET['rp']}');"; ?> //]]> </script> <?php } else if(!file_exists($ds)) { // 315 ?><script type='text/javascript'>location.href='admin.php';</script><?php } else { ?> <table id='srgate' cellspacing='<?php echo $sett[39]?>px' cellpadding='0px' width='<?php echo $srwdthx?>' style='table-layout:fixed'> <?php if(($_GET['findw'] = trim($_GET['findw']))) { if($sett[10] == '1' || $sett[10] == '3') $linktarget = "target='_blank'"; if(!$_GET['p']) $_GET['p'] =1; $np = $_GET['p'] + 1; $acook = str_replace(" ","`",$_GET['findw']."_p".$_GET['p']); if($_GET['p'] > 1) { $cookp = $_GET['p'] - 1; $cookp = str_replace(" ","`",$_GET['findw']."_p".$cookp); $bcook = explode("_",$_SESSION[$cookp]); } $bc0 = (int)$bcook[0]; $bc1 = (int)$bcook[1]; $bc2 = (int)$bcook[2]; $fndw = explode(" ",$_GET['findw']); function search($an, $bn, $cn, $bx, $erh) { global $fsbs, $dxr, $mbr_level, $acook, $fndw; $n = 0; if(!trim($fndw[0])) return; foreach($fsbs as $mid => $mss) { $n++; if($mid && $mss[12] !== 'a' && $mss[12] <= $mbr_level) { if($n >= $an && $cn <= 20) { $mwth = explode("\x1b",$mss); if($bx) {$ida = $mwth[6] -$bx +1;$idb = "/^".$ida;} if((!$idb || $ida > 0) && file_exists($dxr.$mid.$idb."/no.dat")) { if(!$isb) $isb = 1; $rft = (int)substr($mss, 6, 6); $fl = fopen($dxr.$mid.$idb."/list.dat","r"); $fn = fopen($dxr.$mid.$idb."/no.dat","r"); $fb = fopen($dxr.$mid.$idb."/body.dat","r"); $i = 0; while($i < $rft){ if($i >= $bn){ $zzz = fgets($fn); if(trim($zzz)){ $flo = fgets($fl); $fbo = fgets($fb); if((stristr($flo,$fndw[0]) && (!$fndw[1] || stristr($flo,$fndw[1])) && (!$fndw[2] || stristr($flo,$fndw[2]))) || (stristr($fbo,$fndw[0]) && (!$fndw[1] || stristr($fbo,$fndw[1])) && (!$fndw[2] || stristr($fbo,$fndw[2])))) { if($cn < 20) $erh[$mid][$cn] = array((int)substr($zzz,0,6),$flo); $cn++; } } else break; } else { fgets($fn);fgets($fl);fgets($fb); } $i++; if($cn == 20) {$en=$n;$ei=$i;} else if($cn > 20) break; } fclose($fl); fclose($fn); fclose($fb); } } } } if($isb && $cn >= 20) {$_SESSION[$acook] = $en."_".$ei."_".$bx;} return array($cn,$i,$isb,$erh,$mbn); } ?> <tr><td style='line-height:140%;padding:10px;text-align:left'> <?php $erh = array(); list($ii,$i,$isb,$erh,$mbn) = search($bc0, $bc1, 0, $bc2, $erh); for($f=$bc2 + 1;$isb && $ii < 21;$f++) { list($ii,$i,$isb,$erh,$mbn) = search(0, 0, $ii, $f, $erh); } while(list($key,$val) = @each($erh)) { echo "<div style='margin:5px 0 5px 0px;border-bottom:2px solid #2A5EB2;'><a href='{$index}?id={$key}' style='color:#2A5EB2'><b>게시판 : {$bdidnm[$key]}</b></a></div>"; while(list($vo,$vns) = @each($val)) { $flo = explode("\x1b",$vns[1]); if(!stristr($flo[2],$_GET['findw'])) { echo "<span class='f7' style='color:#D7D7D7'><span style='font-size:6pt'>■</span> ".@date("m-d",substr($flo[0],0,10))."</span>&nbsp;<a href='{$index}?id={$key}&amp;no={$vns[0]}' {$linktarget}>[{$flo[1]}] {$flo[3]}</a><br />"; } } } ?> </td></tr><tr><td> <?php pagen('p',$_GET['p'],10,(($isb && $ii > 20)? '+':'')); ?> </td></tr></table> <?php } else if(_GET('member_login')) { ?> <tr><td> <div class='bd_name'><h2>회원로그인</h2><div><a href='<?php echo $index?>'>HOME</a> &gt; <a href='<?php echo $index?>?member_login=1'>회원로그인</a></div></div> <div class='c1png'> &nbsp; 회원로그인</div> <?php include("include/login.php"); ?> </td></tr></table> <?php } else { // 전체 게시판 최근게시물 if($ismobile == 2) include("include/gate_mobile.php"); else if($sect[$section][1] != 3 && $sect[$section][1] != 6 && $sect[$section][1] != 7 && $sect[$section][1] != 's') { $ida = ''; $nxs = 0; $nwx = 0; $tpn = 0; $iii = 0; include("include/gate.php"); if(trim($srkiin) == "</table>") include("include/login.php"); } else echo "</table>"; } } if($mbr_level == 9 && isset($gtbk2)) {?> <div class="ulselect"> &nbsp; &nbsp; &bull; 관리자기능 &bull; &nbsp; &nbsp; <ul> <li onclick="popup('admin.php?ectgt=<?php echo $section?>',500,410)">대문편집창</li> <li onclick="popup('admin.php?ectgtw=<?php echo $section?>',750,600,'',1)">대문 위지윅편집창</li> <li onclick="popup('admin.php?sect_arr=<?php echo $section?>',610,500)">좌우메뉴 배치창</li> <li onclick="popup('admin.php?fm=widget/sectbtm_<?php echo $section?>', 800, 400)">하단 내용편집 </li> <li onclick="popup('admin.php?fm=module/sectcss_<?php echo $section?>.css', 800, 400)">css 편집</li> <li onclick="nwopn('admin.php?section=1')">- 섹션관리 -</li></ul></div> <?php } else if($id) { ?> <form method="post" action="exe.php" name="passe" id="passf" style="display:none;"> <input type="hidden" name="no" value="<?php echo $_GET['no']?>" /> <input type="hidden" name="pno" value="<?php echo $_GET['no']?>" /> <input type="hidden" name="p" value="<?php echo $_GET['p']?>" /> <input type="hidden" name="id" value="<?php echo $id?>" /> <input type="hidden" name="xx" value="<?php echo $xx?>" /> <input type='hidden' name='request' value='<?php echo $_SERVER['REQUEST_URI']?>' /> <input type='hidden' name='edit' value='<?php echo $_GET['edit']?>' /> <table class="passtb" onmousedown="movem(this);" onmouseup="movem();"> <tr><td>password : <input type="password" onmousemove="ry='';px=0;py=0" name="pass" class="psinput" value="<?php echo $uzpass?>" maxlength='10' /></td></tr> <tr><td><input type="button" value="취소" onclick="fpass()" class="srbt" /> &nbsp; &nbsp; <input type="button" name="editt" value="" onclick="passbmt(this)" class="srbt" /></td></tr></table> </form> <form method="post" action="exe.php" id="ckfma" target="exe"></form> <?php } $skv = ''; if($id) $skv = tagcut('listbottom',$srkn); $skv .= tagcut('bottom',$srkn); if($inclwt=inclvde($skv)) foreach($inclwt as $inxv) {if($inxv[0] == 1) eval($inxv[1]);else if($inxv[0] == 2) {if($sett[92][0] == '2' || $sett[92][0] == '3') $gmtime = getmicrotime();include($inxv[1]);if($sett[92][0] == '2' || $sett[92][0] == '3') echo "<!--".$inxv[1]." 처리시간:: ".(getmicrotime() - $gmtime)." -->";}else {?><?php echo $inxv[1]?><?php }} } if($dxr) { if(!$ismobile && (($sett[16][3] && !$id) || ($id && (($sett[16][5] && $_GET['no']) || ($sett[16][4] && !$_GET['no'])))) && @filesize($dxr."tail")) {if($sett[32]) @readfile($dxr."tail");else include($dxr."tail");} if($sett[26]) include('module/'.$sett[26].'.php'); if($sett[3]) include($sett[3]); } ?> <script type='text/javascript'> //<![CDATA[ <?php echo $memb?> stbLR67 = <?php echo $stbLR67?>; function checkmemo(val) { var mdiv = $('notifv'); var ckmbrp = 0; <?php if($mbr_level && $sett[52] > 1 && $sett[57] != 'a' && $sett[57] <= $mbr_level) { ?> ckmbrp += 2; if(val == 'new_memo') { var alertt = ""; if(('<?php echo $sett[52]?>' == '2' || '<?php echo $sett[52]?>' == '3' || '<?php echo $sett[52]?>' == '5' || '<?php echo $sett[52]?>' == '6')) alertt += "<input type='button' id='confirm_memo' class='srbt' value='쪽지가 도착했습니다' onclick='read(\"get\");hidedv(\"notifv\");' /><div class='fcler'></div>"; if('<?php echo $sett[52]?>' == '3' || '<?php echo $sett[52]?>' == '4' || '<?php echo $sett[52]?>' == '6') alertt += "<embed src='icon/memo.swf' type='application/x-shockwave-flash' autostart='true' loop='0' style='width:1px;height:1px' />"; if(parseInt('<?php echo $sett[52]?>') >= 4) read('get'); mdiv.innerHTML = alertt + moux; mdiv.style.display = 'block'; } <?php } if($sett[89] != 'a' && $sett[89] <= $mbr_level && $id && $wdth[5][0] != 'a' && $wdth[5][0] <= $mbr_level) { ?> if(setop[6] != '' && ono != 0) { if($('comment_' + ono)) { var ifcmeW = $('comment_' + ono).contentWindow; if(ifcmeW.$('rp_time').value) { ckmbrp += 1; rpck = '&no=' + ono + '&xx=' + document.passe.xx.value + '&rps=' + ifcmeW.$('rp_count').value + '&rptime=' + ifcmeW.$('rp_time').value; }}} <?php } $azid = (($id)? $id."&alst=".(int)$lst:1); ?> if(ckmbrp > 0) setTimeout('azax("exe.php?&check_memo=<?php echo $time?>&id=<?php echo $azid?>' + rpck + '&isvcnct=<?php echo $isvcnnct?>",9)',10000); } <?php if($tpn || $nxs) {$sett60 = explode('|',$sett[60]); if($tpn){?> tpn = <?php echo $tpn?>; tabchng = <?php echo $sett60[0]*1000?>; <?php } if($nxs) {?> nwx = <?php echo $nwx?>; newxchng = setInterval("newxrotate()", <?php echo $sett60[1]*1000?>); <?php }}?> function resizeheight(w,h){ if(py[2] != 0) { w = w - parseInt(px[0]) + parseInt(px[1]); h = h - parseInt(py[0]) + parseInt(py[1]); if(w > 300 && h > 100) { ry.style.width = w + 'px'; ry.style.height = h + 'px'; }} else { w = w - parseInt(px[0]) + parseInt(px[1]); h = h - parseInt(py[0]) + parseInt(py[1]); ry.style.left = w + 'px'; ry.style.top = h + 'px'; }} <?php if($id && $aview > 1) {?> function emptyselect() { var issel = ''; if(setop[0] == '2' || setop[1] == 'ie11') {if((issel = window.getSelection()) && issel.toString()) {issel.removeAllRanges();}} else if(setop[0] == '1' && (issel = document.selection.createRange()) && issel.htmlText) document.selection.empty(); document.oncontextmenu = new Function ('return false'); document.ondragstart = new Function ('return false'); document.onselectstart = new Function ('return false'); document.body.style.MozUserSelect = "none"; } <?php $onload .= "\nsetInterval('emptyselect()',700);"; } if($aview > 1) {?> function keyctrl() { alert('ctrlKey 금지'); return false; } function mousedow(e) { setTimeout("mouse_down()",200); if((setop[0] == '1' && event.button == 2) || (setop[0] != '1' && e.which == 3)) {alert('우클릭 차단');return false;} } setInterval('if(document.onmousedown == null){document.onmousedown = mousedow;}',300); <?php if($aview >= 3) {?> function aview(idd,no,xx) { if(idd) { azax('include/aview.php?&id=' + idd + '&dd=' + no + '&xx=' + xx,'avax(ajax)'); }} function avieww(val) { var scrt = parseInt(val.substr(0,3)); var txt = val.substr(4).split("."); var str_1 = ''; var str_2 = ''; var txtl = txt.length; for(var i = 0;i < txtl;i++) { if(!!txt[i]) { str_2 = '0x' + txt[i]; str_1 += String.fromCharCode(str_2 - scrt); }} str_1 = decodeURIComponent(str_1); str_1 = str_1.replace(/\+/g," "); return str_1; } function avax(val) { <?php if($aview > 4) {if($isie == 1) echo "ajaxx=avieww(val);popup('{$index}?block5=1',$('bd_main').offsetWidth,500,1);";} else if($aview == 3) {echo "$('ifr_bdo').innerHTML=avieww(val);";} else {?> var doc = $('ifr_bdo').contentWindow.document; doc.open(); doc.write("<html>"); doc.write("<head>"); doc.write("<link rel='stylesheet' type='text/css' href='skin/<?php echo $srk?>/style.css' />"); doc.write("<style type='text/css'>body {overflow:hidden; font-size:<?php echo $fz?>pt; font-family:'<?php echo $faze?>'; margin:0;-moz-user-select:none}</style>"); doc.write("</head>"); doc.write("<body onload='img_resize()' class='bdo' oncontextmenu='return false' ondragstart='return false' onselectstart='return false'>"); doc.write(avieww(val)); doc.write("<script type='text/javascript'>function img_resize() {var rszimg = document.getElementsByName('img580');if(rszimg) {for(i=rszimg.length -1; i >= 0; i--) {if(rszimg[i].width > <?php echo $sett[11]?>) rszimg[i].style.width = '<?php echo $sett[11]?>px';rszimg[i].style.cursor = 'pointer';}}setTimeout('resize()',100);}"); doc.write("function resize() {if(parent.location.href.indexOf('<?php echo $_SERVER['HTTP_HOST']?>') == -1) document.write();var ht=document.body.scrollHeight + \"px\";parent.$('ifr_bdo').style.height=ht;}<\/script>"); doc.write("</body>"); doc.write("</html>"); doc.close(); $('ifr_bdo').style.width=$('ifr_bdo').parentNode.offsetWidth +"px"; <?php }?> } <?php }} else {?> function mousedow(e) { setTimeout("mouse_down()",200); } <?php }?> document.onclick = mousedow; function setup() { if(!thtck) thtck = 0; thtck += 1; azax("exe.php?&onload=<?php echo $time?><?php echo $onajax?>&id=<?php echo ($id)?$id:1?>&isvcnct=<?php echo $isvcnnct?>",9); if(thtck < 2) { imgview(0); pview = $('pview'); sessno = <?php echo $sessno?>; <?php echo $onload?> <?php if($ismobile == 2) echo "if('{$_COOKIE['scrwdth']}' == '' || '{$_COOKIE['scrwdth']}' != window.screen.availWidth) document.cookie = 'scrwdth=' + window.screen.availWidth;"; if($_GET['ct'] && $_GET['deletect'] && $_GET['ct'] == $_GET['deletect'] && $mbr_level == 9) echo "setTimeout(\"choice();document.adselect.exc.value = 'delete';choiced('delete_ct');\",100);"; ?> } recize(); if(thtck < 6 && !sessno) { if(thtck < 3) setTimeout("if(!sessno) setup()",200); else if(thtck < 5) setTimeout("if(!sessno) setup()",500); else setTimeout("if(!sessno) setup()",1500); }} function lochref(key,val) { var url = "<?php echo $index?>?id=<?php echo $id?><?php echo $rrt?>&" + key + "=" + val; location.href = url; } var reque = ["<?php echo md5($sessid)?>","<?php echo $_SERVER['REQUEST_URI']?>","<?php echo $xx?>",<?php if($sett[93][0] != 4 && ($sett[93][0] == 1 || ($sett[93][0] == 2 && $ismobile) || ($sett[93][0] == 3 && !$ismobile))) echo substr($sett[93],1);?>]; document.onreadystatechange = function(){if(document.readyState == "complete" && !sessno) setup();else if(document.readyState) recize(document.documentElement.offsetWidth);} setTimeout("if(!sessno) setup()",1000); window.onresize = recize; //]]> </script> <script type="text/javascript" src="include/bottom.js"></script> <?php $time_end = getmicrotime(); $timee = $time_end - $time_start; echo "<!--서버처리시간:: $timee -->"; if($ismobile == 3) { ?> <div align="center"> <input type="button" class="msrbt" onclick="history.go(-1)" value="이전" /> <input type="button" class="msrbt" onclick="document.cookie='ckmobile=2';location.reload()" value="모바일버전" /> <input type="button" class="msrbt" onclick="location.href='<?php echo $index?>?member_login=<?php echo urlencode($_SERVER['REQUEST_URI'])?>'" value="<?php echo ($mbr_level)? "로그아웃":"로그인";?>" /> </div> <?php } if(isset($chtid)) { ?> <script type="text/javascript" src="chat_w.php?js=1"></script> <?php } ?> <div id='srlogin'><?php if($srlogin) include("include/login.php");?></div> <div id='curtain' style='display:none'></div> <div id='notifv' style='display:none'></div> </body> </html>
erial/srboard
index.php
PHP
gpl-2.0
67,951
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Wraps a DOMElement allowing for SimpleXML-like access to attributes. * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Element implements ArrayAccess { /** * @var DOMElement */ protected $_element; /** * @var string Character encoding to utilize */ protected $_encoding = 'UTF-8'; /** * @var Zend_Feed_Element */ protected $_parentElement; /** * @var boolean */ protected $_appended = true; /** * Zend_Feed_Element constructor. * * @param DOMElement $element The DOM element we're encapsulating. * @return void */ public function __construct($element = null) { $this->_element = $element; } /** * Get a DOM representation of the element * * Returns the underlying DOM object, which can then be * manipulated with full DOM methods. * * @return DOMDocument */ public function getDOM() { return $this->_element; } /** * Update the object from a DOM element * * Take a DOMElement object, which may be originally from a call * to getDOM() or may be custom created, and use it as the * DOM tree for this Zend_Feed_Element. * * @param DOMElement $element * @return void */ public function setDOM(DOMElement $element) { $this->_element = $this->_element->ownerDocument->importNode($element, true); } /** * Set the parent element of this object to another * Zend_Feed_Element. * * @param Zend_Feed_Element $element * @return void */ public function setParent(Zend_Feed_Element $element) { $this->_parentElement = $element; $this->_appended = false; } /** * Appends this element to its parent if necessary. * * @return void */ protected function ensureAppended() { if (!$this->_appended) { $this->_parentElement->getDOM()->appendChild($this->_element); $this->_appended = true; $this->_parentElement->ensureAppended(); } } /** * Get an XML string representation of this element * * Returns a string of this element's XML, including the XML * prologue. * * @return string */ public function saveXml() { // Return a complete document including XML prologue. $doc = new DOMDocument($this->_element->ownerDocument->version, $this->_element->ownerDocument->actualEncoding); $doc->appendChild($doc->importNode($this->_element, true)); return $doc->saveXML(); } /** * Get the XML for only this element * * Returns a string of this element's XML without prologue. * * @return string */ public function saveXmlFragment() { return $this->_element->ownerDocument->saveXML($this->_element); } /** * Get encoding * * @return string */ public function getEncoding() { return $this->_encoding; } /** * Set encoding * * @param string $value Encoding to use * @return Zend_Feed_Element */ public function setEncoding($value) { $this->_encoding = (string) $value; return $this; } /** * Map variable access onto the underlying entry representation. * * Get-style access returns a Zend_Feed_Element representing the * child element accessed. To get string values, use method syntax * with the __call() overriding. * * @param string $var The property to access. * @return mixed */ public function __get($var) { $nodes = $this->_children($var); $length = count($nodes); if ($length == 1) { return new Zend_Feed_Element($nodes[0]); } elseif ($length > 1) { return array_map(create_function('$e', 'return new Zend_Feed_Element($e);'), $nodes); } else { // When creating anonymous nodes for __set chaining, don't // call appendChild() on them. Instead we pass the current // element to them as an extra reference; the child is // then responsible for appending itself when it is // actually set. This way "if ($foo->bar)" doesn't create // a phantom "bar" element in our tree. if (strpos($var, ':') !== false) { list($ns, $elt) = explode(':', $var, 2); $node = $this->_element->ownerDocument->createElementNS(Zend_Feed::lookupNamespace($ns), $elt); } else { $node = $this->_element->ownerDocument->createElement($var); } $node = new self($node); $node->setParent($this); return $node; } } /** * Map variable sets onto the underlying entry representation. * * @param string $var The property to change. * @param string $val The property's new value. * @return void * @throws Zend_Feed_Exception */ public function __set($var, $val) { $this->ensureAppended(); $nodes = $this->_children($var); if (!$nodes) { if (strpos($var, ':') !== false) { list($ns, $elt) = explode(':', $var, 2); $node = $this->_element->ownerDocument->createElementNS(Zend_Feed::lookupNamespace($ns), $var, htmlspecialchars($val, ENT_NOQUOTES, $this->getEncoding())); $this->_element->appendChild($node); } else { $node = $this->_element->ownerDocument->createElement($var, htmlspecialchars($val, ENT_NOQUOTES, $this->getEncoding())); $this->_element->appendChild($node); } } elseif (count($nodes) > 1) { /** * @see Zend_Feed_Exception */ require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Cannot set the value of multiple tags simultaneously.'); } else { $nodes[0]->nodeValue = $val; } } /** * Map isset calls onto the underlying entry representation. * * @param string $var * @return boolean */ public function __isset($var) { // Look for access of the form {ns:var}. We don't use // _children() here because we can break out of the loop // immediately once we find something. if (strpos($var, ':') !== false) { list($ns, $elt) = explode(':', $var, 2); foreach ($this->_element->childNodes as $child) { if ($child->localName == $elt && $child->prefix == $ns) { return true; } } } else { foreach ($this->_element->childNodes as $child) { if ($child->localName == $var) { return true; } } } } /** * Get the value of an element with method syntax. * * Map method calls to get the string value of the requested * element. If there are multiple elements that match, this will * return an array of those objects. * * @param string $var The element to get the string value of. * @param mixed $unused This parameter is not used. * @return mixed The node's value, null, or an array of nodes. */ public function __call($var, $unused) { $nodes = $this->_children($var); if (!$nodes) { return null; } elseif (count($nodes) > 1) { return $nodes; } else { return $nodes[0]->nodeValue; } } /** * Remove all children matching $var. * * @param string $var * @return void */ public function __unset($var) { $nodes = $this->_children($var); foreach ($nodes as $node) { $parent = $node->parentNode; $parent->removeChild($node); } } /** * Returns the nodeValue of this element when this object is used * in a string context. * * @return string */ public function __toString() { return $this->_element->nodeValue; } /** * Finds children with tagnames matching $var * * Similar to SimpleXML's children() method. * * @param string $var Tagname to match, can be either namespace:tagName or just tagName. * @return array */ protected function _children($var) { $found = array(); // Look for access of the form {ns:var}. if (strpos($var, ':') !== false) { list($ns, $elt) = explode(':', $var, 2); foreach ($this->_element->childNodes as $child) { if ($child->localName == $elt && $child->prefix == $ns) { $found[] = $child; } } } else { foreach ($this->_element->childNodes as $child) { if ($child->localName == $var) { $found[] = $child; } } } return $found; } /** * Required by the ArrayAccess interface. * * @param string $offset * @return boolean */ public function offsetExists($offset) { if (strpos($offset, ':') !== false) { list($ns, $attr) = explode(':', $offset, 2); return $this->_element->hasAttributeNS(Zend_Feed::lookupNamespace($ns), $attr); } else { return $this->_element->hasAttribute($offset); } } /** * Required by the ArrayAccess interface. * * @param string $offset * @return string */ public function offsetGet($offset) { if (strpos($offset, ':') !== false) { list($ns, $attr) = explode(':', $offset, 2); return $this->_element->getAttributeNS(Zend_Feed::lookupNamespace($ns), $attr); } else { return $this->_element->getAttribute($offset); } } /** * Required by the ArrayAccess interface. * * @param string $offset * @param string $value * @return string */ public function offsetSet($offset, $value) { $this->ensureAppended(); if (strpos($offset, ':') !== false) { list($ns, $attr) = explode(':', $offset, 2); // DOMElement::setAttributeNS() requires $qualifiedName to have a prefix return $this->_element->setAttributeNS(Zend_Feed::lookupNamespace($ns), $offset, $value); } else { return $this->_element->setAttribute($offset, $value); } } /** * Required by the ArrayAccess interface. * * @param string $offset * @return boolean */ public function offsetUnset($offset) { if (strpos($offset, ':') !== false) { list($ns, $attr) = explode(':', $offset, 2); return $this->_element->removeAttributeNS(Zend_Feed::lookupNamespace($ns), $attr); } else { return $this->_element->removeAttribute($offset); } } }
trungkienpvt/wordpress
wp-content/themes/ecommerce/inc/Zend/Feed/Element.php
PHP
gpl-2.0
12,600