Ejemplo n.º 1
0
		void GamePad::Update()
		{
			unsigned int connected = 0;

			for (unsigned int i = 0; i < 4; i++)
			{
				XINPUT_STATE state;
				ZeroMemory(&state, sizeof(XINPUT_STATE));
				connected = XInputGetState(i, &state);

				if (connected == ERROR_SUCCESS)
				{
					if (Pads[i]._previousState._packetNumber != state.dwPacketNumber)
					{
						Pads[i]._currentState._packetNumber = state.dwPacketNumber;
						Pads[i]._previousState = Pads[i].Current();
						
						Pads[i]._currentState._dPad = DPad(
							(state.Gamepad.wButtons & 0x00000001) != 0, // Up
							(state.Gamepad.wButtons & 0x00000002) != 0, // Down
							(state.Gamepad.wButtons & 0x00000004) != 0, // Left
							(state.Gamepad.wButtons & 0x00000008) != 0  // Right
						);

						Pads[i]._currentState._start = Button((state.Gamepad.wButtons & 0x00000010) != 0);
						Pads[i]._currentState._back  = Button((state.Gamepad.wButtons & 0x00000020) != 0);

						Pads[i]._currentState._leftThumbStick = ThumbStick(
							Utility::Vector2(state.Gamepad.sThumbLX / 32767.0f, state.Gamepad.sThumbLY / 32767.0f), 
							(state.Gamepad.wButtons & 0x00000040) != 0
						);
						
						Pads[i]._currentState._rightThumbStick = ThumbStick(
							Utility::Vector2(state.Gamepad.sThumbRX / 32767.0f, state.Gamepad.sThumbRY / 32767.0f),
							(state.Gamepad.wButtons & 0x00000080) != 0
						);

						Pads[i]._currentState._leftBumper  = Button((state.Gamepad.wButtons & 0x00000100) != 0);
						Pads[i]._currentState._rightBumper = Button((state.Gamepad.wButtons & 0x00000200) != 0);

						Pads[i]._currentState._a = Button((state.Gamepad.wButtons & 0x00001000) != 0);
						Pads[i]._currentState._b = Button((state.Gamepad.wButtons & 0x00002000) != 0);
						Pads[i]._currentState._x = Button((state.Gamepad.wButtons & 0x00004000) != 0);
						Pads[i]._currentState._y = Button((state.Gamepad.wButtons & 0x00008000) != 0);
										
						if (Pads[i]._currentState._leftTrigger > 0.0f) 
							Pads[i]._currentState._leftTrigger = (state.Gamepad.bLeftTrigger - 30) / 225.0f;
						else Pads[i]._currentState._leftTrigger = 0.0f;

						if (Pads[i]._currentState._rightTrigger > 0.0f)
							Pads[i]._currentState._rightTrigger = (state.Gamepad.bRightTrigger - 30) / 225.0f; 
						else Pads[i]._currentState._rightTrigger = 0.0f;

						XINPUT_VIBRATION tmp;
						tmp.wLeftMotorSpeed = (WORD)std::floor(Pads[i]._currentState._leftMotor * 32767);
						tmp.wRightMotorSpeed = (WORD)std::floor(Pads[i]._currentState._rightMotor * 32767);
						XInputSetState(i, &tmp);
					};
				}
				else
				{
					Pads[i]._previousState = Pads[i].Current();
					Pads[i]._currentState = GamePadState();
				};
			};
		};
Ejemplo n.º 2
0
/*
 * Issue a routing socket message for a single changed destination.
 */
DWORD
rtm_send_dest_change(RTM_ENTITY_HANDLE reh, PRTM_DEST_INFO prdi)
{
#ifdef IPV6_DLL
    struct in6_addr dst;
    struct in6_addr ip;
    struct in6_addr nhip;
#else
    struct in_addr dst;
    struct in_addr ip;
    struct in_addr nhip;
#endif
    int i;
    int dstprefix;
    int nhprefix;
    int type;
    DWORD result;

    if (!prdi)
        return NO_ERROR;

    TRACE1(NETWORK, "RtmDestInfo Destination %p", prdi);

#ifdef IPV6_DLL
    RTM_IPV6_GET_ADDR_AND_LEN(dst.s6_addr, dstprefix, &prdi->DestAddress);
#else
    RTM_IPV4_GET_ADDR_AND_LEN(dst.s_addr, dstprefix, &prdi->DestAddress);
#endif

    /*
     * Determine the nature of the change; whether a route has
     * been added, changed or deleted for the given situation.
     * We look only at the unicast routing view.
     */
    for (i = 0; i < prdi->NumberOfViews; i++) {
	if (prdi->ViewInfo[i].ViewId == RTM_VIEW_ID_UCAST) {
#ifdef IPV6_DLL
	    /*
	     * XXX: Don't filter IPv6 routes [yet].
	     */
#else /* IPv4 */
	    /*
	     * Ignore routes to the all-ones broadcast destination.
	     */
	    if ((dst.s_addr == INADDR_BROADCAST && dstprefix == 32)) {
		TRACE0(NETWORK, "ignoring all-ones broadcast");
		break;
	    }
#ifdef notyet
	    /*
	     * XXX: Ignore multicast routes (for now).
	     */
	    if (IN4_IS_ADDR_MULTICAST(dst.s_addr)) {
		TRACE0(NETWORK, "ignoring multicast route");
		break;
	    }
#endif /* notyet */
#endif /* IPV6_DLL */
	    if (prdi->ViewInfo[i].NumRoutes == 0) {
		TRACE0(NETWORK, "route deleted");
		type = RTM_DELETE;
	    } else if (prdi->ViewInfo[i].NumRoutes == 1) {
		TRACE0(NETWORK, "route added");
		type = RTM_ADD;
	    } else {
		/*
		 * XXX: The route has multiple next-hops. We do not know
		 * which next-hop we should send to the FEA, so do not
		 * process such changes for now.
		 */
		TRACE1(NETWORK, "route change, dest %d nexthops, no msg",
		       prdi->ViewInfo[i].NumRoutes);
		type = 0;
	    }
	    break;  /* stop when unicast route view is dealt with. */
	}
    }
    /*
     * Craft a routing socket message based on the changes.
     * We only allocate memory here if we require it.
     */
    if (type != 0) {
	sockunion_t *sa;
	struct rt_msghdr *rtm;
#ifdef IPV6_DLL
	struct in6_addr nh;
#else
	struct in_addr nh;
#endif
	int maxmsgsize;

	maxmsgsize = sizeof(struct rt_msghdr) + (sizeof(sockunion_t) * 3);
	rtm = malloc(maxmsgsize);
	ZeroMemory(rtm, maxmsgsize);

	sa = (sockunion_t *)(rtm + 1);

	rtm->rtm_msglen = maxmsgsize - sizeof(*sa);
	rtm->rtm_version = RTM_VERSION;
	rtm->rtm_type = type;
	rtm->rtm_addrs = RTA_DST | RTA_NETMASK;

	/* Destination */
#ifdef IPV6_DLL
	sa->sin6.sin6_family = AF_INET6;
	sa->sin6.sin6_addr = dst;
#else
	sa->sin.sin_family = AF_INET;
	sa->sin.sin_addr = dst;
#endif

	/*
	 * Route additions require that we also report the next-hop.
	 * Perform the necessary RTMv2 incantations to look up the
	 * next-hop from the destination reported as changed.
	 * XXX: Better error checking here considered desirable.
	 */
	if (type == RTM_ADD) {
	    PRTM_ROUTE_INFO prri;
	    RTM_NEXTHOP_INFO nhi;

	    rtm->rtm_msglen += sizeof(*sa);
	    rtm->rtm_addrs |= RTA_GATEWAY;

	    /* XXX weird heap malloc. */
	    MALLOC(&prri,
		   RTM_SIZE_OF_ROUTE_INFO(g_ce.rrpRtmProfile.MaxNextHopsInRoute), &result);

	    result = RtmGetRouteInfo(reh, prdi->ViewInfo[i].Route, prri, NULL);
	    if (result != NO_ERROR) {
		TRACE1(NETWORK, "RtmGetRouteInfo() returns %d", result);
	    }

	    result = RtmGetNextHopInfo(reh, prri->NextHopsList.NextHops[0],
				       &nhi);
	    if (result != NO_ERROR) {
		TRACE1(ANY, "Error %u getting next hop", result);
	    }

	    /* Gateway */
#ifdef IPV6_DLL
	    RTM_IPV6_GET_ADDR_AND_LEN(nhip.s6_addr, nhprefix,
				      &nhi.NextHopAddress);
	    ++sa;
	    sa->sin6.sin6_family = AF_INET6;
	    sa->sin6.sin6_addr = nhip;
#else
	    RTM_IPV4_GET_ADDR_AND_LEN(nhip.s_addr, nhprefix,
				      &nhi.NextHopAddress);
	    ++sa;
	    sa->sin.sin_family = AF_INET;
	    sa->sin.sin_addr = nhip;
#endif /* IPV6_DLL */

	    /*
	     * Free the next-hop info structures.
	     */
	    (void)RtmReleaseNextHopInfo(reh, &nhi);
	    (void)RtmReleaseRouteInfo(reh, prri);
	    FREE(prri);
	}

	/* Netmask; comes after gateway in the RTM_ADD case. */
	++sa;
#ifdef IPV6_DLL
	/* XXX: may not be right */
	sa->sin6.sin6_family = AF_INET;
	sa->sin6.sin6_addr.s6_addr = RTM_IPV6_MASK_FROM_LEN(dstprefix);
#else
	sa->sin.sin_family = AF_INET;
	sa->sin.sin_addr.s_addr = RTM_IPV4_MASK_FROM_LEN(dstprefix);
#endif

	broadcast_pipe_message(rtm, rtm->rtm_msglen);
	free(rtm);
    }

    return NO_ERROR;
}
Ejemplo n.º 3
0
BOOL xf_create_window(xfContext* xfc)
{
	XGCValues gcv;
	XEvent xevent;
	int width, height;
	char* windowTitle;
	rdpSettings* settings = xfc->settings;

	ZeroMemory(&xevent, sizeof(xevent));

	width = xfc->sessionWidth;
	height = xfc->sessionHeight;

	if (!xfc->hdc)
		xfc->hdc = gdi_CreateDC(CLRBUF_32BPP, xfc->bpp);

	if (!xfc->remote_app)
	{
		xfc->attribs.background_pixel = BlackPixelOfScreen(xfc->screen);
		xfc->attribs.border_pixel = WhitePixelOfScreen(xfc->screen);
		xfc->attribs.backing_store = xfc->primary ? NotUseful : Always;
		xfc->attribs.override_redirect = False;
		xfc->attribs.colormap = xfc->colormap;
		xfc->attribs.bit_gravity = NorthWestGravity;
		xfc->attribs.win_gravity = NorthWestGravity;

#ifdef WITH_XRENDER
		xfc->offset_x = 0;
		xfc->offset_y = 0;
#endif

		if (settings->WindowTitle)
		{
			windowTitle = _strdup(settings->WindowTitle);
		}
		else if (settings->ServerPort == 3389)
		{
			windowTitle = malloc(1 + sizeof("FreeRDP: ") + strlen(settings->ServerHostname));
			sprintf(windowTitle, "FreeRDP: %s", settings->ServerHostname);
		}
		else
		{
			windowTitle = malloc(1 + sizeof("FreeRDP: ") + strlen(settings->ServerHostname) + sizeof(":00000"));
			sprintf(windowTitle, "FreeRDP: %s:%i", settings->ServerHostname, settings->ServerPort);
		}

#ifdef WITH_XRENDER
		if (settings->SmartSizing && !xfc->fullscreen)
		{
			if (settings->SmartSizingWidth)
				width = settings->SmartSizingWidth;
			if (settings->SmartSizingHeight)
				height = settings->SmartSizingHeight;

			xfc->scaledWidth = width;
			xfc->scaledHeight = height;
		}
#endif

		xfc->window = xf_CreateDesktopWindow(xfc, windowTitle, width, height);

		free(windowTitle);

		if (xfc->fullscreen)
			xf_SetWindowFullscreen(xfc, xfc->window, xfc->fullscreen);

		xfc->unobscured = (xevent.xvisibility.state == VisibilityUnobscured);

		XSetWMProtocols(xfc->display, xfc->window->handle, &(xfc->WM_DELETE_WINDOW), 1);
		xfc->drawable = xfc->window->handle;
	}
	else
	{
		xfc->drawable = DefaultRootWindow(xfc->display);
	}

	ZeroMemory(&gcv, sizeof(gcv));

	if (xfc->modifierMap)
		XFreeModifiermap(xfc->modifierMap);

	xfc->modifierMap = XGetModifierMapping(xfc->display);
	assert(!xfc->gc);
	xfc->gc = XCreateGC(xfc->display, xfc->drawable, GCGraphicsExposures, &gcv);
	assert(!xfc->primary);
	xfc->primary = XCreatePixmap(xfc->display, xfc->drawable, xfc->sessionWidth, xfc->sessionHeight, xfc->depth);
	xfc->drawing = xfc->primary;
	assert(!xfc->bitmap_mono);
	xfc->bitmap_mono = XCreatePixmap(xfc->display, xfc->drawable, 8, 8, 1);
	assert(!xfc->gc_mono);
	xfc->gc_mono = XCreateGC(xfc->display, xfc->bitmap_mono, GCGraphicsExposures, &gcv);
	XSetFunction(xfc->display, xfc->gc, GXcopy);
	XSetFillStyle(xfc->display, xfc->gc, FillSolid);
	XSetForeground(xfc->display, xfc->gc, BlackPixelOfScreen(xfc->screen));
	XFillRectangle(xfc->display, xfc->primary, xfc->gc, 0, 0, xfc->sessionWidth, xfc->sessionHeight);
	XFlush(xfc->display);
	assert(!xfc->image);

	xfc->image = XCreateImage(xfc->display, xfc->visual, xfc->depth, ZPixmap, 0,
			(char*) xfc->primary_buffer, xfc->sessionWidth, xfc->sessionHeight, xfc->scanline_pad, 0);

	return TRUE;
}
Ejemplo n.º 4
0
/*
 * Delete a route from RTMv2 based on a routing socket message.
 * XXX: We should report errors in more detail, e.g. if the
 * route could not be added because it already existed, etc.
 */
int
rtm_delete_route(struct rt_msghdr *rtm, int msgsize)
{
    static const min_msgsize = (sizeof(struct rt_msghdr) +
				(sizeof(sockunion_t) * 2));
    sockunion_t *sa;
    struct in_addr in_dest;
    struct in_addr in_mask;
    int found;
    int i;
    int prefix;
    int retval;
    DWORD result;
    RTM_DEST_INFO di;
    RTM_NET_ADDRESS dest;
    RTM_ROUTE_CHANGE_FLAGS changeflags;

    /*
     * Sanity check message size, fields etc.
     */
    if (!rtm)
	return -1;
    if (msgsize < min_msgsize || (rtm->rtm_msglen < min_msgsize))
	return -1;
    if (rtm->rtm_type != RTM_DELETE)
	return -1;
    if ((rtm->rtm_addrs & (RTA_DST|RTA_NETMASK)) != (RTA_DST|RTA_NETMASK))
	return -1;
    /*
     * Extract destination, netmask and next-hop from routing
     * socket message.
     * XXX: bsd's delete order is: <DST,GATEWAY,NETMASK>
     * XXX: we don't check to see if gateway is present and
     * if so we do not handle it correctly.
     */
    sa = (sockunion_t *)(rtm + 1);
    in_dest = sa->sin.sin_addr;
    ++sa;
    in_mask = sa->sin.sin_addr;

    /*
     * Convert netmask to a prefix length.
     * Convert destination to an RTM_NET_ADDRESS.
     */
    RTM_IPV4_LEN_FROM_MASK(prefix, in_mask.s_addr);
    RTM_IPV4_MAKE_NET_ADDRESS(&dest, in_dest.s_addr, prefix);

    /*
     * Look up the route to be deleted in RTMv2, from those
     * which belong to our protocol, in the unicast view.
     */
    ZeroMemory(&di, sizeof(di));
    di.DestAddress = dest;
    result = RtmGetExactMatchDestination(g_ce.hRtmHandle, &dest,
					 RTM_THIS_PROTOCOL,
					 RTM_VIEW_MASK_UCAST, &di);
    if (result != NO_ERROR) {
	TRACE1(NETWORK, "error %u looking up route to delete", result);
	retval = -1;
	goto out;
    }
    i = 0;
    found = 0;
    for (i = 0; i < di.NumberOfViews; i++) {
	if (di.ViewInfo[i].ViewId == RTM_VIEW_ID_UCAST) {
	    /*
	     * Return a match only if the unicast view for our protocol
	     * contains a single next-hop route to the destination.
	     */
	    if (di.ViewInfo[i].NumRoutes == 1)
		found = 1;
	    break;
	}
    }
    if (!found) {
	TRACE0(NETWORK, "route not found in table");
	retval = -1;
	goto out;
    }

    result = RtmDeleteRouteToDest(g_ce.hRtmHandle, di.ViewInfo[i].Route,
				  &changeflags);
    if (result != NO_ERROR) {
	TRACE1(NETWORK, "error %u deleting route", result);
	retval = -1;
	goto out;
    }

    retval = 0;

  out:
    return (retval);
}
Ejemplo n.º 5
0
/*
 * Create a new instance of a pipe and return a pointer to
 * its instance structure.
 */
pipe_instance_t *
pipe_new(void)
{
    pipe_instance_t *npp;
    int failed;
    DWORD result;

    TRACE0(ENTER, "Entering pipe_new");

    npp = malloc(sizeof(*npp));
    if (npp == NULL)
	return NULL;
    ZeroMemory(npp, sizeof(*npp));

    failed = 1;

    /* XXX buffer management */
    npp->rsize = PIPE_READBUF_SIZE;
    npp->state = PIPE_STATE_INIT;

    InitializeCriticalSection(&npp->rcs);

    /*
     * Create the event object used to signal connection completion.
     */
    npp->cevent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (npp->cevent == NULL) {
	result = GetLastError();
        TRACE1(CONFIGURATION, "Error %u creating event", result);
	goto fail;
    }
    npp->cov.hEvent = npp->cevent;

    /*
     * Create the event object used to signal read completion.
     */
    npp->revent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (npp->revent == NULL) {
	result = GetLastError();
        TRACE1(CONFIGURATION, "Error %u creating event", result);
	goto fail;
    }
    npp->rov.hEvent = npp->revent;

    /*
     * Create the instance of the named pipe itself.
     */
    npp->pipe = CreateNamedPipeA(XORPRTM_PIPENAME,
				 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
				 PIPE_TYPE_MESSAGE, PIPE_INSTANCES, 0, 0,
				 XORPRTM_PIPETIMEOUT, NULL);
    if (npp->pipe == NULL) {
	result = GetLastError();
	TRACE1(CONFIGURATION, "Error %u creating named pipe", result);
	goto fail;
    }

    failed = 0;
  fail:
    if (failed) {
	pipe_destroy(npp);
	npp = NULL;
    }
    TRACE1(ENTER, "Leaving pipe_new %p", npp);
    return (npp);
}
Ejemplo n.º 6
0
DWORD
CE_Create (
    PCONFIGURATION_ENTRY    pce)
{
    DWORD dwErr = NO_ERROR;

    /* initialize to default values */
    ZeroMemory(pce, sizeof(CONFIGURATION_ENTRY));
    pce->dwTraceID = INVALID_TRACEID;

    do {
        /* initialize the read-write lock */
        CREATE_READ_WRITE_LOCK(&(pce->rwlLock));
        if (!READ_WRITE_LOCK_CREATED(&(pce->rwlLock))) {
            dwErr = GetLastError();

            TRACE1(CONFIGURATION, "Error %u creating read-write-lock", dwErr);

            break;
        }

        /* initialize the global heap */
        pce->hGlobalHeap = HeapCreate(0, 0, 0);
        if (pce->hGlobalHeap == NULL) {
            dwErr = GetLastError();
            TRACE1(CONFIGURATION, "Error %u creating global heap", dwErr);

            break;
        }

	/*
         * Initialize the count of threads that are active in subsystem.
         * Create the semaphore released by each thread when it is done;
         * required for clean stop to the protocol.
	 */
        pce->ulActivityCount = 0;
        pce->hActivitySemaphore = CreateSemaphore(NULL, 0, 0xfffffff, NULL);
        if (pce->hActivitySemaphore == NULL) {
            dwErr = GetLastError();
            TRACE1(CONFIGURATION, "Error %u creating semaphore", dwErr);
            break;
        }

        /* Logging & Tracing Information */
        pce->dwTraceID  = TraceRegister(XORPRTM_TRACENAME);

        /* Event Queue */
        INITIALIZE_LOCKED_QUEUE(&(pce->lqEventQueue));
        if (!LOCKED_QUEUE_INITIALIZED(&(pce->lqEventQueue))) {
            dwErr = GetLastError();
            TRACE1(CONFIGURATION, "Error %u initializing locked queue", dwErr);
            break;
        }

        /* Protocol State */
        pce->iscStatus = XORPRTM_STATUS_STOPPED;

    } while (FALSE);

    if (dwErr != NO_ERROR) {
        /* something went wrong, so cleanup. */
        TRACE0(CONFIGURATION, "Failed to create configuration entry");
        CE_Destroy(pce);
    }

    return dwErr;
}
Ejemplo n.º 7
0
/*
 * Add a route to RTMv2 based on a routing socket message.
 * XXX: We should report errors in more detail, e.g. if the
 * route could not be added because it already existed, etc.
 */
int
rtm_add_route(struct rt_msghdr *rtm, int msgsize)
{
    static const proper_msgsize = (sizeof(struct rt_msghdr) +
				   (sizeof(sockunion_t) * 3));
    sockunion_t *sa;
#ifdef IPV6_DLL
    struct in6_addr in6_dest;
    struct in6_addr in6_mask;
    struct in6_addr in6_nexthop;
#else
    struct in_addr in_dest;
    struct in_addr in_mask;
    struct in_addr in_nexthop;
    MIB_IPFORWARDROW ro;
#endif
    int retval;
    int prefix;
    DWORD result;
    RTM_NET_ADDRESS dest;
    RTM_NET_ADDRESS nexthop;
    RTM_NEXTHOP_HANDLE nhh;
    RTM_NEXTHOP_INFO nhi;
    RTM_ROUTE_HANDLE nrh;
    RTM_ROUTE_INFO ri;
    RTM_ROUTE_CHANGE_FLAGS changeFlags;

    /*
     * Sanity check message size, fields etc.
     */
    if (!rtm)
	return -1;
    if (msgsize < proper_msgsize || (rtm->rtm_msglen < proper_msgsize))
	return -1;
    if (rtm->rtm_type != RTM_ADD)
	return -1;
    if ((rtm->rtm_addrs & (RTA_DST|RTA_GATEWAY|RTA_NETMASK)) !=
	(RTA_DST|RTA_GATEWAY|RTA_NETMASK))
	return -1;

    nhh = NULL;
    nrh = NULL;

    /*
     * Extract destination, netmask and next-hop from routing
     * socket message.
     */
#ifdef IPV6_DLL
    sa = (sockunion_t *)(rtm + 1);
    in6_dest = sa->sin6.sin6_addr;
    if (sa->sa.sa_family != AF_INET6)
	return -1;
    ++sa;
    in6_nexthop = sa->sin6.sin6_addr;
    if (sa->sa.sa_family != AF_INET6)
	return -1;
    ++sa;
    in6_mask = sa->sin6.sin6_addr;
    if (sa->sa.sa_family != AF_INET6)
	return -1;
#else
    sa = (sockunion_t *)(rtm + 1);
    if (sa->sa.sa_family != AF_INET)
	return -1;
    in_dest = sa->sin.sin_addr;
    ++sa;
    if (sa->sa.sa_family != AF_INET)
	return -1;
    in_nexthop = sa->sin.sin_addr;
    ++sa;
    if (sa->sa.sa_family != AF_INET)
	return -1;
    in_mask = sa->sin.sin_addr;
#endif

#ifndef IPV6_DLL
    /*
     * Look up the next-hop in the system routing table via
     * IP Helper. If there is no directly connected route we
     * can use to reach the next-hop, then we reject this attempt
     * to add a route, as we need to know the interface index
     * of this route in order to add the new route.
     * XXX This is not good for multihop.
     * XXX IPv6!
     */
    result = GetBestRoute(in_nexthop.s_addr, INADDR_ANY, &ro);
    if (result != NO_ERROR) {
	TRACE1(NETWORK, "error: GetBestRoute() returned %d", result);
	return -1;
    }
#endif

    /*
     * Convert netmask to a prefix length.
     * Convert destination to an RTM_NET_ADDRESS.
     * Convert next-hop to an RTM_NET_ADDRESS.
     * XXX: IPv6 path needs 'get length from mask' macro.
     * XXX: IPv6 path needs interface index.
     */
#ifdef IPV6_DLL
    RTM_IPV6_LEN_FROM_MASK(prefix, in6_mask.s_addr);
    RTM_IPV6_MAKE_NET_ADDRESS(&dest, in6_dest.s_addr, prefix);
    RTM_IPV6_MAKE_NET_ADDRESS(&nexthop, in6_nexthop.s_addr, 128);
#else
    RTM_IPV4_LEN_FROM_MASK(prefix, in_mask.s_addr);
    RTM_IPV4_MAKE_NET_ADDRESS(&dest, in_dest.s_addr, prefix);
    RTM_IPV4_MAKE_NET_ADDRESS(&nexthop, in_nexthop.s_addr, 32);
    /*
     * Fill out the next-hop info structure.
     * Create the next-hop in the RTMv2 table.
     */
    ZeroMemory(&nhi, sizeof(nhi));
    nhi.InterfaceIndex = ro.dwForwardIfIndex;
    nhi.NextHopAddress = nexthop;
#endif /* IPV6_DLL */

    result = RtmAddNextHop(g_ce.hRtmHandle, &nhi, &nhh, &changeFlags);
    if (result != NO_ERROR) {
	TRACE1(NETWORK, "error %u adding nexthop", result);
	retval = -1;
	goto out;
    }

    /*
     * Fill out the RTM_ROUTE_INFO structure.
     * Attempt to add the route.
     */
    ZeroMemory(&ri, sizeof(ri));
    ri.PrefInfo.Metric = XORPRTM_RI_METRIC;
    ri.PrefInfo.Preference = XORPRTM_RI_PREF;
    ri.BelongsToViews = RTM_VIEW_MASK_UCAST;
    ri.NextHopsList.NumNextHops = 1;
    ri.NextHopsList.NextHops[0] = nhh;
    changeFlags = 0;

    result = RtmAddRouteToDest(g_ce.hRtmHandle, &nrh, &dest, &ri, INFINITE,
			       NULL, 0, NULL, &changeFlags);
    if (result != NO_ERROR) {
	TRACE1(NETWORK, "error %u adding route", result);
	retval = -1;
	goto out;
    }

    retval = 0;

  out:
    if (nrh != NULL)
	RtmReleaseRoutes(g_ce.hRtmHandle, 1, &nrh);
    if (nhh != NULL)
	RtmReleaseNextHops(g_ce.hRtmHandle, 1, &nhh);

    return (retval);
}
void CubeMan_Light::Initialize()
{
	D3DXMatrixIdentity(&world);
	ZeroMemory(keyState, sizeof(bool)*NUM_OF_KEY_TYPE);

	D3DXVECTOR2 uvList[36];

	root = new CubeManParts_Light;
	GetCubeUVList(uvList, BODY);
	root->Initialize(D3DXVECTOR3(1.0f, 2.0f, 1.0f), D3DXVECTOR3(0.0f, 0.0f, 0.0f), D3DXVECTOR3(0.0f, 3.0f, 0.0f));
	root->SetTextureUV(uvList);

	CubeManParts_Light* head = new CubeManParts_Light;
	GetCubeUVList(uvList, HEAD);
	head->Initialize(D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXVECTOR3(0.0f, -0.5f, 0.0f), D3DXVECTOR3(0.0f, 1.1f, 0.0f));
	head->SetTextureUV(uvList);
	root->AddChild(head);

	CubeManParts_Light* leftArm = new CubeManParts_Light;
	GetCubeUVList(uvList, LEFT_ARM);
	leftArm->Initialize(D3DXVECTOR3(0.5f, 2.0f, 0.5f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR3(-0.8f, 1.0f, 0.0f));
	leftArm->SetTextureUV(uvList);
	leftArm->SetRotationSpeed(2.0f);
	root->AddChild(leftArm);
	animParts[LEFT_ARM] = leftArm;

	CubeManParts_Light* rightArm = new CubeManParts_Light;
	GetCubeUVList(uvList, RIGHT_ARM);
	rightArm->Initialize(D3DXVECTOR3(0.5f, 2.0f, 0.5f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR3(0.8f, 1.0f, 0.0f));
	rightArm->SetTextureUV(uvList);
	rightArm->SetRotation(-D3DX_PI * 0.25);
	root->AddChild(rightArm);
	animParts[RIGHT_ARM] = rightArm;

	CubeManParts_Light* leftLeg = new CubeManParts_Light;
	GetCubeUVList(uvList, LEFT_LEG);
	leftLeg->Initialize(D3DXVECTOR3(0.5f, 2.0f, 0.8f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR3(-0.3f, -1.0f, 0.0f));
	leftLeg->SetTextureUV(uvList);
	leftLeg->SetRotationSpeed(-2.0f);
	root->AddChild(leftLeg);
	animParts[LEFT_LEG] = leftLeg;

	CubeManParts_Light* rigthLeg = new CubeManParts_Light;
	GetCubeUVList(uvList, RIGHT_LEG);
	rigthLeg->Initialize(D3DXVECTOR3(0.5f, 2.0f, 0.8f), D3DXVECTOR3(0.0f, 1.0f, 0.0f), D3DXVECTOR3(0.3f, -1.0f, 0.0f));
	rigthLeg->SetTextureUV(uvList);
	rigthLeg->SetRotationSpeed(2.0f);
	root->AddChild(rigthLeg);
	animParts[RIGHT_LEG] = rigthLeg;

	texture[BATMAN] = TextureManager::GetTexture("batman.png");
	texture[IRONMAN] = TextureManager::GetTexture("IronMan.png");
	texture[ROBOCAP] = TextureManager::GetTexture("robocop.png");
	texture[SPIDERMAN] = TextureManager::GetTexture("spiderman.png");

	AnimationOnOff(false);


	//라이트용 추가
	ZeroMemory(&material, sizeof(D3DMATERIAL9));
	material.Ambient = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f);
	material.Diffuse = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f);
	material.Specular = D3DXCOLOR(0.8f, 0.8f, 0.8f, 1.0f);

	ZeroMemory(&headLight, sizeof(D3DLIGHT9));
	ZeroMemory(&handLight, sizeof(D3DLIGHT9));

	headLight.Type = D3DLIGHT_POINT;
	headLight.Ambient = D3DXCOLOR(0.f, 0.7f, 0.f, 1.0f);
	headLight.Diffuse = D3DXCOLOR(0.f, 0.7f, 0.f, 1.0f);
	headLight.Specular = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
	headLight.Position = D3DXVECTOR3(0, 0, 0);
	headLight.Range = 2.0f;

	handLight.Type = D3DLIGHT_SPOT;
	handLight.Ambient = D3DXCOLOR(0.7f, 0.f, 0.f, 1.0f);
	handLight.Diffuse = D3DXCOLOR(0.7f, 0.f, 0.f, 1.0f);
	handLight.Specular = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
	handLight.Position = D3DXVECTOR3(0, 0, 0);
	handLight.Range = 10.0f;
	handLight.Direction = D3DXVECTOR3(0, 0, 1);
	handLight.Theta = D3DXToRadian(30.0f);
	handLight.Phi = D3DXToRadian(90.0f);
	handLight.Falloff = 1.0f;
	

	GameManager::GetDevice()->SetLight(1, &headLight);
	GameManager::GetDevice()->LightEnable(1, true);

	GameManager::GetDevice()->SetLight(2, &handLight);
	GameManager::GetDevice()->LightEnable(2, true);

	head->AttachLight(&headLight, 1, D3DXVECTOR3(0, 1, 0));
	rightArm->AttachLight(&handLight, 2, D3DXVECTOR3(0, -2, 0));
}
Ejemplo n.º 9
0
LRESULT CView::OnWindowPosChanged(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(uMsg);
	UNREFERENCED_PARAMETER(wParam);
	UNREFERENCED_PARAMETER(lParam);

	if (m_pPicture)
	{
		CRect rcImage = GetImageRect();
		DWORD dwStyle = (DWORD)GetWindowLongPtr(GWL_STYLE);
		DWORD dwExStyle = (DWORD)GetWindowLongPtr(GWL_EXSTYLE);
		AdjustWindowRectEx(&rcImage, dwStyle, FALSE, dwExStyle);

		CRect rcView = GetClientRect();
		AdjustWindowRectEx(&rcView, dwStyle, FALSE, dwExStyle);

		SCROLLINFO si;
		ZeroMemory(&si, sizeof(SCROLLINFO));
		si.cbSize = sizeof(si);
		si.fMask  = SIF_RANGE | SIF_PAGE | SIF_POS;
		si.nMin   = 0;

		if (rcView.Width()  >= rcImage.Width())
		{
			m_xCurrentScroll = 0;
			ShowScrollBar(SB_HORZ, FALSE);
		}
		else
		{
			si.nMax   = rcImage.Width();
			si.nPage  = rcView.Width();
			si.nPos   = m_xCurrentScroll;
			SetScrollInfo(SB_HORZ, si, TRUE);
			ShowScrollBar(SB_HORZ, TRUE);
		}

		if (rcView.Height() >= rcImage.Height())
		{
			m_yCurrentScroll = 0;
			ShowScrollBar(SB_VERT, FALSE);
		}
		else
		{
			si.nMax   = rcImage.Height();
			si.nPage  = rcView.Height();
			si.nPos   = m_yCurrentScroll;
			SetScrollInfo(SB_VERT, si, TRUE);
			ShowScrollBar(SB_VERT, TRUE);
		}

		int xNewPos = MIN(m_xCurrentScroll, rcImage.Width() - rcView.Width());
		m_xCurrentScroll = MAX(xNewPos, 0);
		int yNewPos = MIN(m_yCurrentScroll, rcImage.Height() - rcView.Height());
		m_yCurrentScroll = MAX(yNewPos, 0);

		// Paint the window directly to eliminate flicker
		CClientDC dcView(*this);
		Paint(dcView);
	}

	return 0L;
}
Ejemplo n.º 10
0
Sound*
Sound::CreateStream(const char* filename)
{
    Sound* sound = 0;

    if (!filename || !filename[0] || !creator)
    return sound;

    int namelen = strlen(filename);

    if (namelen < 5)
    return sound;

    if ((filename[namelen-3] == 'o' || filename[namelen-3] == 'O') &&
            (filename[namelen-2] == 'g' || filename[namelen-2] == 'G') &&
            (filename[namelen-1] == 'g' || filename[namelen-1] == 'G')) {

        return CreateOggStream(filename);
    }

    WAVE_HEADER    head;
    WAVE_FMT       fmt;
    WAVE_FACT      fact;
    WAVE_DATA      data;
    WAVEFORMATEX   wfex;

    ZeroMemory(&head, sizeof(head));
    ZeroMemory(&fmt,  sizeof(fmt));
    ZeroMemory(&fact, sizeof(fact));
    ZeroMemory(&data, sizeof(data));

    LPBYTE         buf   = 0;
    LPBYTE         p     = 0;
    int            len   = 0;

    FILE* f;
    ::fopen_s(&f, filename, "rb");

    if (f) {
        fseek(f, 0, SEEK_END);
        len = ftell(f);
        fseek(f, 0, SEEK_SET);

        if (len > 4096) {
            len = 4096;
        }

        buf = new(__FILE__,__LINE__) BYTE[len];

        if (buf && len)
        fread(buf, len, 1, f);

        fclose(f);
    }


    if (len > sizeof(head)) {
        CopyMemory(&head, buf, sizeof(head));

        if (head.RIFF == MAKEFOURCC('R', 'I', 'F', 'F') &&
                head.WAVE == MAKEFOURCC('W', 'A', 'V', 'E')) {

            p = buf + sizeof(WAVE_HEADER);

            do {
                DWORD chunk_id = *((LPDWORD) p);

                switch (chunk_id) {
                case MAKEFOURCC('f', 'm', 't', ' '):
                    CopyMemory(&fmt, p, sizeof(fmt));
                    p += fmt.chunk_size + 8;
                    break;

                case MAKEFOURCC('f', 'a', 'c', 't'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('s', 'm', 'p', 'l'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('d', 'a', 't', 'a'):
                    CopyMemory(&data, p, sizeof(data));
                    p += 8;
                    break;

                default:
                    delete[] buf;
                    return sound;
                }
            }
            while (data.chunk_size == 0);

            wfex.wFormatTag      = fmt.wFormatTag;
            wfex.nChannels       = fmt.nChannels;
            wfex.nSamplesPerSec  = fmt.nSamplesPerSec;
            wfex.nAvgBytesPerSec = fmt.nAvgBytesPerSec;
            wfex.nBlockAlign     = fmt.nBlockAlign;
            wfex.wBitsPerSample  = fmt.wBitsPerSample;
            wfex.cbSize          = 0;

            sound = Create(Sound::STREAMED, &wfex);

            if (sound) {
                sound->SetFilename(filename);
                sound->StreamFile(filename, p - buf);
            }
        }
    }

    delete[] buf;
    return sound;
}
Ejemplo n.º 11
0
Sound*
Sound::CreateOggStream(const char* filename)
{
    Sound* sound = 0;

    if (!filename || !filename[0] || !creator)
    return sound;

    int namelen = strlen(filename);

    if (namelen < 5)
    return sound;

    WAVEFORMATEX wfex;
    ZeroMemory(&wfex, sizeof(wfex));

    FILE* f;
    ::fopen_s(&f, filename, "rb");

    if (f) {
        OggVorbis_File* povf = new(__FILE__,__LINE__) OggVorbis_File;

        if (!povf) {
            Print("Sound::CreateOggStream(%s) - out of memory!\n", filename);
            return sound;
        }

        ZeroMemory(povf, sizeof(OggVorbis_File));

        if (ov_open(f, povf, NULL, 0) < 0) {
            Print("Sound::CreateOggStream(%s) - not an Ogg bitstream\n", filename);
            delete povf;
            return sound;
        }

        Print("\nOpened Ogg Bitstream '%s'\n", filename);
        char **ptr=ov_comment(povf,-1)->user_comments;
        vorbis_info *vi=ov_info(povf,-1);
        while(*ptr){
            Print("%s\n", *ptr);
            ++ptr;
        }

        Print("Bitstream is %d channel, %ldHz\n", vi->channels, vi->rate);
        Print("Decoded length: %ld samples\n",
        (long)ov_pcm_total(povf,-1));
        Print("Encoded by: %s\n\n", ov_comment(povf,-1)->vendor);

        wfex.wFormatTag      = WAVE_FORMAT_PCM;
        wfex.nChannels       = vi->channels;
        wfex.nSamplesPerSec  = vi->rate;
        wfex.nAvgBytesPerSec = vi->channels * vi->rate * 2;
        wfex.nBlockAlign     = vi->channels * 2;
        wfex.wBitsPerSample  = 16;
        wfex.cbSize          = 0;

        sound = Create(Sound::STREAMED | Sound::OGGVORBIS,
        &wfex,
        sizeof(OggVorbis_File),
        (LPBYTE) povf);

        sound->SetFilename(filename);
    }

    return sound;
}
C3DCoordinateAxisMain::C3DCoordinateAxisMain(void)
{
    ZeroMemory( m_clickVecPt, sizeof(VECTOR)*CLICK_MAX);
    m_clickCnt = 0;
    degree = 0.0f;
}
Ejemplo n.º 13
0
/**************************************************************************
 * DoOpenProperties
 */
static void DoOpenProperties(ItemCmImpl *This, HWND hwnd)
{
	static const UINT MAX_PROP_PAGES = 99;
	static const WCHAR wszFolder[] = {'F','o','l','d','e','r', 0};
	static const WCHAR wszFiletypeAll[] = {'*',0};
	LPSHELLFOLDER lpDesktopSF;
	LPSHELLFOLDER lpSF;
	LPDATAOBJECT lpDo;
	WCHAR wszFiletype[MAX_PATH];
	WCHAR wszFilename[MAX_PATH];
	PROPSHEETHEADERW psh;
	HPROPSHEETPAGE hpages[MAX_PROP_PAGES];
	HPSXA hpsxa;
	UINT ret;

	TRACE("(%p)->(wnd=%p)\n", This, hwnd);

	ZeroMemory(&psh, sizeof(PROPSHEETHEADERW));
	psh.dwSize = sizeof (PROPSHEETHEADERW);
	psh.hwndParent = hwnd;
	psh.dwFlags = PSH_PROPTITLE;
	psh.nPages = 0;
	psh.u3.phpage = hpages;
	psh.u2.nStartPage = 0;

	_ILSimpleGetTextW(This->apidl[0], (LPVOID)wszFilename, MAX_PATH);
	psh.pszCaption = (LPCWSTR)wszFilename;

	/* Find out where to look for the shell extensions */
	if (_ILIsValue(This->apidl[0]))
	{
	    char sTemp[64];
	    sTemp[0] = 0;
	    if (_ILGetExtension(This->apidl[0], sTemp, 64))
	    {
		HCR_MapTypeToValueA(sTemp, sTemp, 64, TRUE);
		MultiByteToWideChar(CP_ACP, 0, sTemp, -1, wszFiletype, MAX_PATH);
	    }
	    else
	    {
		wszFiletype[0] = 0;
	    }
	}
	else if (_ILIsFolder(This->apidl[0]))
	{
	    lstrcpynW(wszFiletype, wszFolder, 64);
	}
	else if (_ILIsSpecialFolder(This->apidl[0]))
	{
	    LPGUID folderGUID;
	    static const WCHAR wszclsid[] = {'C','L','S','I','D','\\', 0};
	    folderGUID = _ILGetGUIDPointer(This->apidl[0]);
	    lstrcpyW(wszFiletype, wszclsid);
	    StringFromGUID2(folderGUID, &wszFiletype[6], MAX_PATH - 6);
	}
	else
	{
	    FIXME("Requested properties for unknown type.\n");
	    return;
	}

	/* Get a suitable DataObject for accessing the files */
	SHGetDesktopFolder(&lpDesktopSF);
	if (_ILIsPidlSimple(This->pidl))
	{
	    ret = IShellFolder_GetUIObjectOf(lpDesktopSF, hwnd, This->cidl, (LPCITEMIDLIST*)This->apidl,
					     &IID_IDataObject, NULL, (LPVOID *)&lpDo);
	    IShellFolder_Release(lpDesktopSF);
	}
	else
	{
	    IShellFolder_BindToObject(lpDesktopSF, This->pidl, NULL, &IID_IShellFolder, (LPVOID*) &lpSF);
	    ret = IShellFolder_GetUIObjectOf(lpSF, hwnd, This->cidl, (LPCITEMIDLIST*)This->apidl,
					     &IID_IDataObject, NULL, (LPVOID *)&lpDo);
	    IShellFolder_Release(lpSF);
	    IShellFolder_Release(lpDesktopSF);
	}

	if (SUCCEEDED(ret))
	{
	    hpsxa = SHCreatePropSheetExtArrayEx(HKEY_CLASSES_ROOT, wszFiletype, MAX_PROP_PAGES - psh.nPages, lpDo);
	    if (hpsxa != NULL)
	    {
		SHAddFromPropSheetExtArray(hpsxa, Properties_AddPropSheetCallback, (LPARAM)&psh);
		SHDestroyPropSheetExtArray(hpsxa);
	    }
	    hpsxa = SHCreatePropSheetExtArrayEx(HKEY_CLASSES_ROOT, wszFiletypeAll, MAX_PROP_PAGES - psh.nPages, lpDo);
	    if (hpsxa != NULL)
	    {
		SHAddFromPropSheetExtArray(hpsxa, Properties_AddPropSheetCallback, (LPARAM)&psh);
		SHDestroyPropSheetExtArray(hpsxa);
	    }
	    IDataObject_Release(lpDo);
	}

	if (psh.nPages)
	    PropertySheetW(&psh);
	else
	    FIXME("No property pages found.\n");
}
Ejemplo n.º 14
0
DWORD WINAPI Cadthread(LPVOID lpParam)
{
	OSVERSIONINFO OSversion;	
	OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
	GetVersionEx(&OSversion);


	HDESK desktop=NULL;
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);


	
	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop Error \n"));
	else 
		vnclog.Print(LL_INTERR, VNCLOG("OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];
	if (desktop)
	{
	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("SelectHDESK:!SetThreadDesktop \n"));
	}
	}

	//////
	if(OSversion.dwMajorVersion>=6 && vncService::RunningAsService())
			{				
					if( vncService::RunningAsService() &&!IsSoftwareCadEnabled())
					{
						DWORD result=MessageBoxSecure(NULL,"UAC is Disable, make registry changes to allow cad","Warning",MB_YESNO);
						if (result==IDYES)
							{
								HANDLE hProcess=NULL,hPToken=NULL;
								DWORD id=GetExplorerLogonPid();
								if (id!=0) 
									{						
									hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
									if (!hProcess) goto error;
									if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
													|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
													| TOKEN_READ | TOKEN_WRITE, &hPToken))
									{
										CloseHandle(hProcess);
										goto error;
									}
									char dir[MAX_PATH];
									char exe_file_name[MAX_PATH];
									GetModuleFileName(0, exe_file_name, MAX_PATH);
									strcpy(dir, exe_file_name);
									strcat(dir, " -softwarecadhelper");
		
							
									STARTUPINFO          StartUPInfo;
									PROCESS_INFORMATION  ProcessInfo;
									HANDLE Token=NULL;
									HANDLE process=NULL;
									ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
									ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
									StartUPInfo.wShowWindow = SW_SHOW;
									StartUPInfo.lpDesktop = "Winsta0\\Default";
									StartUPInfo.cb = sizeof(STARTUPINFO);
			
									CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
									DWORD errorcode=GetLastError();
									if (process) CloseHandle(process);
									if (Token) CloseHandle(Token);
									if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess);
									if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread);
									if (errorcode == 1314) goto error;
									goto gotome;
									error:
											Enable_softwareCAD_elevated();							
									}
							}
					
					}
			}
	gotome:
       /////////////////////
	if(OSversion.dwMajorVersion==6)//&& OSversion.dwMinorVersion>=1) //win7  // test win7 +Vista
	{

		if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad");
		if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad);
		if (old_desktop) SetThreadDesktop(old_desktop);
		if (desktop) CloseDesktop(desktop);
		return 0;
	}

	 HKEY hKey; 
	 DWORD isLUAon = 0; 
     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"), 0, KEY_READ, &hKey) == ERROR_SUCCESS) 
              { 
              DWORD LUAbufSize = 4; 
              RegQueryValueEx(hKey, TEXT("EnableLUA"), NULL, NULL, (LPBYTE)&isLUAon, &LUAbufSize); 
              RegCloseKey(hKey); 
			  }
     if (isLUAon != 1 && OSversion.dwMajorVersion==6) 
	 {
		 if (hShutdownEventcad==NULL ) hShutdownEventcad = OpenEvent(EVENT_MODIFY_STATE, FALSE, "Global\\SessionEventUltraCad");
		 if (hShutdownEventcad!=NULL ) SetEvent(hShutdownEventcad);
		 if (old_desktop) SetThreadDesktop(old_desktop);
		 if (desktop) CloseDesktop(desktop);
		 return 0;
	 }

//Full path needed, sometimes it just default to system32
	char WORKDIR[MAX_PATH];
	char mycommand[MAX_PATH];
	if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
		{
		char* p = strrchr(WORKDIR, '\\');
		if (p == NULL) return 0;
		*p = '\0';
		}
	strcpy(mycommand,"");
	strcat(mycommand,WORKDIR);//set the directory
	strcat(mycommand,"\\");
	strcat(mycommand,"cad.exe");

	int nr=(LONG_PTR)ShellExecute(GetDesktopWindow(), "open", mycommand, "", 0, SW_SHOWNORMAL);
	if (nr<=32)
	{
		//error
		//
		if ( nr==SE_ERR_ACCESSDENIED )
			vncTimedMsgBox::Do(
									sz_ID_CADPERMISSION,
									sz_ID_ULTRAVNC_WARNING,
									MB_ICONINFORMATION | MB_OK
									);

		if ( nr==ERROR_PATH_NOT_FOUND || nr==ERROR_FILE_NOT_FOUND)
			vncTimedMsgBox::Do(
									sz_ID_CADERRORFILE,
									sz_ID_ULTRAVNC_WARNING,
									MB_ICONINFORMATION | MB_OK
									);

	}

	if (old_desktop) SetThreadDesktop(old_desktop);
	if (desktop) CloseDesktop(desktop);
	return 0;
}
/* 
 * Check if the given COM port name belongs to a USB-UART converter (CDC/ACM interface). If yes, find driver name 
 * and return it to caller. Iterate over all USB device's interface looking for CDC/ACM interface. When found
 * match COM port name, if matched get its driver name from regostry property.
 *
 * Return 1 if found, 0 if not found, -1 if an error occurs (also throws exception in this case).
 */
int get_driver_com_port_usb(JNIEnv *env, const jchar *port_name, TCHAR *driver_name) {

	int x = 0;
	BOOL ret = FALSE;
	LONG status = 0;
	DWORD error_code = 0;
	DWORD size = 0;
	DWORD regproptype;
	DWORD charbuffer_size = 0;
	DWORD driver_name_size = 0;
	ULONG buffer_size = 0;
	DWORD usb_member_index = 0;
	HDEVINFO usb_dev_info_set;
	SP_DEVINFO_DATA usb_dev_instance;
	ULONG devprop_buffer_size = 0;
	DEVPROPTYPE proptype;
	CONFIGRET cmret = 0;
	DEVINST firstchild = 0;
	DEVINST next_sibling = 0;
	DEVINST current_sibling = 0;

	/* size of these buffers is hardcoded in functions using them */
	TCHAR buffer[1024];
	TCHAR devprop_buffer[1024];
	TCHAR keybuf[1024];
	TCHAR charbuffer[128];
	char cmerror[256];

	/* get information set for all usb devices matching the GUID */
	usb_dev_info_set = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (usb_dev_info_set == INVALID_HANDLE_VALUE) {
		SetupDiDestroyDeviceInfoList(usb_dev_info_set);
		throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
		return -1;
	}

	/* enumerate all devices in this information set */
	usb_member_index = 0;
	while (1) {
		ZeroMemory(&usb_dev_instance, sizeof(usb_dev_instance));
		usb_dev_instance.cbSize = sizeof(usb_dev_instance);

		/* from information set, get device by index */
		ret = SetupDiEnumDeviceInfo(usb_dev_info_set, usb_member_index, &usb_dev_instance);
		if (ret == FALSE) {
			error_code = GetLastError();
			if (error_code == ERROR_NO_MORE_ITEMS) {
				break;
			}else {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(error_code), NULL);
				return -1;
			}
		}

		/* for this device find its instance ID (USB\VID_04D8&PID_00DF\000098037)
		 * this is variable 'Device Instance Path' in device manager. */
		memset(buffer, '\0', 1024);
		ret = SetupDiGetDeviceInstanceId(usb_dev_info_set, &usb_dev_instance, buffer, 1024, &size);
		if (ret == FALSE) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
			return -1;
		}

		cmret = CM_Get_Child(&firstchild, usb_dev_instance.DevInst, 0);
		if (cmret != CR_SUCCESS) {
			if (cmret == CR_NO_SUCH_DEVNODE) {
				/* this device does not have any child, so check if this device itself is a "Ports" class device or not */
				memset(devprop_buffer, '\0', 1024);
				ret = SetupDiGetDeviceRegistryProperty(usb_dev_info_set, &usb_dev_instance, SPDRP_CLASSGUID, &regproptype, (BYTE *)devprop_buffer, sizeof(devprop_buffer), &size);
				if (ret == FALSE) {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
					return -1;
				}

				/* match GUID */
				ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}"));
				if (ret != 0) {
					usb_member_index++;
					continue;
				}

				/* reaching here means that the device is COM port device (CDC/ACM), get its COM port name/number
				 * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\VID_VID+PID_PID+Serial_Number\0000\DeviceParameters\PortName
				 * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_VID+PID_PID\Serial_Number\DeviceParameters\PortName */
				memset(keybuf, '\0', 1024);
				_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer);

				charbuffer_size = sizeof(charbuffer);
				memset(charbuffer, '\0', 128);
				status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
				if (status != ERROR_SUCCESS) {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					throw_serialcom_exception(env, 4, GetLastError(), NULL);
					return -1;
				}

				/* match port name */
				ret = _tcsicmp(charbuffer, port_name);
				if (ret != 0) {
					usb_member_index++;
					continue;
				}

				memset(keybuf, '\0', 1024);
				_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s"), buffer);

				/* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_VID+PID_PID\Serial_Number\Service */
				charbuffer_size = sizeof(charbuffer);
				memset(charbuffer, '\0', 128);
				status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("Service"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
				if (status != ERROR_SUCCESS) {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					throw_serialcom_exception(env, 4, GetLastError(), NULL);
					return -1;
				}

				/* populate array to be returned to caller, return 1 to indicate driver found */
				memset(driver_name, '\0', 128);
				for (x = 0; x < _tcslen(charbuffer); x++) {
					driver_name[x] = charbuffer[x];
				}

				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				return 1;
			}else {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				_snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property CR_xxxx error code : 0x%X\0", cmret);
				throw_serialcom_exception(env, 3, 0, cmerror);
				return -1;
			}
		}

		/* reaching here means that this USB device has at-least one child device node, examine child now */

		devprop_buffer_size = sizeof(devprop_buffer);
		memset(devprop_buffer, '\0', sizeof(devprop_buffer));
		cmret = CM_Get_DevNode_Registry_Property(firstchild, CM_DRP_CLASSGUID, &proptype, (PVOID)devprop_buffer, &devprop_buffer_size, 0);
		if (cmret != CR_SUCCESS) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			_snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property CR_xxxx error code : 0x%X\0", cmret);
			throw_serialcom_exception(env, 3, 0, cmerror);
			return -1;
		}

		/* match GUID */
		ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}"));
		if (ret == 0) {
			/* reaching here means that the child device is COM port device (CDC/ACM), get its COM port name/number */
			memset(buffer, '\0', 1024);
			cmret = CM_Get_Device_ID(firstchild, buffer, 1024, 0);
			if (cmret != CR_SUCCESS) {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				_snprintf_s(cmerror, 256, 256, "CM_Get_Device_ID CR_xxxx error code : 0x%X\0", cmret);
				throw_serialcom_exception(env, 3, 0, cmerror);
				return -1;
			}

			memset(keybuf, '\0', 1024);
			_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer);

			charbuffer_size = sizeof(charbuffer);
			memset(charbuffer, '\0', sizeof(charbuffer));
			status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
			if (status != ERROR_SUCCESS) {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				throw_serialcom_exception(env, 4, GetLastError(), NULL);
				return -1;
			}

			/* match port name and find driver name if port name matches */
			ret = _tcsicmp(charbuffer, port_name);
			if (ret == 0) {
				memset(keybuf, '\0', 1024);
				_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s"), buffer);

				/* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_VID+PID_PID\Serial_Number\Service */
				charbuffer_size = sizeof(charbuffer);
				memset(charbuffer, '\0', 128);
				status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("Service"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
				if (status != ERROR_SUCCESS) {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					throw_serialcom_exception(env, 4, GetLastError(), NULL);
					return -1;
				}

				/* populate array to be returned to caller */
				memset(driver_name, '\0', 128);
				for (x = 0; x < _tcslen(charbuffer); x++) {
					driver_name[x] = charbuffer[x];
				}

				/* clean up and return 1 to indicate driver found */
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				return 1;
			}
		}

		/* reaching here means first child of this USB device was not CDC/ACM interface, need to 
		   iterate over all the interfaces (siblings) this device has examining them for matching our criteria */
		current_sibling = firstchild;
		while (1) {
			cmret = CM_Get_Sibling(&next_sibling, current_sibling, 0);
			if (cmret != CR_SUCCESS) {
				if (cmret == CR_NO_SUCH_DEVNODE) {
					/* done iterating over all interfaces, move to next examine next USB device */
					break;
				}
				else {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					_snprintf_s(cmerror, 256, 256, "CM_Get_Sibling failed with CR_xxxx error code : 0x%X\0", cmret);
					throw_serialcom_exception(env, 3, 0, cmerror);
					return -1;
				}

			}

			/* reaching here means USB device has more than 1 interfaces, get class of this interface (sibling) */
			devprop_buffer_size = sizeof(devprop_buffer);
			memset(devprop_buffer, '\0', sizeof(devprop_buffer));
			cmret = CM_Get_DevNode_Registry_Property(next_sibling, CM_DRP_CLASSGUID, &proptype, (VOID *)devprop_buffer, &devprop_buffer_size, 0);
			if (cmret != CR_SUCCESS) {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				_snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property failed with CR_xxxx error code : 0x%X\0", cmret);
				throw_serialcom_exception(env, 3, 0, cmerror);
				return -1;
			}

			/* match GUID for this sibling */
			ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}"));
			if (ret != 0) {
				/* this interface is not CDC/ACM, loop over to next interface */
				current_sibling = next_sibling;
				continue;
			}

			/* reaching here means that this sibling (interface) is a CDC/ACM type, get its COM port name/number */
			buffer_size = (ULONG)_tcslen(buffer);
			memset(buffer, '\0', 1024);
			cmret = CM_Get_Device_ID(next_sibling, buffer, 1024, 0);
			if (cmret != CR_SUCCESS) {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				_snprintf_s(cmerror, 256, 256, "CM_Get_Device_ID failed with CR_xxxx error code : 0x%X\0", cmret);
				throw_serialcom_exception(env, 3, 0, cmerror);
				return -1;
			}

			memset(keybuf, '\0', 1024);
			_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer);

			charbuffer_size = sizeof(charbuffer);
			memset(charbuffer, '\0', 128);
			status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
			if (status != ERROR_SUCCESS) {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				throw_serialcom_exception(env, 4, GetLastError(), NULL);
				return -1;
			}

			/* match port name and find driver name if port name matches */
			ret = _tcsicmp(charbuffer, port_name);
			if (ret == 0) {
				memset(keybuf, '\0', 1024);
				_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s"), buffer);

				/* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_VID+PID_PID\Serial_Number\Service */
				charbuffer_size = sizeof(charbuffer);
				memset(charbuffer, '\0', 128);
				status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("Service"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
				if (status != ERROR_SUCCESS) {
					SetupDiDestroyDeviceInfoList(usb_dev_info_set);
					throw_serialcom_exception(env, 4, GetLastError(), NULL);
					return -1;
				}

				/* populate array to be returned to caller */
				memset(driver_name, '\0', 128);
				for (x = 0; x < _tcslen(charbuffer); x++) {
					driver_name[x] = charbuffer[x];
				}

				/* clean up and return 1 to indicate driver found */
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				return 1;
			}

			/* set this sibling as base sibling for fetching next sibling, loop over to get and check next 
			   interface (sibling) */
			current_sibling = next_sibling;
		}

		/* increment to get and examine the next usb device for COM ports class */
		usb_member_index++;
	}

	/* reaching here means given COM port does not represent CDC/ACM interface and therefore does not belong to 
	   USB-UART IC. probably other usb-systems need to be examined for finding given COM port's driver */
	SetupDiDestroyDeviceInfoList(usb_dev_info_set); 
	return 0;
}
int CompletionPortListener::Start()
{
	if ((Ret = WSAStartup((2, 2), &wsaData)) != 0)
	{
		printf("WSAStartup() failed with error %d\n", Ret);
		return 1;
	}
	else
		printf("WSAStartup() is OK!\n");

	// Setup an I/O completion port
	if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0)) == NULL)
	{
		printf("CreateIoCompletionPort() failed with error %d\n", GetLastError());
		return 1;
	}
	else
		printf("CreateIoCompletionPort() is damn OK!\n");

	// Determine how many processors are on the system
	GetSystemInfo(&SystemInfo);
	// Create worker threads based on the number of processors available on the
	// system. Create two worker threads for each processor
	for (i = 0; i < (int)SystemInfo.dwNumberOfProcessors * 2; i++)
	{
		// Create a server worker thread and pass the completion port to the thread
		if ((ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, this, 0, &ThreadID)) == NULL)
		{
			printf("CreateThread() failed with error %d\n", GetLastError());
			return 1;
		}
		else
			printf("CreateThread() is OK!\n");
		// Close the thread handle
		CloseHandle(ThreadHandle);
	}

	// Create a listening socket
	if ((Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
	{
		printf("WSASocket() failed with error %d\n", WSAGetLastError());
		return 1;
	}
	else
		printf("WSASocket() is OK!\n");

	InternetAddr.sin_family = AF_INET;
	InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	InternetAddr.sin_port = htons(DEFAULT_PORT_INT);

	if (bind(Listen, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
	{
		printf("bind() failed with error %d\n", WSAGetLastError());
		return 1;
	}
	else
		printf("bind() is fine!\n");

	// Prepare socket for listening
	if (listen(Listen, 5) == SOCKET_ERROR)
	{
		printf("listen() failed with error %d\n", WSAGetLastError());
		return 1;
	}
	else
		printf("listen() is working...\n");

	completionPortStackListener.Start();

	// Accept connections and assign to the completion port
	while (TRUE)
	{
		if ((Accept = WSAAccept(Listen, NULL, NULL, NULL, 0)) == SOCKET_ERROR)
		{
			printf("WSAAccept() failed with error %d\n", WSAGetLastError());
			return 1;
		}
		else
			printf("WSAAccept() looks fine!\n");

		// Create a socket information structure to associate with the socket
		if ((PerHandleData = (LPPER_HANDLE_DATA)GlobalAlloc(GPTR, sizeof(PER_HANDLE_DATA))) == NULL)
			printf("GlobalAlloc() failed with error %d\n", GetLastError());
		else
			printf("GlobalAlloc() for LPPER_HANDLE_DATA is OK!\n");

		// Associate the accepted socket with the original completion port
		printf("Socket number %d got connected...\n", Accept);
		PerHandleData->Socket = Accept;

		if (CreateIoCompletionPort((HANDLE)Accept, CompletionPort, (DWORD)PerHandleData, 0) == NULL)
		{
			printf("CreateIoCompletionPort() failed with error %d\n", GetLastError());
			return 1;
		}
		else
			printf("CreateIoCompletionPort() is OK!\n");

		// Create per I/O socket information structure to associate with the WSARecv call below
		if ((PerIoData = (LPPER_IO_OPERATION_DATA)GlobalAlloc(GPTR, sizeof(PER_IO_OPERATION_DATA))) == NULL)
		{
			printf("GlobalAlloc() failed with error %d\n", GetLastError());
			return 1;
		}
		else
			printf("GlobalAlloc() for LPPER_IO_OPERATION_DATA is OK!\n");

		ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
		PerIoData->BytesSEND = 0;
		PerIoData->BytesRECV = 0;
		PerIoData->DataBuf.len = DATA_BUFSIZE;
		PerIoData->DataBuf.buf = PerIoData->Buffer;

		Flags = 0;
		if (WSARecv(Accept, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags, &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
		{
			if (WSAGetLastError() != ERROR_IO_PENDING)
			{
				printf("WSARecv() failed with error %d\n", WSAGetLastError());
				return 1;
			}
		}
		else
			printf("WSARecv() is OK!\n");

	}

}
Ejemplo n.º 17
0
void NPCDonate(BYTE *m_PacketBuffer)
{
	
	FILE *arq, *arq2;
	int clientid = m_PacketBuffer[6];
	p379 *pak = (p379*)m_PacketBuffer;
	MOB *player = (MOB*)GetMobFromIndex(m_PacketBuffer[6]);
	MOB *npc = (MOB*)GetMobFromIndex(pak->MobID);
	char local_item[100], line[120], nome[100], local_cash[100], msg[100],msg_confirm[100];
	int slot_nulo = GetFirstSlotSADD(clientid,0,64);
	int preco, cash, confirm;
	sprintf(local_item,"DataBase\\Itens\\%d.txt",npc->Inventory[pak->SellSlot].Index);
	sprintf(local_cash,"DataBase\\Cash\\%s.txt",vLogin(clientid));
	{
		arq=fopen(local_item,"r");
		if(arq != NULL)
		{
			while((fscanf(arq, "%[^\n]", line)) != EOF)
			{
			fgetc(arq);
			sscanf(line,"%d,%s",&preco,&nome);
			}
			fclose(arq);
			arq2=fopen(local_cash,"r");
			if(arq2 != NULL)
			{
				while((fscanf(arq2, "%[^\n]", line)) != EOF)
				{
				fgetc(arq2);
				sscanf(line,"%d",&cash);
				}
				fclose(arq2);
				if(cash >= preco)
				{
					player->Inventory[slot_nulo].Index = npc->Inventory[pak->SellSlot].Index;
					player->Inventory[slot_nulo].EF1 = npc->Inventory[pak->SellSlot].EF1;
					player->Inventory[slot_nulo].EFV1 = npc->Inventory[pak->SellSlot].EFV1;
					player->Inventory[slot_nulo].EF2 = npc->Inventory[pak->SellSlot].EF2;
					player->Inventory[slot_nulo].EFV2 = npc->Inventory[pak->SellSlot].EFV2;
					player->Inventory[slot_nulo].EF3 = npc->Inventory[pak->SellSlot].EF3;
					player->Inventory[slot_nulo].EFV3 = npc->Inventory[pak->SellSlot].EFV3;
					arq2=fopen(local_cash,"w");
					fprintf(arq2,"%d",(cash - preco));
					fclose(arq2);
					sprintf(msg,"O item [%s] foi comprado com sucesso.",nome);
					SendSay(clientid,msg);
					SendALL(clientid);
					ZeroMemory(m_PacketBuffer, *(short*)m_PacketBuffer);
					return;
				}
				else
				{
					fclose(arq2);
					sprintf(msg,"Necessário [%d] Donates.",preco);
					SendClientMsg(clientid,msg);
					ZeroMemory(m_PacketBuffer, *(short*)m_PacketBuffer);
					return;
				}
			}
			else
			{
				sprintf(msg,"Necessário [%d] Donates.",preco);
				SendClientMsg(clientid,msg);
				ZeroMemory(m_PacketBuffer, *(short*)m_PacketBuffer);
				return;
			}
		}
	}
}
DWORD WINAPI CompletionPortListener::ServerWorkerThread(LPVOID obj)
{
	CompletionPortListener* instance = (CompletionPortListener*)obj;
	HANDLE CompletionPort = instance->CompletionPort;
	DWORD BytesTransferred;
	LPPER_HANDLE_DATA PerHandleData;
	LPPER_IO_OPERATION_DATA PerIoData;
	DWORD SendBytes, RecvBytes;
	DWORD Flags;

	while (TRUE)
	{
		if (GetQueuedCompletionStatus(CompletionPort, &BytesTransferred,
			(LPDWORD)&PerHandleData, (LPOVERLAPPED *)&PerIoData, INFINITE) == 0)
		{
			printf("GetQueuedCompletionStatus() failed with error %d\n", GetLastError());
			return 0;
		}
		//else
		//	printf("GetQueuedCompletionStatus() is OK!\n");

		// First check to see if an error has occurred on the socket and if so
		// then close the socket and cleanup the SOCKET_INFORMATION structure
		// associated with the socket
		if (BytesTransferred == 0)
		{
			printf("Closing socket %d\n", PerHandleData->Socket);
			if (closesocket(PerHandleData->Socket) == SOCKET_ERROR)
			{
				printf("closesocket() failed with error %d\n", WSAGetLastError());
				return 0;
			}
			//else
			//	printf("closesocket() is fine!\n");

			GlobalFree(PerHandleData);
			GlobalFree(PerIoData);
			continue;
		}

		instance->completionPortStackListener.SetProtocol((Protocol*)new ProtocolBase());
		instance->completionPortStackListener.AddJobRequest(PerHandleData->Socket, PerIoData->DataBuf.buf, PerIoData->DataBuf.len);

		ZeroMemory(PerIoData->Buffer, DATA_BUFSIZE);


		PerIoData->BytesRECV = 0;
		// Now that there are no more bytes to send post another WSARecv() request
		Flags = 0;
		ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
		PerIoData->DataBuf.len = DATA_BUFSIZE;
		PerIoData->DataBuf.buf = PerIoData->Buffer;

		if (WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
			&(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
		{
			if (WSAGetLastError() != ERROR_IO_PENDING)
			{
				printf("WSARecv() failed with error %d\n", WSAGetLastError());
				return 0;
			}
		}
		//else
		//	printf("WSARecv() is OK!\n");


		if (false)
		{
			// Check to see if the BytesRECV field equals zero. If this is so, then
			// this means a WSARecv call just completed so update the BytesRECV field
			// with the BytesTransferred value from the completed WSARecv() call
			if (PerIoData->BytesRECV == 0)
			{
				PerIoData->BytesRECV = BytesTransferred;
				PerIoData->BytesSEND = 0;
			}
			else
			{
				PerIoData->BytesSEND += BytesTransferred;
			}

			if (PerIoData->BytesRECV > PerIoData->BytesSEND)
			{
				// Post another WSASend() request.
				// Since WSASend() is not guaranteed to send all of the bytes requested,
				// continue posting WSASend() calls until all received bytes are sent.
				ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
				PerIoData->DataBuf.buf = PerIoData->Buffer + PerIoData->BytesSEND;
				PerIoData->DataBuf.len = PerIoData->BytesRECV - PerIoData->BytesSEND;

				if (WSASend(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &SendBytes, 0,
					&(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
				{
					if (WSAGetLastError() != ERROR_IO_PENDING)
					{
						printf("WSASend() failed with error %d\n", WSAGetLastError());
						return 0;
					}
				}
				//else
				//	printf("WSASend() is OK!\n");
			}
			else
			{
				PerIoData->BytesRECV = 0;
				// Now that there are no more bytes to send post another WSARecv() request
				Flags = 0;
				ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
				PerIoData->DataBuf.len = DATA_BUFSIZE;
				PerIoData->DataBuf.buf = PerIoData->Buffer;

				if (WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
					&(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
				{
					if (WSAGetLastError() != ERROR_IO_PENDING)
					{
						printf("WSARecv() failed with error %d\n", WSAGetLastError());
						return 0;
					}
				}
				else
					printf("WSARecv() is OK!\n");
			}
		}
	}
}
Ejemplo n.º 19
0
/*! Iterates over all the threads associated with this job (as determined by
 * mJobHandle), and runs the given callback function on them. The callback
 * function need not close the handle to the thread.
 *
 * \param callback The callback function to run on each thread.
 *
 * \par A few notes on the necessity and implementation of IterateThreads:
 * Before going to far into this function, you must realize that as much as one
 * may hope to the contrary, windows has no concept of mass process management.
 * If you want to do something to multiple processes or threads, windows
 * provides a few mediocre iteration methods, but beyond that, you're on your
 * own to find the processes and/or threads and work with them one at a time.
 * The following function was written for that exact purpose, it searches
 * through the list of all threads present in the entire system, finds the ones
 * whose parent process is part of the job object and runs the given callback
 * function on the thread.
 *
 * \par
 * The reason this is written on the thread level as opposed to the process
 * level (which would have been much easier), is because windows has no concept
 * of suspending a process, it can only suspend threads. Since the ability to
 * suspend and resume jobs was something that I wanted in GamessQ, it has to be
 * done on the tread level. When it comes to terminating processes, simply
 * terminating all their threads works just as well as terminating the process
 * via windows TerminatProcess function.
 *
 * \note
 * As clumsy as this method may seem, and as much as you may think and hope
 * that there MUST be a better way to do it, there really isn't. So far as I
 * have been able to find (and I searched for a while) this is the cleanest,
 * most efficient way to handle windows processes and threads in mass.
 *
 * \sa mJobHandle
 */
bool WindowsJob::IterateThreads(bool (*callback)(HANDLE))
{
	// We'll need this for later
	bool retVal = true;

	// get all the process ids for the job object
	JOBOBJECT_BASIC_PROCESS_ID_LIST *info;
	int num = mNumProcessors + 15; // make sure there's enough space
	int size = sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST) + num * sizeof(DWORD);
	info = (JOBOBJECT_BASIC_PROCESS_ID_LIST *)malloc(size);
	ZeroMemory(info, size);
	info->NumberOfAssignedProcesses = num;
	if (! QueryInformationJobObject(mJobHandle, JobObjectBasicProcessIdList,
			info, size, NULL)) {
		LOG_ERROR("QueryInformationJobObject");
		return false;
	}
	num = info->NumberOfProcessIdsInList;

	// get a thread snapshot
	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
	THREADENTRY32 entry;
	ZeroMemory(&entry, sizeof(entry));
	entry.dwSize = sizeof(entry);
	if (! Thread32First(snapshot, &entry)) {
		LOG_ERROR("Thread32First");
		CloseHandle(snapshot);
		return false;
	}

	// iterate through all the threads in the system.
	bool more = true;
	while (more) {
		// search through the job ids
		for (int i = 0; i < num; i ++) {
			// if this thread's parent is in the list, run the callback on it
			if (entry.th32OwnerProcessID == info->ProcessIdList[i]) {
				HANDLE threadHandle = OpenThread(THREAD_TERMINATE |
						THREAD_SUSPEND_RESUME , false, entry.th32ThreadID);
				if (! threadHandle) {
					LOG_ERROR("OpenThread");
				} else {
					retVal = retVal && callback(threadHandle);
				}
				CloseHandle(threadHandle);
				break;
			}
		}

		// get the next thread, and make sure it's valid
		ZeroMemory(&entry, sizeof(entry));
		entry.dwSize = sizeof(entry);
		if (! Thread32Next(snapshot, &entry)) {
			if (GetLastError() == ERROR_NO_MORE_FILES) {
				more = false;
			} else {
				LOG_ERROR("Thread32Next");
				free(info);
				CloseHandle(snapshot);
				return false;
			}
		}
	}

	// clean up
	free(info);
	CloseHandle(snapshot);
	return retVal;
}
/* **************************************************************************
 * dhExitEx:
 *   This function is called when exiting a DispHelper function.
 *
 * Parameter Info:
 *   bDispatchError   - TRUE if the error was returned from the IDispatch interface.  
 *   szMember         - The member name that caused the error. eg. "TypeText"
 *   szCompleteMember - The complete member. eg. "Selection.TypeText(%S)"
 *   pExcepInfo       - A pointer to the EXCEPINFO structure returned by IDispatch::Invoke.
 *   iArgError        - The index of the argument that caused the error as returned by Invoke.
 *   szFunctionName   - The function which is exiting(string must have global life time).
 * 
 * Notes:
 *   szMember, szCompleteMember, pExcepInfo and iArgError are NULL or 0 if not available.
 *
 ============================================================================ */
HRESULT dhExitEx(HRESULT hr, BOOL bDispatchError, LPCWSTR szMember, LPCWSTR szCompleteMember,
                 EXCEPINFO * pExcepInfo, UINT iArgError, LPCWSTR szFunctionName)
{
	UINT nStackCount = GetStackCount();

	SetStackCount(nStackCount - 1);

	if (FAILED(hr) && !g_ExceptionOptions.bDisableRecordExceptions)
	{
		PDH_EXCEPTION pException = GetExceptionPtr();

		if (!pException) /* No exception allocated for this thread yet */
		{ 
			pException = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DH_EXCEPTION));
			if (!pException) return hr;
			SetExceptionPtr(pException);
		}
		else if (pException->bOld) /* Exception is from a former call */
		{
			SysFreeString(pException->szDescription);
			SysFreeString(pException->szSource);
			SysFreeString(pException->szHelpFile);
			ZeroMemory(pException, sizeof(DH_EXCEPTION));
		}

		if (pException->hr == 0)
		{
			/* Only record the error information the first time it is reported */

			pException->hr              = hr;
			pException->iArgError       = iArgError;
			pException->szErrorFunction = szFunctionName;
			pException->bDispatchError  = bDispatchError;

			if (szMember) hlprStringCchCopyW(pException->szMember, ARRAYSIZE(pException->szMember), szMember);

			if (pExcepInfo && hr == DISP_E_EXCEPTION)
			{
				/* Extract error info returned by IDispatch::Invoke in an EXCEPINFO */

				if (pExcepInfo->pfnDeferredFillIn &&
				    !IsBadCodePtr((FARPROC) pExcepInfo->pfnDeferredFillIn)) pExcepInfo->pfnDeferredFillIn(pExcepInfo);

				pException->szDescription = pExcepInfo->bstrDescription;
				pException->szSource      = pExcepInfo->bstrSource;
				pException->szHelpFile    = pExcepInfo->bstrHelpFile;
				pException->dwHelpContext = pExcepInfo->dwHelpContext;
				pException->swCode        = (pExcepInfo->wCode ? pExcepInfo->wCode : pExcepInfo->scode);
			}
		}

		if (nStackCount == 1) /* We are exiting the outer most function */
		{
			pException->bOld              = TRUE;
			pException->szInitialFunction = szFunctionName;

			if (szCompleteMember) hlprStringCchCopyW(pException->szCompleteMember, ARRAYSIZE(pException->szCompleteMember), szCompleteMember);

			if (g_ExceptionOptions.bShowExceptions)
				dhShowException(pException);

			if (g_ExceptionOptions.pfnExceptionCallback)
				g_ExceptionOptions.pfnExceptionCallback(pException);
		}
	}
	else if (hr == DISP_E_EXCEPTION && pExcepInfo)
	{
		/* We are responsible for cleaning up pExcepInfo even if we don't use it */
		SysFreeString(pExcepInfo->bstrDescription);
		SysFreeString(pExcepInfo->bstrSource);
		SysFreeString(pExcepInfo->bstrHelpFile);
	}

	return hr;
}
Ejemplo n.º 21
0
int _tmain(int argc, _TCHAR* argv[]) {
	int i;
	DWORD failures = 0;
	ULONGLONG size = 0;
	DWORD err;
	TCHAR *f;
	TCHAR sSize[64];
	
	parsed_args* args = parse_args(argc, argv);
	BOOL oneVolumeOnly = has_arg(args, TEXT("one-volume-only"), TEXT('\0'));

	PSID sid = NULL;
	PACL acl = NULL;
	BOOL takeownership;
	EXPLICIT_ACCESS ea[1];

	if (!args->file_count) {
		_ftprintf(stderr, TEXT("Usage: %s [options] file1 [file2 ...]\n\n"), args->program);
		_ftprintf(stderr, TEXT("  The files can be directories, files, or simple wildcards\n\n"));
		_ftprintf(stderr, TEXT("  Options:\n"));
		_ftprintf(stderr, TEXT("    --one-volume-only  do not delete files on other volumes when\n                       junctions/symbolic links/mount points are found"));
		return 1;
	}

	takeownership = EnableTakeOwnershipPriv();
	if (!takeownership) {
		_ftprintf(stderr, TEXT("! Failed to enable the Take Ownership privilege\n"));
		_ftprintf(stderr, TEXT("Make sure you are an Administrator or elevated\n"));
		_ftprintf(stderr, TEXT("We will still try to delete the files\n"));
	}
	sid = GetCurrentSID();
	if (!sid) {
		_ftprintf(stderr, TEXT("! Failed to get the current user's SID\n"));
		_ftprintf(stderr, TEXT("We will still try to delete the files\n"));
	} else {
		// Explicit Access: All Access
		ZeroMemory(&ea, 1*sizeof(EXPLICIT_ACCESS));
		ea[0].grfAccessPermissions = GENERIC_ALL;
		ea[0].grfAccessMode = SET_ACCESS;
		ea[0].grfInheritance = SUB_OBJECTS_ONLY_INHERIT;
		ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
		ea[0].Trustee.TrusteeType = TRUSTEE_IS_USER;
		ea[0].Trustee.ptstrName = (LPTSTR)sid;
		// Create the ACL
		err = SetEntriesInAcl(1, ea, NULL, &acl);
		if (err != ERROR_SUCCESS) {
			LogError(TEXT("SetEntriesInAcl"), err);
		}
	}

	files = vector_create(64);

	// Find all files to delete
	for (i = 0; i < args->file_count; i++) {
		DWORD attrib = GetFileAttributes(args->files[i]);
		if (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY)) {
			vector_append(files, copyStr(args->files[i]));
			if (oneVolumeOnly && (attrib & FILE_ATTRIBUTE_REPARSE_POINT) && FileChangesVolume(args->files[i])) {
				continue;
			}
		}
		FindFiles(args->files[i], FALSE, oneVolumeOnly);
	}

	// Leave now if there is nothing to delete
	if (files->length == 0) {
		_tprintf(TEXT("No files found\n"));
		vector_destroy(files, TRUE);
		return 0;
	}

	// Correct security and delete files / directories
	for (i = files->length-1; i >= 0; i--) {
		WIN32_FILE_ATTRIBUTE_DATA attrib;
		BY_HANDLE_FILE_INFORMATION info;
		DWORD volumeSN = 0;
		f = (TCHAR*)files->x[i];
		if (!GetFileAttributesEx(f, GetFileExInfoStandard, &attrib))
			continue;
		CorrectSecurity(f, attrib.dwFileAttributes, takeownership, sid, acl, oneVolumeOnly);
		if (attrib.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			if (!RemoveDirectory(f) && (err = DeleteWithSH(f)) != 0) {
				LogFileError(TEXT("Failed to delete folder"), f, err);
				failures++;
			}
		} else {
			if (!DeleteFile(f) && (err = DeleteWithSH(f)) != 0) {
				LogFileError(TEXT("Failed to delete file"), f, GetLastError());
				failures++;
			} else {
				size += attrib.nFileSizeLow;
				size += ((ULONGLONG)attrib.nFileSizeHigh) << 32;
			}
		}
	}

	// Show results
	if (size < 1000)			_sntprintf(sSize, 64, TEXT("%I64d bytes"), size);
	else if (size < 1000000)	_sntprintf(sSize, 64, TEXT("%.2f KB"), size / 1024.0);
	else if (size < 1000000000)	_sntprintf(sSize, 64, TEXT("%.2f MB"), size / 1024 / 1024.0);
	else						_sntprintf(sSize, 64, TEXT("%.2f GB"), size / 1024 / 1024 / 1024.0);
	_tprintf(TEXT("Deleted %d files (%s)\n"), files->length-failures, sSize);
	if (failures > 0)
		_tprintf(TEXT("Failed to delete %d files\n"), failures);

	// Cleanup
	vector_destroy(files, TRUE);
	LocalFree(acl);
	LocalFree(sid);
	free_parsed_args(args);

	return 0;
}
Ejemplo n.º 22
0
/*! 
 *
 * Starts the job running and sets the status code to STATUS_RUNNING.
 * 
 * The windows implementation of this function opens a new process for
 * GAMESS and redirects stdout to a log file handle and redirects
 * stderr to NUL. The process is created in a suspended state, and the
 * added to a new windows job object before it is resumed.
 *
 * \par Notes of explanation concerning the implementation of Start:
 * In order to make cshell happy, you must provide it with valid standard
 * output and standard error handles. If either of the above is missing, cshell
 * will simply quit with an exit status of 1, and nothing will happen. Standard
 * output goes to the log file anyway, so that one is obvious. In order to
 * provide a valid standard error handle, I used the windows NUL file.
 *
 * \par
 * The process is created in a suspended state, added to the job object and
 * then resumed. The reason for this is because when you run a script with
 * cshell, the first thing it will do is fork and start running other processes
 * as described by the shell script. In order to make sure that all of its sub
 * processes are part of the job object, it must be added to the job object
 * before it has a chance to do anything. Since we have no guarantee as to when
 * the sub-process will start getting processor time, it is suspended until we
 * know it has been added to the job object.
 *
 * \sa WindowsJob::mProcessHandle
 * \sa WindowsJob::mJobHandle
 */
void WindowsJob::Start()
{
	// set this here, so we don't accidentally start it twice
	mStatus = STATUS_RUNNING;

	// try to find gamess
	wxString gamessname;
	if (gamessDir.IsEmpty()) {
		wxPathList SystemPath;
		SystemPath.AddEnvList(wxT("PATH"));
		gamessname = SystemPath.FindAbsoluteValidPath(wxT("rungms.bat"));
	} else {
		wxFileName name(gamessDir, wxT("rungms.bat"));
		name.MakeAbsolute();
		gamessname = name.GetFullPath();
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}

#ifdef DEFAULT_GAMESS_PATH
	if (gamessname.IsEmpty()) {
		wxStandardPathsBase& gStdPaths = wxStandardPaths::Get();
		gamessname = gStdPaths.GetResourcesDir() + wxT(DEFAULT_GAMESS_PATH) +
				wxT("/rungms.bat");
		if (! wxFileExists(gamessname)) {
			gamessname = wxT("");
		}
	}
#endif

	if (gamessname.IsEmpty()) {
		wxLogError(wxT("Could not find GAMESS"));
		mStatus = STATUS_ERROR;
		return;
	}

	// clean up old temp stuff so ddikick doesn't fail
	CleanUpTempFiles();

	wxFileName dest(GetSpoolFileName());
	dest = wxFileName(gamessDir + wxT("\\scratch"), dest.GetName());
	dest.SetExt(wxT("F05"));
	wxString debug = wxT("Copying file from ") + GetSpoolFileName();
	debug << wxT(" to ") << dest.GetFullPath();
	wxLogDebug(debug);
	wxCopyFile(GetSpoolFileName(), dest.GetFullPath(), true);


	// generate the command
	wxFileName name(gamessname);
	name.SetFullName(wxT("rungms.bat"));
//	name.SetFullName(wxT("csh.exe"));
//	name.MakeAbsolute();
	wxString command = name.GetFullPath();
//	name.SetFullName(wxT("runscript.csh"));
//	command << wxT(" -e -f ") << name.GetFullPath();
	name = wxFileName(GetSpoolFileName());
	command << wxT(" ") << name.GetName();
	command << wxT(" 13-64.pgi.linux.blas ");
	command << mNumProcessors;
//	command << wxT(" ") << gamessDir;
//	command << wxT(" ") << wxGetHostName();
	wxLogMessage(wxT("Exec: ") + command);

	// set up the security attributes for the input and output handles
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = true;

	// create a the log file and it's handle
	name.SetExt(wxT("log"));
	name.MakeAbsolute();
	HANDLE logFileHandle = CreateFile(name.GetFullPath(), GENERIC_WRITE,
			FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
	if (logFileHandle == INVALID_HANDLE_VALUE) {
		LOG_ERROR("CreateFile");
	}

	// make a null handle for stderr
	HANDLE nullHandle = CreateFile(wxT("NUL"), GENERIC_WRITE,
			FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
	if (nullHandle == INVALID_HANDLE_VALUE) {
		LOG_ERROR("CreateFile");
	}

	// create a new STARTUPINFO object with the newly created handles
	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.wShowWindow=SW_HIDE; // hide the window
	si.dwFlags=STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
	si.hStdOutput = logFileHandle;
	si.hStdInput = NULL;
	si.hStdError = nullHandle;

	// create a new PROCESS_INFORMATION object
	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));

	// create a new job
	mJobHandle = CreateJobObject(NULL, NULL);
	if (! mJobHandle) {
		LOG_ERROR("CreateJobObject");
	}

	// now we create the actual process, it needs to be created in a suspended
	// state so that we can assign it to the job object before it gets a chance
	// to spawn any more processes.
	if (CreateProcess(NULL, (wxChar *)command.wc_str(), NULL, NULL, true,
		CREATE_SUSPENDED, NULL, spoolDir, &si, &pi)) {
		if (! AssignProcessToJobObject(mJobHandle, pi.hProcess)) {
			LOG_ERROR("AssignProcessToJobObject");
		}
		mProcessHandle = pi.hProcess;
		ResumeThread(pi.hThread);
	} else {
		mStatus = STATUS_ERROR;
		LOG_ERROR("CreateProcess");
		mStatus = STATUS_ERROR;
		mProcessHandle = NULL;
		CloseHandle(pi.hProcess);
	}

	// close our side of the IO handles
	CloseHandle(logFileHandle);
	CloseHandle(nullHandle);

	// we don't need this one anymore
	CloseHandle(pi.hThread);
}
Ejemplo n.º 23
0
static BOOL CALLBACK SkinEdit_ExtBkDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
    SKINDESCRIPTION *psd = (SKINDESCRIPTION *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

    if(psd) {
        ID_EXTBK_FIRST = psd->firstItem;
        ID_EXTBK_LAST = psd->lastItem;
        StatusItems = psd->StatusItems;
    }
    switch (msg) {
        case WM_INITDIALOG:
            psd = (SKINDESCRIPTION *)malloc(sizeof(SKINDESCRIPTION));
            ZeroMemory(psd, sizeof(SKINDESCRIPTION));
            CopyMemory(psd, (void *)lParam, sizeof(SKINDESCRIPTION));
            SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)psd);

            if(psd) {
                ID_EXTBK_FIRST = psd->firstItem;
                ID_EXTBK_LAST = psd->lastItem;
                StatusItems = psd->StatusItems;
            }

            TranslateDialogDefault(hwndDlg);
            FillItemList(hwndDlg);
            SendMessage(hwndDlg, WM_USER + 101, 0, 0);

            psd->hMenuItems = CreatePopupMenu();
            AppendMenu(psd->hMenuItems, MF_STRING | MF_DISABLED, (UINT_PTR)0, _T("Copy from"));
            AppendMenuA(psd->hMenuItems, MF_SEPARATOR, (UINT_PTR)0, NULL);

            {
				int i;
				
				for(i = ID_EXTBK_FIRST; i <= ID_EXTBK_LAST; i++) {
					int iOff = StatusItems[i - ID_EXTBK_FIRST].szName[0] == '{' ? 3 : 0;
					if(iOff)
						AppendMenuA(psd->hMenuItems, MF_SEPARATOR, (UINT_PTR)0, NULL);
					AppendMenuA(psd->hMenuItems, MF_STRING, (UINT_PTR)i, &StatusItems[i - ID_EXTBK_FIRST].szName[iOff]);
				}
			}
            return TRUE;
        case WM_USER + 101:
            {
                SendDlgItemMessage(hwndDlg, IDC_MRGN_LEFT_SPIN, UDM_SETRANGE, 0, MAKELONG(100, 0));
                SendDlgItemMessage(hwndDlg, IDC_MRGN_TOP_SPIN, UDM_SETRANGE, 0, MAKELONG(100, 0));
                SendDlgItemMessage(hwndDlg, IDC_MRGN_RIGHT_SPIN, UDM_SETRANGE, 0, MAKELONG(100, 0));
                SendDlgItemMessage(hwndDlg, IDC_MRGN_BOTTOM_SPIN, UDM_SETRANGE, 0, MAKELONG(100, 0));
                SendDlgItemMessage(hwndDlg, IDC_ALPHASPIN, UDM_SETRANGE, 0, MAKELONG(100, 0));
                SendDlgItemMessage(hwndDlg, IDC_ALPHASPIN2, UDM_SETRANGE, 0, MAKELONG(100, 0));

                return 0;
            }

        case WM_DRAWITEM:
            {
                DRAWITEMSTRUCT *dis = (DRAWITEMSTRUCT *) lParam;
                int iItem = dis->itemData;
                TStatusItem *item = 0;

                SetBkMode(dis->hDC, TRANSPARENT);
                FillRect(dis->hDC, &dis->rcItem, GetSysColorBrush(COLOR_WINDOW));

                if(iItem >= ID_EXTBK_FIRST && iItem <= ID_EXTBK_LAST)
                    item = &StatusItems[iItem - ID_EXTBK_FIRST];

                if (dis->itemState & ODS_SELECTED && iItem != ID_EXTBKSEPARATOR) {
                    FillRect(dis->hDC, &dis->rcItem, GetSysColorBrush(COLOR_HIGHLIGHT));
                    SetTextColor(dis->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
                }
                else {
                    FillRect(dis->hDC, &dis->rcItem, GetSysColorBrush(COLOR_WINDOW));
                    if(item && item->IGNORED)
                        SetTextColor(dis->hDC, RGB(255, 0, 0));
                    else if(item && item->dwFlags & S_ITEM_IMAGE_ONLY)
                    	SetTextColor(dis->hDC, RGB(0, 0, 255));
                    else
                        SetTextColor(dis->hDC, GetSysColor(COLOR_WINDOWTEXT));
                }
                if(iItem == ID_EXTBKSEPARATOR) {
                    HPEN    hPen, hPenOld;
                    POINT   pt;

                    hPen = CreatePen(PS_SOLID, 2, GetSysColor(COLOR_WINDOWTEXT));
                    hPenOld = (HPEN)SelectObject(dis->hDC, hPen);

                    MoveToEx(dis->hDC, dis->rcItem.left, (dis->rcItem.top + dis->rcItem.bottom) / 2, &pt);
                    LineTo(dis->hDC, dis->rcItem.right, (dis->rcItem.top + dis->rcItem.bottom) / 2);
                    SelectObject(dis->hDC, hPenOld);
                    DeleteObject((HGDIOBJ)hPen);
                }
                else if(dis->itemID >= 0 && item) {
                    char   *szName = item->szName[0] == '{' ? &item->szName[3] : item->szName;

                    TextOutA(dis->hDC, dis->rcItem.left, dis->rcItem.top, szName, lstrlenA(szName));
                }
                return TRUE;
            }

        case WM_CONTEXTMENU:
            {
                POINT pt;
                RECT  rc;
                HWND hwndList = GetDlgItem(hwndDlg, IDC_ITEMS);

                GetCursorPos(&pt);
                GetWindowRect(hwndList, &rc);
                if(PtInRect(&rc, pt)) {
                    int iSelection = (int)TrackPopupMenu(psd->hMenuItems, TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL);

                    if(iSelection >= ID_EXTBK_FIRST && iSelection <= ID_EXTBK_LAST) {
                        iSelection -= ID_EXTBK_FIRST;

                        for(int i = ID_EXTBK_FIRST; i <= ID_EXTBK_LAST; i++) {
                            if(SendMessage(hwndList, LB_GETSEL, i - ID_EXTBK_FIRST, 0) > 0) {
                                int iIndex = SendMessage(hwndList, LB_GETITEMDATA, i - ID_EXTBK_FIRST, 0);
                                iIndex -= ID_EXTBK_FIRST;

                                if(iIndex >= 0) {
                                    StatusItems[iIndex].ALPHA = StatusItems[iSelection].ALPHA;
                                    StatusItems[iIndex].COLOR = StatusItems[iSelection].COLOR;
                                    StatusItems[iIndex].COLOR2 = StatusItems[iSelection].COLOR2;
                                    StatusItems[iIndex].ALPHA2 = StatusItems[iSelection].ALPHA2;
                                    StatusItems[iIndex].CORNER = StatusItems[iSelection].CORNER;
                                    StatusItems[iIndex].GRADIENT = StatusItems[iSelection].GRADIENT;
                                    StatusItems[iIndex].IGNORED = StatusItems[iSelection].IGNORED;
                                    StatusItems[iIndex].imageItem = StatusItems[iSelection].imageItem;
                                    StatusItems[iIndex].MARGIN_BOTTOM = StatusItems[iSelection].MARGIN_BOTTOM;
                                    StatusItems[iIndex].MARGIN_LEFT = StatusItems[iSelection].MARGIN_LEFT;
                                    StatusItems[iIndex].MARGIN_RIGHT = StatusItems[iSelection].MARGIN_RIGHT;
                                    StatusItems[iIndex].MARGIN_TOP = StatusItems[iSelection].MARGIN_TOP;
                                    StatusItems[iIndex].TEXTCOLOR = StatusItems[iSelection].TEXTCOLOR;
                                    StatusItems[iIndex].dwFlags = StatusItems[iSelection].dwFlags;
                                }
                            }
                        }
                        OnListItemsChange(hwndDlg);
                    }
                }
                break;
            }
        case WM_COMMAND:
    // this will check if the user changed some actual statusitems values
    // if yes the flag bChanged will be set to TRUE
            SetChangedStatusItemFlag(wParam, hwndDlg);
            switch(LOWORD(wParam)) {
                case IDC_ITEMS:
                    if (HIWORD(wParam) != LBN_SELCHANGE)
                        return FALSE;
                    {
                        int iItem = SendDlgItemMessage(hwndDlg, IDC_ITEMS, LB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_ITEMS, LB_GETCURSEL, 0, 0), 0);
                        if(iItem == ID_EXTBKSEPARATOR)
                            return FALSE;
                    }
                    OnListItemsChange(hwndDlg);
					if(psd->pfnClcOptionsChanged)
						psd->pfnClcOptionsChanged();
                    break;
                case IDC_SKIP_UNDERLAY:
                case IDC_SKIP_IMAGE:
                case IDC_GRADIENT:
                case IDC_CORNER:
                case IDC_IGNORE:
                    ReActiveCombo(hwndDlg);
                    break;
            }
            if ((LOWORD(wParam) == IDC_ALPHA || LOWORD(wParam) == IDC_ALPHA2 || LOWORD(wParam) == IDC_MRGN_LEFT || LOWORD(wParam) == IDC_MRGN_BOTTOM || LOWORD(wParam) == IDC_MRGN_TOP || LOWORD(wParam) == IDC_MRGN_RIGHT) && (HIWORD(wParam) != EN_CHANGE || (HWND) lParam != GetFocus()))
                return 0;
            SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
            break;

        case WM_NOTIFY:
            switch (((LPNMHDR) lParam)->idFrom) {
                case 0:
                    switch (((LPNMHDR) lParam)->code) {
                        case PSN_APPLY:
                // save user made changes
                            SaveLatestChanges(hwndDlg);
                // save struct to DB
							if(psd->pfnSaveCompleteStruct)
								psd->pfnSaveCompleteStruct();

                            if(psd->pfnClcOptionsChanged)
								psd->pfnClcOptionsChanged();
							if(psd->hwndCLUI) {
								SendMessage(psd->hwndCLUI, WM_SIZE, 0, 0);
								PostMessage(psd->hwndCLUI, WM_USER+100, 0, 0);          // CLUIINTM_REDRAW
							}
                            break;
                    }
            }
            break;
        case WM_DESTROY:
            DestroyMenu(psd->hMenuItems);
            break;
        case WM_NCDESTROY:
            free(psd);
            SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)0);
            break;
    }
    return FALSE;
}
Ejemplo n.º 24
0
BOOL Notepad_plus::notify(SCNotification *notification)
{
	//Important, keep track of which element generated the message
	bool isFromPrimary = (_mainEditView.getHSelf() == notification->nmhdr.hwndFrom || _mainDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	bool isFromSecondary = !isFromPrimary && (_subEditView.getHSelf() == notification->nmhdr.hwndFrom || _subDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	ScintillaEditView * notifyView = isFromPrimary?&_mainEditView:&_subEditView;
	DocTabView *notifyDocTab = isFromPrimary?&_mainDocTab:&_subDocTab;
	TBHDR * tabNotification = (TBHDR*) notification;
	switch (notification->nmhdr.code) 
	{
		case SCN_MODIFIED:
		{
			static bool prevWasEdit = false;
			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT))
			{
				_pEditView->updateBeginEndSelectPosition(notification->modificationType & SC_MOD_INSERTTEXT, notification->position, notification->length);
				prevWasEdit = true;
				_linkTriggered = true;
				::InvalidateRect(notifyView->getHSelf(), NULL, TRUE);
			}

			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO))
			{
				// for the backup system
				_pEditView->getCurrentBuffer()->setModifiedStatus(true);
			}

			if (notification->modificationType & SC_MOD_CHANGEFOLD)
			{
				if (prevWasEdit) 
				{
					notifyView->foldChanged(notification->line, notification->foldLevelNow, notification->foldLevelPrev);
					prevWasEdit = false;
				}
			}
			else if (!(notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT)))
			{
				prevWasEdit = false;
			}


		}
		break;

		case SCN_SAVEPOINTREACHED:
		case SCN_SAVEPOINTLEFT:
		{
			Buffer * buf = 0;
			if (isFromPrimary)
			{
				buf = _mainEditView.getCurrentBuffer();
			}
			else if (isFromSecondary)
			{
				buf = _subEditView.getCurrentBuffer();
			}
			else
			{
				//Done by invisibleEditView?
				BufferID id = BUFFER_INVALID;
				if (notification->nmhdr.hwndFrom == _invisibleEditView.getHSelf()) 
				{
					id = MainFileManager->getBufferFromDocument(_invisibleEditView.execute(SCI_GETDOCPOINTER));
				}
				else if (notification->nmhdr.hwndFrom == _fileEditView.getHSelf())
				{
					id = MainFileManager->getBufferFromDocument(_fileEditView.execute(SCI_GETDOCPOINTER));
				}
				else 
				{
					break;	//wrong scintilla
				}

				if (id != BUFFER_INVALID)
				{
					buf = MainFileManager->getBufferByID(id);
				}
				else
				{
					break;
				}
			}
			bool isDirty = notification->nmhdr.code == SCN_SAVEPOINTLEFT;
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode && !isDirty)
			{
				bool canUndo = _pEditView->execute(SCI_CANUNDO) == TRUE;
				if (!canUndo && buf->isLoadedDirty())
					isDirty = true;
			}
			buf->setDirty(isDirty);
			break; 
		}

		case  SCN_MODIFYATTEMPTRO :
			// on fout rien
			break;

		case SCN_KEY:
			break;

	case TCN_TABDROPPEDOUTSIDE:
	case TCN_TABDROPPED:
	{
        TabBarPlus *sender = reinterpret_cast<TabBarPlus *>(notification->nmhdr.idFrom);
        bool isInCtrlStat = (::GetKeyState(VK_LCONTROL) & 0x80000000) != 0;
        if (notification->nmhdr.code == TCN_TABDROPPEDOUTSIDE)
        {
            POINT p = sender->getDraggingPoint();

			//It's the coordinate of screen, so we can call 
			//"WindowFromPoint" function without converting the point
            HWND hWin = ::WindowFromPoint(p);
			if (hWin == _pEditView->getHSelf()) // In the same view group
			{
				if (!_tabPopupDropMenu.isCreated())
				{
					TCHAR goToView[32] = TEXT("Move to other view");
					TCHAR cloneToView[32] = TEXT("Clone to other View");
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, goToView));
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, cloneToView));
					_tabPopupDropMenu.create(_pPublicInterface->getHSelf(), itemUnitArray, _mainMenuHandle);
					_nativeLangSpeaker.changeLangTabDrapContextMenu(_tabPopupDropMenu.getMenuHandle());
				}
				_tabPopupDropMenu.display(p);
			}
			else if ((hWin == _pNonDocTab->getHSelf()) || 
				     (hWin == _pNonEditView->getHSelf())) // In the another view group
			{
                docGotoAnotherEditView(isInCtrlStat?TransferClone:TransferMove);
			}/*
			else if ((hWin == _pProjectPanel_1->getTreeHandle()))
			{
				
                //printStr(TEXT("IN!!!"));
			}*/
			else
			{
				RECT nppZone;
				::GetWindowRect(_pPublicInterface->getHSelf(), &nppZone);
				bool isInNppZone = (((p.x >= nppZone.left) && (p.x <= nppZone.right)) && (p.y >= nppZone.top) && (p.y <= nppZone.bottom));
				if (isInNppZone)
				{
					// Do nothing
					return TRUE;
				}
				generic_string quotFileName = TEXT("\"");
				quotFileName += _pEditView->getCurrentBuffer()->getFullPathName();
				quotFileName += TEXT("\"");
				COPYDATASTRUCT fileNamesData;
				fileNamesData.dwData = COPYDATA_FILENAMES;
				fileNamesData.lpData = (void *)quotFileName.c_str();
				fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR));

				HWND hWinParent = ::GetParent(hWin);
				TCHAR className[MAX_PATH];
				::GetClassName(hWinParent,className, sizeof(className));
				if (lstrcmp(className, _pPublicInterface->getClassName()) == 0 && hWinParent != _pPublicInterface->getHSelf()) // another Notepad++
				{
					int index = _pDocTab->getCurrentTabIndex();
					BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
					Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
					int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
					if (buf->isDirty()) 
					{
						generic_string msg, title;
						_nativeLangSpeaker.messageBox("CannotMoveDoc",
							_pPublicInterface->getHSelf(),
							TEXT("Document is modified, save it then try again."),
							TEXT("Move to new Notepad++ Instance"),
							MB_OK);
					}
					else
					{
						::SendMessage(hWinParent, NPPM_INTERNAL_SWITCHVIEWFROMHWND, 0, (LPARAM)hWin);
						::SendMessage(hWinParent, WM_COPYDATA, (WPARAM)_pPublicInterface->getHinst(), (LPARAM)&fileNamesData);
                        if (!isInCtrlStat)
						{
							fileClose(bufferToClose, iView);
							if (noOpenedDoc())
								::SendMessage(_pPublicInterface->getHSelf(), WM_CLOSE, 0, 0);
						}
					}
				}
                else // Not Notepad++, we open it here
                {
					docOpenInNewInstance(isInCtrlStat?TransferClone:TransferMove, p.x, p.y);
                }
			}
        }
		//break;
		sender->resetDraggingPoint();
		return TRUE;
	}

	case TCN_TABDELETE:
	{
		int index = tabNotification->tabOrigin;
		BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
		Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
		int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
		if (buf->isDirty())
		{
			activateBuffer(bufferToClose, iView);
		}
		fileClose(bufferToClose, iView);
		break;
	}

	case TCN_SELCHANGE:
	{
		int iView = -1;
        if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
			iView = MAIN_VIEW;
		}
		else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
		{
			iView = SUB_VIEW;
		}
		else
		{
			break;
		}

		switchEditViewTo(iView);
		BufferID bufid = _pDocTab->getBufferByIndex(_pDocTab->getCurrentTabIndex());
		if (bufid != BUFFER_INVALID)
			activateBuffer(bufid, iView);
		
		break;
	}

	case NM_CLICK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_TYPING_MODE))
			{
				bool isOverTypeMode = (_pEditView->execute(SCI_GETOVERTYPE) != 0);
				_pEditView->execute(SCI_SETOVERTYPE, !isOverTypeMode);
				_statusBar.setText((_pEditView->execute(SCI_GETOVERTYPE))?TEXT("OVR"):TEXT("INS"), STATUSBAR_TYPING_MODE);
			}
        }
		else if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf() && _activeView == SUB_VIEW)
		{
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf() && _activeView == MAIN_VIEW)
        {
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(SUB_VIEW);
        }

		break;
	}

	case NM_DBLCLK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_CUR_POS))
			{
				bool isFirstTime = !_goToLineDlg.isCreated();
                _goToLineDlg.doDialog(_nativeLangSpeaker.isRTL());
				if (isFirstTime)
                    _nativeLangSpeaker.changeDlgLang(_goToLineDlg.getHSelf(), "GoToLine");
			}
            else if (lpnm->dwItemSpec == DWORD(STATUSBAR_DOC_SIZE))
			{
				command(IDM_VIEW_SUMMARY);
			}
        }
		break;
	}

    case NM_RCLICK :
    {
		POINT p;
		::GetCursorPos(&p);

		if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
        {
            switchEditViewTo(SUB_VIEW);
        }
		else if (_pFileSwitcherPanel && notification->nmhdr.hwndFrom == _pFileSwitcherPanel->getHSelf())
        {
			// Already switched, so do nothing here.

			if (_pFileSwitcherPanel->nbSelectedFiles() > 1)
			{
				if (!_fileSwitcherMultiFilePopupMenu.isCreated())
				{
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSE, TEXT("Close Selected files")));
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSEOTHERS, TEXT("Close others files")));

					_fileSwitcherMultiFilePopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
					_nativeLangSpeaker.changeLangTabContextMenu(_fileSwitcherMultiFilePopupMenu.getMenuHandle());
				}
				_fileSwitcherMultiFilePopupMenu.display(p);
				return TRUE;
			}
		}
		else // From tool bar or Status Bar
			return TRUE;
			//break;

		if (!_tabPopupMenu.isCreated())
		{
			vector<MenuItemUnit> itemUnitArray;
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSE, TEXT("Close")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_BUT_CURRENT, TEXT("Close All BUT This")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TOLEFT, TEXT("Close All to the Left")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TORIGHT, TEXT("Close All to the Right")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVE, TEXT("Save")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVEAS, TEXT("Save As...")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RENAME, TEXT("Rename")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_DELETE, TEXT("Move to Recycle Bin")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RELOAD, TEXT("Reload")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_PRINT, TEXT("Print")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_FOLDER, TEXT("Open Containing Folder in Explorer")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_CMD, TEXT("Open Containing Folder in cmd")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_SETREADONLY, TEXT("Read-Only")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CLEARREADONLY, TEXT("Clear Read-Only Flag")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FULLPATHTOCLIP,	TEXT("Full File Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FILENAMETOCLIP,   TEXT("Filename to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CURRENTDIRTOCLIP, TEXT("Current Dir. Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, TEXT("Move to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, TEXT("Clone to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_NEW_INSTANCE, TEXT("Move to New Instance")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_LOAD_IN_NEW_INSTANCE, TEXT("Open in New Instance")));

			_tabPopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
            _nativeLangSpeaker.changeLangTabContextMenu(_tabPopupMenu.getMenuHandle());
		}

		bool isEnable = ((::GetMenuState(_mainMenuHandle, IDM_FILE_SAVE, MF_BYCOMMAND)&MF_DISABLED) == 0);
		_tabPopupMenu.enableItem(IDM_FILE_SAVE, isEnable);
		
		Buffer * buf = _pEditView->getCurrentBuffer();
		bool isUserReadOnly = buf->getUserReadOnly();
		_tabPopupMenu.checkItem(IDM_EDIT_SETREADONLY, isUserReadOnly);

		bool isSysReadOnly = buf->getFileReadOnly();
		_tabPopupMenu.enableItem(IDM_EDIT_SETREADONLY, !isSysReadOnly);
		_tabPopupMenu.enableItem(IDM_EDIT_CLEARREADONLY, isSysReadOnly);

		bool isFileExisting = PathFileExists(buf->getFullPathName()) != FALSE;
		_tabPopupMenu.enableItem(IDM_FILE_DELETE, isFileExisting);
		_tabPopupMenu.enableItem(IDM_FILE_RENAME, isFileExisting);

		bool isDirty = buf->isDirty();
		bool isUntitled = buf->isUntitled();
		_tabPopupMenu.enableItem(IDM_VIEW_GOTO_NEW_INSTANCE, !(isDirty||isUntitled));
		_tabPopupMenu.enableItem(IDM_VIEW_LOAD_IN_NEW_INSTANCE, !(isDirty||isUntitled));

		_tabPopupMenu.display(p);
		return TRUE;
    }

    
	case SCN_MARGINCLICK:
    {
        if (notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
            switchEditViewTo(MAIN_VIEW);
		else if (notification->nmhdr.hwndFrom == _subEditView.getHSelf())
            switchEditViewTo(SUB_VIEW);

        int lineClick = int(_pEditView->execute(SCI_LINEFROMPOSITION, notification->position));
        
		if (notification->margin == ScintillaEditView::_SC_MARGE_FOLDER)
        {
            _pEditView->marginClick(notification->position, notification->modifiers);
			if (_pDocMap)
				_pDocMap->fold(lineClick, _pEditView->isFolded(lineClick));
        }
        else if ((notification->margin == ScintillaEditView::_SC_MARGE_SYBOLE) && !notification->modifiers)
        {
			if (!_pEditView->markerMarginClick(lineClick))
				bookmarkToggle(lineClick);
        }
		break;
	}

	case SCN_FOLDINGSTATECHANGED :
	{
		if ((notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
		|| (notification->nmhdr.hwndFrom == _subEditView.getHSelf()))
		{
			int lineClicked = notification->line;
			
			if (!_isFolding)
			{
				int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
				if ((urlAction == 1) || (urlAction == 2))
					addHotSpot();
			}

			if (_pDocMap)
				_pDocMap->fold(lineClicked, _pEditView->isFolded(lineClicked));
		}
		return TRUE;
	}

	case SCN_CHARADDED:
	{
		const NppGUI & nppGui = NppParameters::getInstance()->getNppGUI();
		bool indentMaintain = nppGui._maitainIndent;
		if (indentMaintain)
			maintainIndentation(static_cast<TCHAR>(notification->ch));
		
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		
		if (nppGui._matchedPairConf.hasAnyPairsPair())
			autoC->insertMatchedChars(notification->ch, nppGui._matchedPairConf);
		autoC->update(notification->ch);

		break;
	}

	case SCN_DOUBLECLICK :
	{
		if(notification->modifiers == SCMOD_CTRL)
		{
			const NppGUI & nppGUI = NppParameters::getInstance()->getNppGUI();

			std::string bufstring;
			unsigned int position_of_click;

			// Anonymous scope to limit use of the buf pointer (much easier to deal with std::string).
			{
				char *buf;
				int length;
				
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					// Get entire document.
					length = notifyView->execute(SCI_GETLENGTH);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETTEXT, (LPARAM)(length + 1), (WPARAM)buf);

					// For some reason Ctrl+DoubleClick on an empty line means that notification->position == 1.
					// In that case we use SCI_GETCURRENTPOS to get the position.
					if(notification->position != -1)
						position_of_click = notification->position;
					else
						position_of_click = int(_pEditView->execute(SCI_GETCURRENTPOS));
				}
				else
				{
					// Get single line.
					length = notifyView->execute(SCI_GETCURLINE);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETCURLINE, (WPARAM)length, (LPARAM)buf);

					// Compute the position of the click (relative to the beginning of the line).
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					position_of_click = notification->position - line_position;
				}

				bufstring = buf;
				delete [] buf;
			}

			int leftmost_position = -1;
			int rightmost_position = -1;

			if(nppGUI._rightmostDelimiter == nppGUI._leftmostDelimiter)
			{
				// If the delimiters are the same (e.g. they are both a quotation mark), choose the ones
				// which are closest to the clicked position.

				for(unsigned int i = position_of_click; i >= 0; --i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._leftmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								leftmost_position = i;
								break;
							}
						}
						else
						{
							leftmost_position = i;
							break;
						}
					}
				}

				if(leftmost_position == -1)
					break;

				// Scan for right delimiter.
				for(unsigned int i = position_of_click; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._rightmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._rightmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								rightmost_position = i;
								break;
							}
						}
						else
						{
							rightmost_position = i;
							break;
						}
					}
				}
			}
			else
			{
				// Find matching pairs of delimiters (e.g. parantheses).
				// The pair where the distance from the left delimiter to position_of_click is at a minimum is the one we're looking for.
				// Of course position_of_click must lie between the delimiters.

				// This logic is required to handle cases like this:
				// (size_t i = function(); i < _buffers.size(); i++)

				std::stack<unsigned int> leftmost_delimiter_positions;

				for(unsigned int i = 0; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
						leftmost_delimiter_positions.push(i);
					else if(bufstring.at(i) == nppGUI._rightmostDelimiter && ! leftmost_delimiter_positions.empty())
					{
						unsigned int matching_leftmost = leftmost_delimiter_positions.top();
						leftmost_delimiter_positions.pop();

						// We have either 1) chosen neither the left- or rightmost position, or 2) chosen both left- and rightmost position.
						assert( (leftmost_position == -1 && rightmost_position == -1) || (leftmost_position >= 0 && rightmost_position >= 0) );

						// Note: cast of leftmost_position to unsigned int is safe, since if leftmost_position is not -1 then it is guaranteed to be positive.
						// If it was possible, leftmost_position and rightmost_position should be of type optional<unsigned int>.
						if( matching_leftmost <= position_of_click && i >= position_of_click &&  (leftmost_position == -1 ||  matching_leftmost > (unsigned int)leftmost_position) )
						{
							leftmost_position = matching_leftmost;
							rightmost_position = i;
						}
					}
				}
			}

			// Set selection to the position we found (if any).
			if(rightmost_position != -1 && leftmost_position != -1)
			{
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					notifyView->execute(SCI_SETCURRENTPOS, rightmost_position);
					notifyView->execute(SCI_SETANCHOR, leftmost_position + 1);
				}
				else
				{
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					notifyView->execute(SCI_SETCURRENTPOS, line_position + rightmost_position);
					notifyView->execute(SCI_SETANCHOR, line_position + leftmost_position + 1);
				}
			}
		}
		else if (_isHotspotDblClicked)
		{
			int pos = notifyView->execute(SCI_GETCURRENTPOS);
			notifyView->execute(SCI_SETCURRENTPOS, pos);
			notifyView->execute(SCI_SETANCHOR, pos);
			_isHotspotDblClicked = false;
		}

		//display dialog, this dialog display current line information(ymj)
		//only my Log file need to display line info dialog
		//if(MainFileManager->isConvertFile())  //maybe have some problem
		BufferID id = _pEditView->getCurrentBufferID();
		
		if(id != BUFFER_INVALID)
		{
			Buffer *buf = MainFileManager->getBufferByID(id);

			if(buf->isConvertFile())
			{
				int tmpLength = notifyView->execute(SCI_GETCURLINE);
				if(tmpLength < (1024 * 8))
				{
					char *buf = _lineDetailInfoDlg.getLineContentBuf();
					memset(buf, 0x00, tmpLength + 1);
					notifyView->execute(SCI_GETCURLINE, (LPARAM)(tmpLength + 1), (WPARAM)buf);

					bool isFirstTime = !_lineDetailInfoDlg.isCreated();
					_lineDetailInfoDlg.doDialog(_nativeLangSpeaker.isRTL());
					if (isFirstTime)
						_nativeLangSpeaker.changeDlgLang(_lineDetailInfoDlg.getHSelf(), "LineInfo");

					_lineDetailInfoDlg.DisplayLineInfo(tmpLength);

					
				}
			}
		}
	}
	break;

	case SCN_UPDATEUI:
	{
		NppParameters *nppParam = NppParameters::getInstance();

		// replacement for obsolete custom SCN_SCROLLED
		if (notification->updated & SC_UPDATE_V_SCROLL)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
		}

		// if it's searching/replacing, then do nothing
		if (nppParam->_isFindReplacing)
			break;

		if (notification->nmhdr.hwndFrom != _pEditView->getHSelf())
			break;
		
        braceMatch();

		NppGUI & nppGui = (NppGUI &)nppParam->getNppGUI();

		if (nppGui._enableTagsMatchHilite)
		{
			XmlMatchedTagsHighlighter xmlTagMatchHiliter(_pEditView);
			xmlTagMatchHiliter.tagMatch(nppGui._enableTagAttrsHilite);
		}
		
		if (nppGui._enableSmartHilite)
		{
			if (nppGui._disableSmartHiliteTmp)
				nppGui._disableSmartHiliteTmp = false;
			else
				_smartHighlighter.highlightView(notifyView);
		}

		updateStatusBar();
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->update(0);

        break;
	}

    case TTN_GETDISPINFO:
    {
		try {
			LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)notification; 

			//Joce's fix
			lpttt->hinst = NULL; 

			POINT p;
			::GetCursorPos(&p);
			::ScreenToClient(_pPublicInterface->getHSelf(), &p);
			HWND hWin = ::RealChildWindowFromPoint(_pPublicInterface->getHSelf(), p);
			const int tipMaxLen = 1024;
			static TCHAR docTip[tipMaxLen];
			docTip[0] = '\0';

			generic_string tipTmp(TEXT(""));
			int id = int(lpttt->hdr.idFrom);

			if (hWin == _rebarTop.getHSelf())
			{
				getNameStrFromCmd(id, tipTmp);
				if (tipTmp.length() >= 80)
					return FALSE;

				lstrcpy(lpttt->szText, tipTmp.c_str());
				return TRUE;
			}
			else if (hWin == _mainDocTab.getHSelf())
			{
				BufferID idd = _mainDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else if (hWin == _subDocTab.getHSelf())
			{
				BufferID idd = _subDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		} catch (...) {
			//printStr(TEXT("ToolTip crash is caught!"));
		}
    }
	break;


    case SCN_ZOOM:
		break;

    case SCN_MACRORECORD:
        _macro.push_back(recordedMacroStep(notification->message, notification->wParam, notification->lParam, _pEditView->execute(SCI_GETCODEPAGE)));
		break;

	case SCN_PAINTED:
	{
		//--FLS: ViewMoveAtWrappingDisableFix: Disable wrapping messes up visible lines. Therefore save view position before in IDM_VIEW_WRAP and restore after SCN_PAINTED, as doc. says
		if (_mainEditView.isWrapRestoreNeeded())
		{
			_mainEditView.restoreCurrentPos();
			_mainEditView.setWrapRestoreNeeded(false);
		}

		if (_subEditView.isWrapRestoreNeeded())
		{
			_subEditView.restoreCurrentPos();
			_subEditView.setWrapRestoreNeeded(false);
		}
		notifyView->updateLineNumberWidth();
		if (_syncInfo.doSync()) 
			doSynScorll(HWND(notification->nmhdr.hwndFrom));

		NppParameters *nppParam = NppParameters::getInstance();
		
		// if it's searching/replacing, then do nothing
		if ((_linkTriggered && !nppParam->_isFindReplacing) || notification->wParam == LINKTRIGGERED)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
			_linkTriggered = false;
		}

		if (_pDocMap)
		{
			_pDocMap->wrapMap();
			_pDocMap->scrollMap();
		}
		break;
	}

	case SCN_HOTSPOTDOUBLECLICK :
	{
		notifyView->execute(SCI_SETWORDCHARS, 0, (LPARAM)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+.,:?&@=/%#()");
		
		int pos = notifyView->execute(SCI_GETCURRENTPOS);
		int startPos = static_cast<int>(notifyView->execute(SCI_WORDSTARTPOSITION, pos, false));
		int endPos = static_cast<int>(notifyView->execute(SCI_WORDENDPOSITION, pos, false));

		notifyView->execute(SCI_SETTARGETSTART, startPos);
		notifyView->execute(SCI_SETTARGETEND, endPos);
	
		int posFound = notifyView->execute(SCI_SEARCHINTARGET, strlen(URL_REG_EXPR), (LPARAM)URL_REG_EXPR);
		if (posFound != -2)
		{
			if (posFound != -1)
			{
				startPos = int(notifyView->execute(SCI_GETTARGETSTART));
				endPos = int(notifyView->execute(SCI_GETTARGETEND));
			}

			// Prevent buffer overflow in getGenericText().
			if(endPos - startPos > 2*MAX_PATH)
				endPos = startPos + 2*MAX_PATH;

			TCHAR currentWord[2*MAX_PATH];

			notifyView->getGenericText(currentWord, MAX_PATH*2, startPos, endPos);

			// This treatment would fail on some valid URLs where there's actually supposed to be a comma or parenthesis at the end.
			int lastCharIndex = _tcsnlen(currentWord, MAX_PATH*2) - 1;
			if(lastCharIndex >= 0 && (currentWord[lastCharIndex] == ',' || currentWord[lastCharIndex] == ')' || currentWord[lastCharIndex] == '('))
				currentWord[lastCharIndex] = '\0';

			::ShellExecute(_pPublicInterface->getHSelf(), TEXT("open"), currentWord, NULL, NULL, SW_SHOW);
			_isHotspotDblClicked = true;
			notifyView->execute(SCI_SETCHARSDEFAULT);
		}
		break;
	}

	case SCN_NEEDSHOWN :
	{
		int begin = notifyView->execute(SCI_LINEFROMPOSITION, notification->position);
		int end = notifyView->execute(SCI_LINEFROMPOSITION, notification->position + notification->length);
		int firstLine = begin < end ? begin : end;
		int lastLine = begin > end ? begin : end;
		for (int line = firstLine; line <= lastLine; ++line)
		{
			notifyView->execute(SCI_ENSUREVISIBLE, line, 0);
		}
		break;
	}

	case SCN_CALLTIPCLICK:
	{
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->callTipClick(notification->position);
		break;
	}

	case RBN_HEIGHTCHANGE:
	{
		SendMessage(_pPublicInterface->getHSelf(), WM_SIZE, 0, 0);
		break;
	}
	case RBN_CHEVRONPUSHED:
	{
		NMREBARCHEVRON * lpnm = (NMREBARCHEVRON*) notification;
		ReBar * notifRebar = &_rebarTop;
		if (_rebarBottom.getHSelf() == lpnm->hdr.hwndFrom)
			notifRebar = &_rebarBottom;
		//If N++ ID, use proper object
		switch(lpnm->wID) {
			case REBAR_BAR_TOOLBAR: {
				POINT pt;
				pt.x = lpnm->rc.left;
				pt.y = lpnm->rc.bottom;
				ClientToScreen(notifRebar->getHSelf(), &pt);
				_toolBar.doPopop(pt);
				return TRUE;
				break; }
		}
		//Else forward notification to window of rebarband
		REBARBANDINFO rbBand;
		ZeroMemory(&rbBand, REBARBAND_SIZE);
		rbBand.cbSize  = REBARBAND_SIZE;

		rbBand.fMask = RBBIM_CHILD;
		::SendMessage(notifRebar->getHSelf(), RB_GETBANDINFO, lpnm->uBand, (LPARAM)&rbBand);
		::SendMessage(rbBand.hwndChild, WM_NOTIFY, 0, (LPARAM)lpnm);
		break;
	}

	default :
		break;

  }
  return FALSE;
}
Ejemplo n.º 25
0
bool CDirDialog::DoBrowse()
{
  LPMALLOC pMalloc;
  if( SHGetMalloc( &pMalloc ) != NOERROR )
    return false;

  BROWSEINFO bInfo;
  LPITEMIDLIST pidl;
  ZeroMemory( (PVOID)&bInfo, sizeof( BROWSEINFO ) );

  if( !m_strInitDir.IsEmpty() )
  {
    OLECHAR       olePath[MAX_PATH];
    ULONG         chEaten;
    ULONG         dwAttributes;
    HRESULT       hr;
    LPSHELLFOLDER pDesktopFolder;
    // 
    // Get a pointer to the Desktop's IShellFolder interface. 
    //
    if( SUCCEEDED( SHGetDesktopFolder( &pDesktopFolder ) ) )
    {
      //
      // IShellFolder::ParseDisplayName requires the file name be in Unicode.
      //
      MultiByteToWideChar( 
				CP_ACP, MB_PRECOMPOSED, 
				m_strInitDir.GetBuffer(MAX_PATH), -1,
        olePath, MAX_PATH );
      m_strInitDir.ReleaseBuffer( -1 );
      //
      // Convert the path to an ITEMIDLIST.
      //
      hr = pDesktopFolder->ParseDisplayName(
				NULL, NULL, olePath, &chEaten, &pidl, &dwAttributes );
      if( FAILED( hr ) )
      {
        pMalloc->Free( pidl );
        pMalloc->Release();
		    return false;
      }
      bInfo.pidlRoot = pidl;
    }
  }
  bInfo.hwndOwner = m_hwndOwner;
  bInfo.pszDisplayName = m_strPath.GetBuffer( MAX_PATH );
  bInfo.lpszTitle = m_strTitle;
  bInfo.ulFlags = BIF_RETURNFSANCESTORS|BIF_RETURNONLYFSDIRS;
  bInfo.lpfn = BrowseCtrlCallback;  // address of callback function
  bInfo.lParam = (LPARAM)this;      // pass address of object to callback function

  if( ( pidl = ::SHBrowseForFolder( &bInfo ) ) == NULL )
    return false;

  m_strPath.ReleaseBuffer();
  m_iImageIndex = bInfo.iImage;

  if( ::SHGetPathFromIDList( pidl, m_strPath.GetBuffer( MAX_PATH ) ) == FALSE )
  {
    pMalloc->Free( pidl );
    pMalloc->Release();
    return false;
  }

  m_strPath.ReleaseBuffer();

  pMalloc->Free( pidl );
  pMalloc->Release();

  return true;
}
Ejemplo n.º 26
0
static LRESULT CALLBACK
MonthCalWndProc(IN HWND hwnd,
                IN UINT uMsg,
                IN WPARAM wParam,
                IN LPARAM lParam)
{
    PMONTHCALWND infoPtr;
    LRESULT Ret = 0;

    infoPtr = (PMONTHCALWND)GetWindowLongPtrW(hwnd,
                                              0);

    if (infoPtr == NULL && uMsg != WM_CREATE)
    {
        goto HandleDefaultMessage;
    }

    switch (uMsg)
    {
#if MONTHCAL_CTRLBG != MONTHCAL_DISABLED_CTRLBG
        case WM_ERASEBKGND:
            Ret = !infoPtr->Enabled;
            break;
#endif

        case WM_PAINT:
        case WM_PRINTCLIENT:
        {
            if (infoPtr->CellSize.cx != 0 && infoPtr->CellSize.cy != 0)
            {
                PAINTSTRUCT ps;
                HDC hDC;

                if (wParam != 0)
                {
                    if (!GetUpdateRect(hwnd,
                                       &ps.rcPaint,
                                       TRUE))
                    {
                        break;
                    }
                    hDC = (HDC)wParam;
                }
                else
                {
                    hDC = BeginPaint(hwnd,
                                     &ps);
                    if (hDC == NULL)
                    {
                        break;
                    }
                }

                MonthCalPaint(infoPtr,
                              hDC,
                              &ps.rcPaint);

                if (wParam == 0)
                {
                    EndPaint(hwnd,
                             &ps);
                }
            }
            break;
        }

        case WM_LBUTTONDBLCLK:
        case WM_LBUTTONDOWN:
        {
            WORD SelDay;

            SelDay = MonthCalPtToDay(infoPtr,
                                     GET_X_LPARAM(lParam),
                                     GET_Y_LPARAM(lParam));
            if (SelDay != 0 && SelDay != infoPtr->Day)
            {
                MonthCalSetDate(infoPtr,
                                SelDay,
                                infoPtr->Month,
                                infoPtr->Year);
            }

            /* Fall through */
        }

        case WM_MBUTTONDOWN:
        case WM_RBUTTONDOWN:
        {
            if (!infoPtr->HasFocus)
            {
                SetFocus(hwnd);
            }
            break;
        }

        case WM_KEYDOWN:
        {
            WORD NewDay = 0;

            switch (wParam)
            {
                case VK_UP:
                {
                    if (infoPtr->Day > 7)
                    {
                        NewDay = infoPtr->Day - 7;
                    }
                    break;
                }

                case VK_DOWN:
                {
                    if (infoPtr->Day + 7 <= MonthCalMonthLength(infoPtr->Month,
                                                                infoPtr->Year))
                    {
                        NewDay = infoPtr->Day + 7;
                    }
                    break;
                }

                case VK_LEFT:
                {
                    if (infoPtr->Day > 1)
                    {
                        NewDay = infoPtr->Day - 1;
                    }
                    break;
                }

                case VK_RIGHT:
                {
                    if (infoPtr->Day < MonthCalMonthLength(infoPtr->Month,
                                                           infoPtr->Year))
                    {
                        NewDay = infoPtr->Day + 1;
                    }
                    break;
                }
            }

            /* Update the selection */
            if (NewDay != 0)
            {
                MonthCalSetDate(infoPtr,
                                NewDay,
                                infoPtr->Month,
                                infoPtr->Year);
            }

            goto HandleDefaultMessage;
        }

        case WM_GETDLGCODE:
        {
            INT virtKey;

            virtKey = (lParam != 0 ? (INT)((LPMSG)lParam)->wParam : 0);
            switch (virtKey)
            {
                case VK_TAB:
                {
                    /* Change the UI status */
                    SendMessageW(GetAncestor(hwnd,
                                             GA_PARENT),
                                 WM_CHANGEUISTATE,
                                 MAKEWPARAM(UIS_INITIALIZE,
                                            0),
                                 0);
                    break;
                }
            }

            Ret |= DLGC_WANTARROWS;
            break;
        }

        case WM_SETFOCUS:
        {
            infoPtr->HasFocus = TRUE;
            MonthCalRepaintDay(infoPtr,
                               infoPtr->Day);
            break;
        }

        case WM_KILLFOCUS:
        {
            infoPtr->HasFocus = FALSE;
            MonthCalRepaintDay(infoPtr,
                               infoPtr->Day);
            break;
        }

        case WM_UPDATEUISTATE:
        {
            DWORD OldUIState;

            Ret = DefWindowProcW(hwnd,
                                 uMsg,
                                 wParam,
                                 lParam);

            OldUIState = infoPtr->UIState;
            switch (LOWORD(wParam))
            {
                case UIS_SET:
                    infoPtr->UIState |= HIWORD(wParam);
                    break;

                case UIS_CLEAR:
                    infoPtr->UIState &= ~HIWORD(wParam);
                    break;
            }

            if (infoPtr->UIState != OldUIState)
            {
                MonthCalRepaintDay(infoPtr,
                                   infoPtr->Day);
            }
            break;
        }

        case MCCM_SETDATE:
        {
            WORD Day, Month, Year, DaysCount;

            Day = LOWORD(wParam);
            Month = HIWORD(wParam);
            Year = LOWORD(lParam);

            if (Day == (WORD)-1)
                Day = infoPtr->Day;
            if (Month == (WORD)-1)
                Month = infoPtr->Month;
            if (Year == (WORD)-1)
                Year = infoPtr->Year;

            DaysCount = MonthCalMonthLength(Month,
                                            Year);
            if (Day > DaysCount)
                Day = DaysCount;

            if (MonthCalValidDate(Day,
                                  Month,
                                  Year))
            {
                if (Day != infoPtr->Day ||
                    Month != infoPtr->Month ||
                    Year != infoPtr->Year)
                {
                    Ret = MonthCalSetDate(infoPtr,
                                          Day,
                                          Month,
                                          Year);
                }
            }
            break;
        }

        case MCCM_GETDATE:
        {
            LPSYSTEMTIME lpSystemTime = (LPSYSTEMTIME)wParam;

            lpSystemTime->wYear = infoPtr->Year;
            lpSystemTime->wMonth = infoPtr->Month;
            lpSystemTime->wDay = infoPtr->Day;

            Ret = TRUE;
            break;
        }

        case MCCM_RESET:
        {
            MonthCalSetLocalTime(infoPtr,
                                 NULL);
            Ret = TRUE;
            break;
        }

        case MCCM_CHANGED:
        {
            Ret = infoPtr->Changed;
            break;
        }

        case WM_TIMER:
        {
            switch (wParam)
            {
                case ID_DAYTIMER:
                {
                    /* Kill the timer */
                    KillTimer(hwnd,
                              ID_DAYTIMER);
                    infoPtr->DayTimerSet = FALSE;

                    if (!infoPtr->Changed)
                    {
                        /* Update the system time and setup the new day timer */
                        MonthCalSetLocalTime(infoPtr,
                                             NULL);

                        /* Update the control */
                        MonthCalUpdate(infoPtr);
                    }
                    break;
                }
            }
            break;
        }

        case WM_SETFONT:
        {
            Ret = (LRESULT)MonthCalChangeFont(infoPtr,
                                              (HFONT)wParam,
                                              (BOOL)LOWORD(lParam));
            break;
        }

        case WM_SIZE:
        {
            infoPtr->ClientSize.cx = LOWORD(lParam);
            infoPtr->ClientSize.cy = HIWORD(lParam);
            infoPtr->CellSize.cx = infoPtr->ClientSize.cx / 7;
            infoPtr->CellSize.cy = infoPtr->ClientSize.cy / 7;

            /* Repaint the control */
            InvalidateRect(hwnd,
                           NULL,
                           TRUE);
            break;
        }

        case WM_GETFONT:
        {
            Ret = (LRESULT)infoPtr->hFont;
            break;
        }

        case WM_ENABLE:
        {
            infoPtr->Enabled = ((BOOL)wParam != FALSE);
            MonthCalReload(infoPtr);
            break;
        }

        case WM_STYLECHANGED:
        {
            if (wParam == GWL_STYLE)
            {
                unsigned int OldEnabled = infoPtr->Enabled;
                infoPtr->Enabled = !(((LPSTYLESTRUCT)lParam)->styleNew & WS_DISABLED);

                if (OldEnabled != infoPtr->Enabled)
                {
                    MonthCalReload(infoPtr);
                }
            }
            break;
        }

        case WM_CREATE:
        {
            infoPtr = (MONTHCALWND*) HeapAlloc(GetProcessHeap(),
                                0,
                                sizeof(MONTHCALWND));
            if (infoPtr == NULL)
            {
                Ret = (LRESULT)-1;
                break;
            }

            SetWindowLongPtrW(hwnd,
                              0,
                              (LONG_PTR)infoPtr);

            ZeroMemory(infoPtr,
                       sizeof(MONTHCALWND));

            infoPtr->hSelf = hwnd;
            infoPtr->hNotify = ((LPCREATESTRUCTW)lParam)->hwndParent;
            infoPtr->Enabled = !(((LPCREATESTRUCTW)lParam)->style & WS_DISABLED);

            MonthCalSetLocalTime(infoPtr,
                                 NULL);

            MonthCalReload(infoPtr);
            break;
        }

        case WM_DESTROY:
        {
            HeapFree(GetProcessHeap(),
                     0,
                     infoPtr);
            SetWindowLongPtrW(hwnd,
                              0,
                              (DWORD_PTR)NULL);
            break;
        }

        default:
        {
HandleDefaultMessage:
            Ret = DefWindowProcW(hwnd,
                                 uMsg,
                                 wParam,
                                 lParam);
            break;
        }
    }

    return Ret;
}
/*
 * Check if the given COM port name belongs to a multi port serial adaptor device. If yes, get its driver name
 * and return to caller.
 *
 * Return 1 if found, 0 if not found, -1 if an error occurs (also throws exception in this case).
 */
int get_driver_com_port_multiportadaptor(JNIEnv *env, const jchar *port_name, TCHAR *driver_name) {

	int x = 0;
	BOOL ret = FALSE;
	LONG status = 0;
	DWORD error_code = 0;
	DWORD size = 0;
	DWORD regproptype;
	DWORD charbuffer_size = 0;
	DWORD driver_name_size = 0;
	ULONG buffer_size = 0;
	DWORD multiport_member_index = 0;
	HDEVINFO multiport_dev_info_set;
	SP_DEVINFO_DATA multiport_dev_instance;
	ULONG devprop_buffer_size = 0;
	DEVPROPTYPE proptype;
	CONFIGRET cmret = 0;
	DEVINST firstchild = 0;
	DEVINST next_sibling = 0;
	DEVINST current_sibling = 0;

	/* size of these buffers is hardcoded in functions using them */
	TCHAR buffer[1024];
	TCHAR devprop_buffer[1024];
	TCHAR keybuf[1024];
	TCHAR charbuffer[128];
	char cmerror[256];

	/* get information set for all multi port serial adaptor devices matching the GUID */
	multiport_dev_info_set = SetupDiGetClassDevs(&GUID_MULTIPORT_SERIAL_ADAPTOR_DEVICE, NULL, NULL, DIGCF_DEVICEINTERFACE);
	if (multiport_dev_info_set == INVALID_HANDLE_VALUE) {
		SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
		throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
		return -1;
	}

	/* enumerate all devices in this information set */
	multiport_member_index = 0;
	while (1) {
		ZeroMemory(&multiport_dev_instance, sizeof(multiport_dev_instance));
		multiport_dev_instance.cbSize = sizeof(multiport_dev_instance);

		/* from information set, get device by index */
		ret = SetupDiEnumDeviceInfo(multiport_dev_info_set, multiport_member_index, &multiport_dev_instance);
		if (ret == FALSE) {
			error_code = GetLastError();
			if (error_code == ERROR_NO_MORE_ITEMS) {
				break;
			}else {
				SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
				throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(error_code), NULL);
				return -1;
			}
		}

		/* for this device find its instance ID (USB\VID_04D8&PID_00DF\000098037)
		 * this is variable 'Device Instance Path' in device manager. */
		cmret = CM_Get_Device_ID(multiport_dev_instance.DevInst, buffer, 1024, 0);
		if (cmret != CR_SUCCESS) {
			SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
			_snprintf_s(cmerror, 256, 256, "CM_Get_Device_ID CR_xxxx error code : 0x%X\0", cmret);
			throw_serialcom_exception(env, 3, 0, cmerror);
			return -1;
		}

		/* get its COM port name/number for this device */
		memset(keybuf, '\0', 1024);
		_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer);

		charbuffer_size = sizeof(charbuffer);
		memset(charbuffer, '\0', 128);
		/* ignore error as some devices might not have portname registry key */
		status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
		if (status == ERROR_SUCCESS) {
			/* match port name */
			ret = _tcsicmp(charbuffer, port_name);
			if (ret == 0) {
				/* get driver name */
				memset(keybuf, '\0', 1024);
				_stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s"), buffer);

				/* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\XXXX\XXX\XXX\Service */
				charbuffer_size = sizeof(charbuffer);
				memset(charbuffer, '\0', 128);
				status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("Service"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size);
				if (status != ERROR_SUCCESS) {
					SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
					throw_serialcom_exception(env, 4, GetLastError(), NULL);
					return -1;
				}

				/* populate array to be returned to caller */
				memset(driver_name, '\0', 128);
				for (x = 0; x < _tcslen(charbuffer); x++) {
					driver_name[x] = charbuffer[x];
				}

				/* clean up and return 1 to indicate driver found */
				SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
				return 1;
			}
		}

		/* increment to get and examine the next multiport device for COM ports class */
		multiport_member_index++;
	}

	/* reaching here means given COM port does not belong to multi-port serial adaptor device */
	SetupDiDestroyDeviceInfoList(multiport_dev_info_set);
	return 0;
}
Ejemplo n.º 28
-1
bool CWin32DirectSound::Initialize(IAudioCallback* pCallback, const CStdString& device, int iChannels, enum PCMChannels* channelMap, unsigned int uiSamplesPerSec, unsigned int uiBitsPerSample, bool bResample, bool bIsMusic, bool bAudioPassthrough)
{
  m_uiDataChannels = iChannels;

  if(!bAudioPassthrough)
  {
    //If no channel map is specified, use the default.
    if(!channelMap)
      channelMap = (PCMChannels *)dsound_default_channel_layout[iChannels - 1];

    PCMChannels *outLayout = m_remap.SetInputFormat(iChannels, channelMap, uiBitsPerSample / 8);

    for(iChannels = 0; outLayout[iChannels] != PCM_INVALID;) ++iChannels;

    BuildChannelMapping(iChannels, outLayout);
    m_remap.SetOutputFormat(iChannels, m_SpeakerOrder, false);
  }

  bool bAudioOnAllSpeakers(false);
  g_audioContext.SetupSpeakerConfig(iChannels, bAudioOnAllSpeakers, bIsMusic);
  if(bAudioPassthrough)
    g_audioContext.SetActiveDevice(CAudioContext::DIRECTSOUND_DEVICE_DIGITAL);
  else
    g_audioContext.SetActiveDevice(CAudioContext::DIRECTSOUND_DEVICE);
  m_pDSound=g_audioContext.GetDirectSoundDevice();

  m_bPause = false;
  m_bIsAllocated = false;
  m_pBuffer = NULL;
  m_uiChannels = iChannels;
  m_uiSamplesPerSec = uiSamplesPerSec;
  m_uiBitsPerSample = uiBitsPerSample;
  m_Passthrough = bAudioPassthrough;

  m_nCurrentVolume = g_settings.m_nVolumeLevel;

  WAVEFORMATEXTENSIBLE wfxex = {0};

  //fill waveformatex
  ZeroMemory(&wfxex, sizeof(WAVEFORMATEXTENSIBLE));
  wfxex.Format.cbSize          =  sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
  wfxex.Format.nChannels       = iChannels;
  wfxex.Format.nSamplesPerSec  = uiSamplesPerSec;
  if (bAudioPassthrough == true)
  {
    wfxex.dwChannelMask          = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
    wfxex.Format.wFormatTag      = WAVE_FORMAT_DOLBY_AC3_SPDIF;
    wfxex.SubFormat              = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF;
    wfxex.Format.wBitsPerSample  = 16;
    wfxex.Format.nChannels       = 2;
  }
  else
  {
    wfxex.dwChannelMask          = m_uiSpeakerMask;

    if (iChannels > 2)
      wfxex.Format.wFormatTag    = WAVE_FORMAT_EXTENSIBLE;
    else
      wfxex.Format.wFormatTag    = WAVE_FORMAT_PCM;

    wfxex.SubFormat              = _KSDATAFORMAT_SUBTYPE_PCM;
    wfxex.Format.wBitsPerSample  = uiBitsPerSample;
  }

  wfxex.Samples.wValidBitsPerSample = wfxex.Format.wBitsPerSample;
  wfxex.Format.nBlockAlign       = wfxex.Format.nChannels * (wfxex.Format.wBitsPerSample >> 3);
  wfxex.Format.nAvgBytesPerSec   = wfxex.Format.nSamplesPerSec * wfxex.Format.nBlockAlign;

  m_AvgBytesPerSec = wfxex.Format.nAvgBytesPerSec;

  m_uiBytesPerFrame     = wfxex.Format.nBlockAlign;
  m_uiDataBytesPerFrame = (wfxex.Format.nBlockAlign / iChannels) * m_uiDataChannels;

  // unsure if these are the right values
  m_dwChunkSize = wfxex.Format.nBlockAlign * 3096;
  m_dwDataChunkSize = (m_dwChunkSize / iChannels) * m_uiDataChannels;
  m_dwBufferLen = m_dwChunkSize * 16;
  m_PreCacheSize = m_dwBufferLen - 2*m_dwChunkSize;

  CLog::Log(LOGDEBUG, __FUNCTION__": Packet Size = %d. Avg Bytes Per Second = %d.", m_dwChunkSize, m_AvgBytesPerSec);

  // fill in the secondary sound buffer descriptor
  DSBUFFERDESC dsbdesc;
  memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 /** Better position accuracy */
                  | DSBCAPS_GLOBALFOCUS         /** Allows background playing */
                  | DSBCAPS_CTRLVOLUME;         /** volume control enabled */

  if (!g_sysinfo.IsVistaOrHigher())
    dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;     /** Needed for 5.1 on emu101k, always fails on Vista, by design  */

  dsbdesc.dwBufferBytes = m_dwBufferLen;
  dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&wfxex;

  // now create the stream buffer
  HRESULT res = IDirectSound_CreateSoundBuffer(m_pDSound, &dsbdesc, &m_pBuffer, NULL);
  if (res != DS_OK)
  {
    if (dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE)
    {
      SAFE_RELEASE(m_pBuffer);
      CLog::Log(LOGDEBUG, __FUNCTION__": Couldn't create secondary buffer (%s). Trying without LOCHARDWARE.", dserr2str(res));
      // Try without DSBCAPS_LOCHARDWARE
      dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
      res = IDirectSound_CreateSoundBuffer(m_pDSound, &dsbdesc, &m_pBuffer, NULL);
    }
    if (res != DS_OK && dsbdesc.dwFlags & DSBCAPS_CTRLVOLUME)
    {
      SAFE_RELEASE(m_pBuffer);
      CLog::Log(LOGDEBUG, __FUNCTION__": Couldn't create secondary buffer (%s). Trying without CTRLVOLUME.", dserr2str(res));
      // Try without DSBCAPS_CTRLVOLUME
      dsbdesc.dwFlags &= ~DSBCAPS_CTRLVOLUME;
      res = IDirectSound_CreateSoundBuffer(m_pDSound, &dsbdesc, &m_pBuffer, NULL);
    }
    if (res != DS_OK)
    {
      SAFE_RELEASE(m_pBuffer);
      CLog::Log(LOGERROR, __FUNCTION__": cannot create secondary buffer (%s)", dserr2str(res));
      return false;
    }
  }
  CLog::Log(LOGDEBUG, __FUNCTION__": secondary buffer created");

  m_pBuffer->Stop();

  if (DSERR_CONTROLUNAVAIL == m_pBuffer->SetVolume(g_settings.m_nVolumeLevel))
    CLog::Log(LOGINFO, __FUNCTION__": Volume control is unavailable in the current configuration");

  m_bIsAllocated = true;
  m_BufferOffset = 0;
  m_CacheLen = 0;
  m_LastCacheCheck = XbmcThreads::SystemClockMillis();

  return m_bIsAllocated;
}
Ejemplo n.º 29
-1
void CSnoopyProApp::ScanForNewSnoopedDevices(void)
{
    TRACE("Accessing usbsnoopies to find new devices...\n");
    HANDLE hSniffer = CreateFile(USBSNPYS_W32NAME_2K, 
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, // no SECURITY_ATTRIBUTES structure
        OPEN_EXISTING, // No special create flags
        0, // No special attributes
        NULL);
    
    if(INVALID_HANDLE_VALUE == hSniffer)
    {
        hSniffer = CreateFile(USBSNPYS_W32NAME_9X,
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            NULL, // no SECURITY_ATTRIBUTES structure
            OPEN_EXISTING,
            FILE_FLAG_DELETE_ON_CLOSE,
            NULL);
    }

    m_bIsSnpysPresent = (INVALID_HANDLE_VALUE != hSniffer);

    if(INVALID_HANDLE_VALUE != hSniffer)
    {
        DWORD dwBytesReturned = 0;
        SNOOPED_DEVICES SnoopedDevices;
        ZeroMemory(&SnoopedDevices, sizeof(SnoopedDevices));

        BOOL bResult = DeviceIoControl(hSniffer, USBSNOOP_GET_SNOOPED_DEVS, 
                &SnoopedDevices, sizeof(SnoopedDevices),
                &SnoopedDevices, sizeof(SnoopedDevices),
                &dwBytesReturned, NULL);
        CloseHandle(hSniffer);
        hSniffer = INVALID_HANDLE_VALUE;

        TRACE("DeviceIoControl(): got %d snooped devices\n", SnoopedDevices.uCount);
        m_nSnpysUsage = SnoopedDevices.uCount;
        if(bResult)
        {
            TRACE("Devices:\n");
            for(ULONG nSnooped = 0; nSnooped < SnoopedDevices.uCount; ++nSnooped)
            {
                PSNOOPED_DEVICE pSnooped = &SnoopedDevices.Entry[nSnooped];
                TRACE(" Dev[%d] = 0x%08x\n", nSnooped, pSnooped->uDeviceID);
                if(INVALID_DEVICE_ID == pSnooped->uDeviceID)
                {
                    TRACE("  .. skipping\n");
                }
                else
                {
                    BOOL bAlreadySnooped = FALSE;
                    if(!m_DocsNeedingUpdate.IsEmpty())
                    {
                        POSITION pos = m_DocsNeedingUpdate.GetHeadPosition();
                        while(NULL != pos)
                        {
                            CUSBLogDoc *pDoc = m_DocsNeedingUpdate.GetNext(pos);
                            ASSERT(NULL != pDoc);
                            if(NULL != pDoc)
                            {
                                if(pSnooped->uDeviceID == pDoc->GetSnifferDevice())
                                {
                                    bAlreadySnooped = TRUE;
                                    break;
                                }
                            }
                        }
                    }
                    if(!bAlreadySnooped)
                    {
                        CUSBLogDoc *pDoc = CreateNewDocument();
                        pDoc->AccessSniffer(pSnooped->uDeviceID, pSnooped->sHardwareIDs);
                        pDoc->SetTimeStampZero(SnoopedDevices.Entry[nSnooped].uTimeStampZero);
                    }
                }
            }
        }
    }
}
Ejemplo n.º 30
-1
static NTSTATUS DOKAN_CALLBACK
FuseGetFileSecurity(LPCWSTR FileName, PSECURITY_INFORMATION SecurityInformation,
                    PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG BufferLength,
                    PULONG LengthNeeded, PDOKAN_FILE_INFO DokanFileInfo) {
    impl_fuse_context *impl = the_impl;
    if (impl->debug())
        FPRINTF(stderr, "GetFileSecurity: " PRIxDWORD "\n", *SecurityInformation);

    BY_HANDLE_FILE_INFORMATION byHandleFileInfo;
    ZeroMemory(&byHandleFileInfo, sizeof(BY_HANDLE_FILE_INFORMATION));

    int ret;
    {
        impl_chain_guard guard(impl, DokanFileInfo->ProcessId);
        ret =
            impl->get_file_information(FileName, &byHandleFileInfo, DokanFileInfo);
    }

    if (0 != ret) {
        return errno_to_ntstatus_error(ret);
    }

    if (byHandleFileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        // We handle directories for the Explorer's
        // context menu. (New Folder, ...)

        // Authenticated users rights
        PSECURITY_DESCRIPTOR SecurityDescriptorTmp = nullptr;
        ULONG Size = 0;
        if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
                    "D:PAI(A;OICI;FA;;;AU)", SDDL_REVISION_1, &SecurityDescriptorTmp,
                    &Size)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        LPTSTR pStringBuffer = nullptr;
        if (!ConvertSecurityDescriptorToStringSecurityDescriptor(
                    SecurityDescriptorTmp, SDDL_REVISION_1, *SecurityInformation,
                    &pStringBuffer, nullptr)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        LocalFree(SecurityDescriptorTmp);
        SecurityDescriptorTmp = nullptr;
        Size = 0;
        if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
                    pStringBuffer, SDDL_REVISION_1, &SecurityDescriptorTmp, &Size)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        if (Size > BufferLength) {
            *LengthNeeded = Size;
            return STATUS_BUFFER_OVERFLOW;
        }

        memcpy(SecurityDescriptor, SecurityDescriptorTmp, Size);
        *LengthNeeded = Size;

        if (pStringBuffer != nullptr)
            LocalFree(pStringBuffer);
        if (SecurityDescriptorTmp != nullptr)
            LocalFree(SecurityDescriptorTmp);

        return STATUS_SUCCESS;
    }
    return STATUS_NOT_IMPLEMENTED;
}