FlatCAMApp.py 482 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. fcTranslate.apply_language('strings')
  80. if '_' not in builtins.__dict__:
  81. _ = gettext.gettext
  82. class App(QtCore.QObject):
  83. """
  84. The main application class. The constructor starts the GUI.
  85. """
  86. # ###############################################################################################################
  87. # ########################################## App ################################################################
  88. # ###############################################################################################################
  89. # ###############################################################################################################
  90. # ######################################### LOGGING #############################################################
  91. # ###############################################################################################################
  92. log = logging.getLogger('base')
  93. log.setLevel(logging.DEBUG)
  94. # log.setLevel(logging.WARNING)
  95. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  96. handler = logging.StreamHandler()
  97. handler.setFormatter(formatter)
  98. log.addHandler(handler)
  99. # ###############################################################################################################
  100. # #################################### Get Cmd Line Options #####################################################
  101. # ###############################################################################################################
  102. cmd_line_shellfile = ''
  103. cmd_line_shellvar = ''
  104. cmd_line_headless = None
  105. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  106. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  107. "FlatCam.py --headless=1"
  108. try:
  109. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  110. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  111. "shellvar=",
  112. "headless=",
  113. "multiprocessing-fork="])
  114. except getopt.GetoptError:
  115. print(cmd_line_help)
  116. sys.exit(2)
  117. for opt, arg in cmd_line_options:
  118. if opt == '-h':
  119. print(cmd_line_help)
  120. sys.exit()
  121. elif opt == '--shellfile':
  122. cmd_line_shellfile = arg
  123. elif opt == '--shellvar':
  124. cmd_line_shellvar = arg
  125. elif opt == '--headless':
  126. try:
  127. cmd_line_headless = eval(arg)
  128. except NameError:
  129. pass
  130. # ###############################################################################################################
  131. # ################################### Version and VERSION DATE ##################################################
  132. # ###############################################################################################################
  133. version = 8.992
  134. version_date = "2020/05/01"
  135. beta = True
  136. engine = '3D'
  137. # current date now
  138. date = str(datetime.today()).rpartition('.')[0]
  139. date = ''.join(c for c in date if c not in ':-')
  140. date = date.replace(' ', '_')
  141. # ###############################################################################################################
  142. # ############################################ URLS's ###########################################################
  143. # ###############################################################################################################
  144. # URL for update checks and statistics
  145. version_url = "http://flatcam.org/version"
  146. # App URL
  147. app_url = "http://flatcam.org"
  148. # Manual URL
  149. manual_url = "http://flatcam.org/manual/index.html"
  150. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  151. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  152. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  153. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  154. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  155. # this variable will hold the project status
  156. # if True it will mean that the project was modified and not saved
  157. should_we_save = False
  158. # flag is True if saving action has been triggered
  159. save_in_progress = False
  160. # ###############################################################################################################
  161. # ####################################### APP Signals ######################################################
  162. # ###############################################################################################################
  163. # Inform the user
  164. # Handled by:
  165. # * App.info() --> Print on the status bar
  166. inform = QtCore.pyqtSignal(str)
  167. app_quit = QtCore.pyqtSignal()
  168. # General purpose background task
  169. worker_task = QtCore.pyqtSignal(dict)
  170. # File opened
  171. # Handled by:
  172. # * register_folder()
  173. # * register_recent()
  174. # Note: Setting the parameters to unicode does not seem
  175. # to have an effect. Then are received as Qstring
  176. # anyway.
  177. # File type and filename
  178. file_opened = QtCore.pyqtSignal(str, str)
  179. # File type and filename
  180. file_saved = QtCore.pyqtSignal(str, str)
  181. # Percentage of progress
  182. progress = QtCore.pyqtSignal(int)
  183. plots_updated = QtCore.pyqtSignal()
  184. # Emitted by new_object() and passes the new object as argument, plot flag.
  185. # on_object_created() adds the object to the collection, plots on appropriate flag
  186. # and emits new_object_available.
  187. object_created = QtCore.pyqtSignal(object, bool, bool)
  188. # Emitted when a object has been changed (like scaled, mirrored)
  189. object_changed = QtCore.pyqtSignal(object)
  190. # Emitted after object has been plotted.
  191. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  192. object_plotted = QtCore.pyqtSignal(object)
  193. # Emitted when a new object has been added or deleted from/to the collection
  194. object_status_changed = QtCore.pyqtSignal(object, str, str)
  195. message = QtCore.pyqtSignal(str, str, str)
  196. # Emmited when shell command is finished(one command only)
  197. shell_command_finished = QtCore.pyqtSignal(object)
  198. # Emitted when multiprocess pool has been recreated
  199. pool_recreated = QtCore.pyqtSignal(object)
  200. # Emitted when an unhandled exception happens
  201. # in the worker task.
  202. thread_exception = QtCore.pyqtSignal(object)
  203. # used to signal that there are arguments for the app
  204. args_at_startup = QtCore.pyqtSignal(list)
  205. # a reusable signal to replot a list of objects
  206. # should be disconnected after use so it can be reused
  207. replot_signal = pyqtSignal(list)
  208. # signal emitted when jumping
  209. jump_signal = pyqtSignal(tuple)
  210. # signal emitted when jumping
  211. locate_signal = pyqtSignal(tuple, str)
  212. # close app signal
  213. close_app_signal = pyqtSignal()
  214. # will perform the cleanup operation after a Graceful Exit
  215. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  216. # graphic residues behind
  217. cleanup = pyqtSignal()
  218. def __init__(self, user_defaults=True):
  219. """
  220. Starts the application.
  221. :return: app
  222. :rtype: App
  223. """
  224. App.log.info("FlatCAM Starting...")
  225. self.main_thread = QtWidgets.QApplication.instance().thread()
  226. # ############################################################################################################
  227. # ################# Setup the listening thread for another instance launching with args ######################
  228. # ############################################################################################################
  229. if sys.platform == 'win32' or sys.platform == 'linux':
  230. # make sure the thread is stored by using a self. otherwise it's garbage collected
  231. self.th = QtCore.QThread()
  232. self.th.start(priority=QtCore.QThread.LowestPriority)
  233. self.new_launch = ArgsThread()
  234. self.new_launch.open_signal[list].connect(self.on_startup_args)
  235. self.new_launch.moveToThread(self.th)
  236. self.new_launch.start.emit()
  237. # ############################################################################################################
  238. # # ######################################## OS-specific #####################################################
  239. # ############################################################################################################
  240. portable = False
  241. # Folder for user settings.
  242. if sys.platform == 'win32':
  243. from win32comext.shell import shell, shellcon
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults["global_gray_icons"] is False:
  354. self.resource_location = 'share'
  355. else:
  356. self.resource_location = 'share/dark_resources'
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize GUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. QtCore.QObject.__init__(self)
  409. self.ui = FlatCAMGUI(self)
  410. self.on_grid_snap_triggered(state=True)
  411. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  412. if theme_settings.contains("theme"):
  413. theme = theme_settings.value('theme', type=str)
  414. else:
  415. theme = 'white'
  416. if self.defaults["global_cursor_color_enabled"]:
  417. self.cursor_color_3D = self.defaults["global_cursor_color"]
  418. else:
  419. if theme == 'white':
  420. self.cursor_color_3D = 'black'
  421. else:
  422. self.cursor_color_3D = 'gray'
  423. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  424. self.ui.final_save.connect(self.final_save)
  425. # restore the toolbar view
  426. self.restore_toolbar_view()
  427. # restore the GUI geometry
  428. self.restore_main_win_geom()
  429. # set FlatCAM units in the Status bar
  430. self.set_screen_units(self.defaults['units'])
  431. # ###########################################################################################################
  432. # ########################################### AUTOSAVE SETUP ################################################
  433. # ###########################################################################################################
  434. self.block_autosave = False
  435. self.autosave_timer = QtCore.QTimer(self)
  436. self.save_project_auto_update()
  437. self.autosave_timer.timeout.connect(self.save_project_auto)
  438. # ###########################################################################################################
  439. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  440. # ###########################################################################################################
  441. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  442. inform=self.inform, app=self)
  443. self.preferencesUiManager.defaults_write_form()
  444. # When the self.defaults dictionary changes will update the Preferences GUI forms
  445. self.defaults.set_change_callback(self.on_defaults_dict_change)
  446. # ###########################################################################################################
  447. # ##################################### FIRST RUN SECTION ###################################################
  448. # ################################ It's done only once after install #####################################
  449. # ###########################################################################################################
  450. if self.defaults["first_run"] is True:
  451. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  452. initial_lay = 'compact'
  453. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  454. # Set the combobox in Preferences to the current layout
  455. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  456. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  457. # after the first run, this object should be False
  458. self.defaults["first_run"] = False
  459. self.preferencesUiManager.save_defaults(silent=True)
  460. # ###########################################################################################################
  461. # ############################################ Data #########################################################
  462. # ###########################################################################################################
  463. self.recent = []
  464. self.recent_projects = []
  465. self.clipboard = QtWidgets.QApplication.clipboard()
  466. self.project_filename = None
  467. self.toggle_units_ignore = False
  468. # ###########################################################################################################
  469. # #################################### LOAD PREPROCESSORS ###################################################
  470. # ###########################################################################################################
  471. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  472. # the preprocessor file
  473. self.preprocessors = load_preprocessors(self)
  474. # make sure that always the 'default' preprocessor is the first item in the dictionary
  475. if 'default' in self.preprocessors.keys():
  476. new_ppp_dict = {}
  477. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  478. default_pp = self.preprocessors.pop('default')
  479. new_ppp_dict['default'] = default_pp
  480. # then add the rest of the keys
  481. for name, val_class in self.preprocessors.items():
  482. new_ppp_dict[name] = val_class
  483. # and now put back the ordered dict with 'default' key first
  484. self.preprocessors = new_ppp_dict
  485. for name in list(self.preprocessors.keys()):
  486. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  487. if name.partition('_')[0] == 'Paste':
  488. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  489. continue
  490. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  491. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  492. if name == 'hpgl':
  493. continue
  494. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  495. # ###########################################################################################################
  496. # ########################################## LOAD LANGUAGES ################################################
  497. # ###########################################################################################################
  498. self.languages = fcTranslate.load_languages()
  499. for name in sorted(self.languages.values()):
  500. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  501. # ###########################################################################################################
  502. # ####################################### APPLY APP LANGUAGE ################################################
  503. # ###########################################################################################################
  504. ret_val = fcTranslate.apply_language('strings')
  505. if ret_val == "no language":
  506. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  507. log.debug("Could not find the Language files. The App strings are missing.")
  508. else:
  509. # make the current language the current selection on the language combobox
  510. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  511. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  512. # ###########################################################################################################
  513. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  514. # ###########################################################################################################
  515. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  516. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  517. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  518. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  519. self.defaults.propagate_defaults()
  520. # ###########################################################################################################
  521. # ######################################## UPDATE THE OPTIONS ###############################################
  522. # ###########################################################################################################
  523. self.options = LoudDict()
  524. # -----------------------------------------------------------------------------------------------------------
  525. # Update the self.options from the self.defaults
  526. # The self.defaults holds the application defaults while the self.options holds the object defaults
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Copy app defaults to project options
  529. for def_key, def_val in self.defaults.items():
  530. self.options[def_key] = deepcopy(def_val)
  531. self.preferencesUiManager.show_preferences_gui()
  532. # ### End of Data ####
  533. # ###########################################################################################################
  534. # #################################### SETUP OBJECT COLLECTION ##############################################
  535. # ###########################################################################################################
  536. self.collection = ObjectCollection(self)
  537. self.ui.project_tab_layout.addWidget(self.collection.view)
  538. # ### Adjust tabs width ## ##
  539. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  540. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  541. self.collection.view.setMinimumWidth(290)
  542. self.log.debug("Finished creating Object Collection.")
  543. # ###########################################################################################################
  544. # ######################################## SETUP Plot Area ##################################################
  545. # ###########################################################################################################
  546. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  547. if self.defaults["global_graphic_engine"] == '3D':
  548. self.is_legacy = False
  549. else:
  550. self.is_legacy = True
  551. # Event signals disconnect id holders
  552. self.mp = None
  553. self.mm = None
  554. self.mr = None
  555. self.mdc = None
  556. self.mp_zc = None
  557. self.kp = None
  558. # Matplotlib axis
  559. self.axes = None
  560. if show_splash:
  561. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  562. "Canvas initialization started."),
  563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  564. color=QtGui.QColor("gray"))
  565. start_plot_time = time.time() # debug
  566. self.plotcanvas = None
  567. self.app_cursor = None
  568. self.hover_shapes = None
  569. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  570. # setup the PlotCanvas
  571. self.on_plotcanvas_setup()
  572. end_plot_time = time.time()
  573. self.used_time = end_plot_time - start_plot_time
  574. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  575. if show_splash:
  576. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started.\n"
  578. "Canvas initialization finished in"), '%.2f' % self.used_time),
  579. alignment=Qt.AlignBottom | Qt.AlignLeft,
  580. color=QtGui.QColor("gray"))
  581. self.ui.splitter.setStretchFactor(1, 2)
  582. # ###########################################################################################################
  583. # ############################################### SYS TRAY ##################################################
  584. # ###########################################################################################################
  585. if self.defaults["global_systray_icon"]:
  586. self.parent_w = QtWidgets.QWidget()
  587. if self.cmd_line_headless == 1:
  588. self.trayIcon = FlatCAMSystemTray(app=self,
  589. icon=QtGui.QIcon(self.resource_location +
  590. '/flatcam_icon32_green.png'),
  591. headless=True,
  592. parent=self.parent_w)
  593. else:
  594. self.trayIcon = FlatCAMSystemTray(app=self,
  595. icon=QtGui.QIcon(self.resource_location +
  596. '/flatcam_icon32_green.png'),
  597. parent=self.parent_w)
  598. # ###########################################################################################################
  599. # ############################################### Worker SETUP ##############################################
  600. # ###########################################################################################################
  601. if self.defaults["global_worker_number"]:
  602. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  603. else:
  604. self.workers = WorkerStack(workers_number=2)
  605. self.worker_task.connect(self.workers.add_task)
  606. self.log.debug("Finished creating Workers crew.")
  607. # ###########################################################################################################
  608. # ############################################# Activity Monitor ###########################################
  609. # ###########################################################################################################
  610. self.activity_view = FlatCAMActivityView(app=self)
  611. self.ui.infobar.addWidget(self.activity_view)
  612. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  613. # ###########################################################################################################
  614. # ############################################# Signal handling #############################################
  615. # ###########################################################################################################
  616. # ########################################## Custom signals ################################################
  617. # signal for displaying messages in status bar
  618. self.inform.connect(self.info)
  619. # signal to be called when the app is quiting
  620. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  621. self.message.connect(self.message_dialog)
  622. # self.progress.connect(self.set_progress_bar)
  623. # signals that are emitted when object state changes
  624. self.object_created.connect(self.on_object_created)
  625. self.object_changed.connect(self.on_object_changed)
  626. self.object_plotted.connect(self.on_object_plotted)
  627. self.plots_updated.connect(self.on_plots_updated)
  628. # signals emitted when file state change
  629. self.file_opened.connect(self.register_recent)
  630. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  631. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  632. # ########################################## Standard signals ###############################################
  633. # ### Menu
  634. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  635. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  636. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  637. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  638. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  639. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  640. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  641. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  642. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  643. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  644. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  645. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  646. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  647. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  648. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  649. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  650. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  651. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  652. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  653. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  654. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  655. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  656. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  657. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  658. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  659. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  660. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  661. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  662. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  663. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  664. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  665. self.ui.menufile_exit.triggered.connect(self.final_save)
  666. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  667. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  668. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  669. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  670. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  671. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  672. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  673. self.ui.menueditdelete.triggered.connect(self.on_delete)
  674. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  675. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  676. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  677. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  678. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  679. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  680. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  681. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  682. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  683. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  684. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  685. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  686. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  687. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  688. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  689. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  690. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  691. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  692. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  693. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  694. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  695. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  696. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  697. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  698. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  699. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  700. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  701. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  702. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  703. self.ui.menuview_replot.triggered.connect(self.plot_all)
  704. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  705. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  706. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  707. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  708. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  709. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  710. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  711. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  712. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  713. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  714. self.ui.menuhelp_about.triggered.connect(self.on_about)
  715. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  716. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  717. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  718. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  719. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  720. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  721. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  722. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  723. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  724. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  725. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  726. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  727. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  728. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  729. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  730. # ToolBar signals
  731. self.connect_toolbar_signals()
  732. # Notebook and Plot Tab Area signals
  733. # make the right click on the notebook tab and plot tab area tab raise a menu
  734. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  735. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  736. self.on_tab_setup_context_menu()
  737. # activate initial state
  738. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  739. # Context Menu
  740. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  741. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  742. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  743. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  744. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  745. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  746. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  747. self.ui.clearplot.triggered.connect(self.clear_plots)
  748. self.ui.replot.triggered.connect(self.plot_all)
  749. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  750. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  751. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  752. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  753. self.ui.popmenu_move.triggered.connect(self.obj_move)
  754. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  755. # Project Context Menu -> Color Setting
  756. for act in self.ui.menuprojectcolor.actions():
  757. act.triggered.connect(self.on_set_color_action_triggered)
  758. # ###########################################################################################################
  759. # #################################### GUI PREFERENCES SIGNALS ##############################################
  760. # ###########################################################################################################
  761. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  762. lambda: self.on_toggle_units(no_pref=False))
  763. # ##################################### Workspace Setting Signals ###########################################
  764. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  765. self.on_workspace_modified)
  766. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  767. self.on_workspace_modified
  768. )
  769. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  770. # ###########################################################################################################
  771. # ######################################## GUI SETTINGS SIGNALS #############################################
  772. # ###########################################################################################################
  773. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  774. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  775. # ######################################## Tools related signals ############################################
  776. # Film Tool
  777. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  778. self.on_film_color_entry)
  779. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  780. self.on_film_color_button)
  781. # QRCode Tool
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  783. self.on_qrcode_fill_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  785. self.on_qrcode_fill_color_button)
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  787. self.on_qrcode_back_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  789. self.on_qrcode_back_color_button)
  790. # portability changed signal
  791. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  792. # Object list
  793. self.collection.view.activated.connect(self.on_row_activated)
  794. self.collection.item_selected.connect(self.on_row_selected)
  795. self.object_status_changed.connect(self.on_collection_updated)
  796. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  797. # Export Excellon parameters.
  798. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  799. self.on_update_exc_export
  800. )
  801. # call it once to make sure it is updated at startup
  802. self.on_update_exc_export(state=self.defaults["excellon_update"])
  803. # when there are arguments at application startup this get launched
  804. self.args_at_startup[list].connect(self.on_startup_args)
  805. # ###########################################################################################################
  806. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  807. # ###########################################################################################################
  808. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='gerber'))
  814. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='excellon'))
  816. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  817. lambda: self.delete_all_extensions(ext_type='gcode'))
  818. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  819. lambda: self.delete_all_extensions(ext_type='gerber'))
  820. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='excellon'))
  822. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  823. lambda: self.add_extension(ext_type='gcode'))
  824. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  825. lambda: self.add_extension(ext_type='gerber'))
  826. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='excellon'))
  828. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='gcode'))
  830. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='gerber'))
  832. # connect the 'Apply' buttons from the Preferences/File Associations
  833. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='excellon'))
  835. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  836. lambda: self.on_register_files(obj_type='gcode'))
  837. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  838. lambda: self.on_register_files(obj_type='gerber'))
  839. # ###########################################################################################################
  840. # ########################################### KEYWORDS SIGNALS ##############################################
  841. # ###########################################################################################################
  842. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  843. lambda: self.restore_extensions(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  845. lambda: self.delete_all_extensions(ext_type='keyword'))
  846. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  847. lambda: self.add_extension(ext_type='keyword'))
  848. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  849. lambda: self.del_extension(ext_type='keyword'))
  850. # connect the abort_all_tasks related slots to the related signals
  851. self.proc_container.idle_flag.connect(self.app_is_idle)
  852. # signal emitted when a tab is closed in the Plot Area
  853. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  854. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  855. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  856. # signal to close the application
  857. self.close_app_signal.connect(self.kill_app)
  858. # ################################# FINISHED CONNECTING SIGNALS #############################################
  859. # ###########################################################################################################
  860. # ###########################################################################################################
  861. # ###########################################################################################################
  862. self.log.debug("Finished connecting Signals.")
  863. # ###########################################################################################################
  864. # ########################################## Other setups ###################################################
  865. # ###########################################################################################################
  866. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  867. # depending on from where those tools are called different actions can be done
  868. self.call_source = 'app'
  869. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  870. self.tool_tab_locked = False
  871. # decide if to show or hide the Notebook side of the screen at startup
  872. if self.defaults["global_project_at_startup"] is True:
  873. self.ui.splitter.setSizes([1, 1])
  874. else:
  875. self.ui.splitter.setSizes([0, 1])
  876. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  877. self.setup_component_editor()
  878. # ###########################################################################################################
  879. # ####################################### Auto-complete KEYWORDS ############################################
  880. # ###########################################################################################################
  881. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  882. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  883. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  884. 'export_exc',
  885. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  886. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  887. 'interiors', 'isolate', 'join_excellon',
  888. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  889. 'mirror', 'ncc',
  890. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  891. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  892. 'options', 'origin',
  893. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  894. 'save', 'save_project',
  895. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  896. 'skew', 'subtract_poly', 'subtract_rectangle',
  897. 'version', 'write_gcode'
  898. ]
  899. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  900. 'Paste_1',
  901. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  902. 'Toolchange_manual', 'True', 'Users',
  903. 'all', 'auto', 'axis',
  904. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  905. 'contour', 'default',
  906. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  907. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  908. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  909. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  910. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  911. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  912. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  913. 'spacing_columns',
  914. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  915. 'toolchange_xy', 'toolchangez', 'travelz',
  916. 'tooldia', 'use_threads', 'value',
  917. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  918. ]
  919. self.tcl_keywords = [
  920. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  921. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  922. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  923. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  924. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  925. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  926. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  927. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  928. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  929. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  930. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  931. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  932. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  933. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  934. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  935. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  936. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  937. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  938. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  939. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  940. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  941. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  942. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  943. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  944. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  945. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  946. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  947. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  948. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  949. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  950. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  951. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  952. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  953. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  954. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  955. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  956. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  957. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  958. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  959. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  960. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  961. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  962. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  963. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  964. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  965. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  966. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  967. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  968. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  969. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  970. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  971. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  972. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  973. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  974. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  975. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  976. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  977. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  978. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  979. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  980. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  981. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  982. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  983. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  984. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  985. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  986. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  987. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  988. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  989. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  990. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  991. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  992. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  993. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  994. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  995. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  996. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  997. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  998. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  999. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1000. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1001. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1002. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1003. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1004. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1005. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1006. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1007. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1008. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1009. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1010. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1011. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1012. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1013. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1014. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1015. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1016. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1017. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1018. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1019. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1020. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1021. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1022. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1023. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1024. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1025. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1026. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1027. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1028. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1029. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1030. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1031. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1032. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1033. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1034. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1035. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1036. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1037. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1038. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1039. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1040. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1041. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1042. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1043. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1044. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1045. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1046. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1047. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1048. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1049. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1050. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1051. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1052. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1053. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1054. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1055. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1056. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1057. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1058. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1059. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1060. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1061. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1062. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1063. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1064. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1065. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1066. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1067. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1068. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1069. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1070. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1071. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1072. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1073. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1074. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1075. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1076. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1077. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1078. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1079. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1080. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1081. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1082. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1083. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1084. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1085. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1086. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1087. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1088. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1089. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1090. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1091. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1092. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1093. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1094. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1095. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1096. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1097. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1098. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1099. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1100. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1101. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1102. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1103. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1104. ]
  1105. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1106. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1107. # ###########################################################################################################
  1108. # ############################################## Shell SETUP ################################################
  1109. # ###########################################################################################################
  1110. self.shell = FCShell(app=self, version=self.version)
  1111. self.ui.shell_dock.setWidget(self.shell)
  1112. self.log.debug("TCL Shell has been initialized.")
  1113. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1114. if self.defaults["global_shell_at_startup"]:
  1115. self.ui.shell_dock.show()
  1116. else:
  1117. self.ui.shell_dock.hide()
  1118. # ###########################################################################################################
  1119. # ########################################## Tools and Plugins ##############################################
  1120. # ###########################################################################################################
  1121. self.dblsidedtool = None
  1122. self.distance_tool = None
  1123. self.distance_min_tool = None
  1124. self.panelize_tool = None
  1125. self.film_tool = None
  1126. self.paste_tool = None
  1127. self.calculator_tool = None
  1128. self.rules_tool = None
  1129. self.sub_tool = None
  1130. self.move_tool = None
  1131. self.cutout_tool = None
  1132. self.ncclear_tool = None
  1133. self.optimal_tool = None
  1134. self.paint_tool = None
  1135. self.transform_tool = None
  1136. self.properties_tool = None
  1137. self.pdf_tool = None
  1138. self.image_tool = None
  1139. self.pcb_wizard_tool = None
  1140. self.cal_exc_tool = None
  1141. self.qrcode_tool = None
  1142. self.copper_thieving_tool = None
  1143. self.fiducial_tool = None
  1144. self.edrills_tool = None
  1145. self.align_objects_tool = None
  1146. self.punch_tool = None
  1147. self.invert_tool = None
  1148. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1149. try:
  1150. self.install_tools()
  1151. except AttributeError as e:
  1152. log.debug("App.__init__() install tools() --> %s" % str(e))
  1153. # ###########################################################################################################
  1154. # ############################################ SETUP RECENT ITEMS ###########################################
  1155. # ###########################################################################################################
  1156. self.setup_recent_items()
  1157. # ###########################################################################################################
  1158. # ######################################### BookMarks Manager ###############################################
  1159. # ###########################################################################################################
  1160. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1161. self.install_bookmarks()
  1162. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1163. # ###########################################################################################################
  1164. # ########################################### Tools Database ################################################
  1165. # ###########################################################################################################
  1166. self.tools_db_tab = None
  1167. # ### System Font Parsing ###
  1168. # self.f_parse = ParseFont(self)
  1169. # self.parse_system_fonts()
  1170. # ###########################################################################################################
  1171. # ######################################### Check for updates ###############################################
  1172. # ###########################################################################################################
  1173. # Separate thread (Not worker)
  1174. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1175. if (self.beta is False or self.beta is None) and \
  1176. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1177. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1178. self.thr2 = QtCore.QThread()
  1179. self.worker_task.emit({'fcn': self.version_check,
  1180. 'params': []})
  1181. self.thr2.start(QtCore.QThread.LowPriority)
  1182. # ###########################################################################################################
  1183. # ##################################### Register files with FlatCAM; #######################################
  1184. # ################################### It works only for Windows for now ####################################
  1185. # ###########################################################################################################
  1186. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1187. self.on_register_files()
  1188. # ###########################################################################################################
  1189. # ######################################## Variables for global usage #######################################
  1190. # ###########################################################################################################
  1191. # hold the App units
  1192. self.units = 'MM'
  1193. # coordinates for relative position display
  1194. self.rel_point1 = (0, 0)
  1195. self.rel_point2 = (0, 0)
  1196. # variable to store coordinates
  1197. self.pos = (0, 0)
  1198. self.pos_canvas = (0, 0)
  1199. self.pos_jump = (0, 0)
  1200. # variable to store mouse coordinates
  1201. self.mouse = [0, 0]
  1202. # variable to store the delta positions on cavnas
  1203. self.dx = 0
  1204. self.dy = 0
  1205. # decide if we have a double click or single click
  1206. self.doubleclick = False
  1207. # store here the is_dragging value
  1208. self.event_is_dragging = False
  1209. # variable to store if a command is active (then the var is not None) and which one it is
  1210. self.command_active = None
  1211. # variable to store the status of moving selection action
  1212. # None value means that it's not an selection action
  1213. # True value = a selection from left to right
  1214. # False value = a selection from right to left
  1215. self.selection_type = None
  1216. # List to store the objects that are currently loaded in FlatCAM
  1217. # This list is updated on each object creation or object delete
  1218. self.all_objects_list = []
  1219. self.objects_under_the_click_list = []
  1220. # List to store the objects that are selected
  1221. self.sel_objects_list = []
  1222. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1223. self.key_modifiers = None
  1224. # Variable to hold the status of the axis
  1225. self.toggle_axis = True
  1226. # Variable to hold the status of the grid lines
  1227. self.toggle_grid_lines = True
  1228. # Variable to store the status of the fullscreen event
  1229. self.toggle_fscreen = False
  1230. # Variable to store the status of the code editor
  1231. self.toggle_codeeditor = False
  1232. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1233. self.click_noproject = False
  1234. self.cursor = None
  1235. # Variable to store the GCODE that was edited
  1236. self.gcode_edited = ""
  1237. self.text_editor_tab = None
  1238. # reference for the self.ui.code_editor
  1239. self.reference_code_editor = None
  1240. self.script_code = ''
  1241. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1242. self.tools_db_changed_flag = False
  1243. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1244. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1245. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1246. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1247. 'tsm']
  1248. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1249. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1250. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1251. 'sbp', 'tap', 'xpi']
  1252. self.svg_list = ['svg']
  1253. self.dxf_list = ['dxf']
  1254. self.pdf_list = ['pdf']
  1255. self.prj_list = ['flatprj']
  1256. self.conf_list = ['flatconfig']
  1257. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1258. # flag for polygons not cleared
  1259. self.poly_not_cleared = False
  1260. # VisPy visuals
  1261. self.isHovering = False
  1262. self.notHovering = True
  1263. # Window geometry
  1264. self.x_pos = None
  1265. self.y_pos = None
  1266. self.width = None
  1267. self.height = None
  1268. # when True, the app has to return from any thread
  1269. self.abort_flag = False
  1270. # set the value used in the Windows Title
  1271. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1272. # this holds a widget that is installed in the Plot Area when View Source option is used
  1273. self.source_editor_tab = None
  1274. self.pagesize = {}
  1275. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1276. # VisPy visuals
  1277. if self.is_legacy is False:
  1278. try:
  1279. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1280. except AttributeError:
  1281. self.tool_shapes = None
  1282. else:
  1283. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1284. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1285. # used in the delayed shutdown self.start_delayed_quit() method
  1286. self.save_timer = None
  1287. # ###########################################################################################################
  1288. # ################################## ADDING FlatCAM EDITORS section #########################################
  1289. # ###########################################################################################################
  1290. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1291. # at the first launch of the App , the editors will not be functional.
  1292. try:
  1293. self.geo_editor = FlatCAMGeoEditor(self)
  1294. except AttributeError:
  1295. pass
  1296. try:
  1297. self.exc_editor = FlatCAMExcEditor(self)
  1298. except AttributeError:
  1299. pass
  1300. try:
  1301. self.grb_editor = FlatCAMGrbEditor(self)
  1302. except AttributeError:
  1303. pass
  1304. self.log.debug("Finished adding FlatCAM Editor's.")
  1305. self.set_ui_title(name=_("New Project - Not saved"))
  1306. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1307. current_platform = platform.architecture()[0]
  1308. if current_platform != '64bit':
  1309. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1310. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1311. # ###########################################################################################################
  1312. # ##################################### Finished the CONSTRUCTOR ############################################
  1313. # ###########################################################################################################
  1314. App.log.debug("END of constructor. Releasing control.")
  1315. # ###########################################################################################################
  1316. # ########################################## SHOW GUI #######################################################
  1317. # ###########################################################################################################
  1318. # if the app is not started as headless, show it
  1319. if self.cmd_line_headless != 1:
  1320. if show_splash:
  1321. # finish the splash
  1322. self.splash.finish(self.ui)
  1323. mgui_settings = QSettings("Open Source", "FlatCAM")
  1324. if mgui_settings.contains("maximized_gui"):
  1325. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1326. if maximized_ui is True:
  1327. self.ui.showMaximized()
  1328. else:
  1329. self.ui.show()
  1330. else:
  1331. self.ui.show()
  1332. if self.defaults["global_systray_icon"]:
  1333. self.trayIcon.show()
  1334. else:
  1335. log.warning("******************* RUNNING HEADLESS *******************")
  1336. # ###########################################################################################################
  1337. # ######################################## START-UP ARGUMENTS ###############################################
  1338. # ###########################################################################################################
  1339. # test if the program was started with a script as parameter
  1340. if self.cmd_line_shellvar:
  1341. try:
  1342. cnt = 0
  1343. command_tcl = 0
  1344. for i in self.cmd_line_shellvar.split(','):
  1345. if i is not None:
  1346. # noinspection PyBroadException
  1347. try:
  1348. command_tcl = eval(i)
  1349. except Exception:
  1350. command_tcl = i
  1351. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1352. cnt += 1
  1353. # if there are Windows paths then replace the path separator with a Unix like one
  1354. if sys.platform == 'win32':
  1355. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1356. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1357. except Exception as ext:
  1358. print("ERROR: ", ext)
  1359. sys.exit(2)
  1360. if self.cmd_line_shellfile:
  1361. if self.cmd_line_headless != 1:
  1362. if self.ui.shell_dock.isHidden():
  1363. self.ui.shell_dock.show()
  1364. try:
  1365. with open(self.cmd_line_shellfile, "r") as myfile:
  1366. # if show_splash:
  1367. # self.splash.showMessage('%s: %ssec\n%s' % (
  1368. # _("Canvas initialization started.\n"
  1369. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1370. # _("Executing Tcl Script ...")),
  1371. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1372. # color=QtGui.QColor("gray"))
  1373. cmd_line_shellfile_text = myfile.read()
  1374. if self.cmd_line_headless != 1:
  1375. self.shell.exec_command(cmd_line_shellfile_text)
  1376. else:
  1377. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1378. except Exception as ext:
  1379. print("ERROR: ", ext)
  1380. sys.exit(2)
  1381. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1382. # the path/file_name must be enclosed in quotes if it contain spaces
  1383. if App.args:
  1384. self.args_at_startup.emit(App.args)
  1385. if self.defaults.old_defaults_found is True:
  1386. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1387. "Please reboot the application to update."))
  1388. self.defaults.old_defaults_found = False
  1389. # ######################################### INIT FINISHED #######################################################
  1390. # #################################################################################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. # #################################################################################################################
  1395. @staticmethod
  1396. def copy_and_overwrite(from_path, to_path):
  1397. """
  1398. From here:
  1399. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1400. :param from_path: source path
  1401. :param to_path: destination path
  1402. :return: None
  1403. """
  1404. if os.path.exists(to_path):
  1405. shutil.rmtree(to_path)
  1406. try:
  1407. shutil.copytree(from_path, to_path)
  1408. except FileNotFoundError:
  1409. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1410. shutil.copytree(from_new_path, to_path)
  1411. def on_startup_args(self, args, silent=False):
  1412. """
  1413. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1414. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1415. :param args: a list containing the application args at startup
  1416. :return: None
  1417. """
  1418. if args is not None:
  1419. args_to_process = args
  1420. else:
  1421. args_to_process = App.args
  1422. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1423. for argument in args_to_process:
  1424. if '.FlatPrj'.lower() in argument.lower():
  1425. try:
  1426. project_name = str(argument)
  1427. if project_name == "":
  1428. if silent is False:
  1429. self.inform.emit(_("Cancelled."))
  1430. else:
  1431. # self.open_project(project_name)
  1432. run_from_arg = True
  1433. # self.worker_task.emit({'fcn': self.open_project,
  1434. # 'params': [project_name, run_from_arg]})
  1435. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1436. except Exception as e:
  1437. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1438. elif '.FlatConfig'.lower() in argument.lower():
  1439. try:
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Config file failed."))
  1444. else:
  1445. run_from_arg = True
  1446. # self.worker_task.emit({'fcn': self.open_config_file,
  1447. # 'params': [file_name, run_from_arg]})
  1448. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1449. except Exception as e:
  1450. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1451. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1452. try:
  1453. file_name = str(argument)
  1454. if file_name == "":
  1455. if silent is False:
  1456. self.inform.emit(_("Open Script file failed."))
  1457. else:
  1458. if silent is False:
  1459. self.on_fileopenscript(name=file_name)
  1460. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1461. self.on_filerunscript(name=file_name)
  1462. except Exception as e:
  1463. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1464. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1465. log.debug("App.on_startup_args() --> Quit event.")
  1466. sys.exit()
  1467. elif 'save'.lower() in argument.lower():
  1468. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1469. self.preferencesUiManager.save_defaults()
  1470. else:
  1471. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1472. proc_arg = argument.lower()
  1473. for ext in exc_list:
  1474. proc_ext = ext.replace(' ', '')
  1475. proc_ext = '.%s' % proc_ext
  1476. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1477. file_name = str(argument)
  1478. if file_name == "":
  1479. if silent is False:
  1480. self.inform.emit(_("Open Excellon file failed."))
  1481. else:
  1482. self.on_fileopenexcellon(name=file_name, signal=None)
  1483. return
  1484. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1485. for ext in gco_list:
  1486. proc_ext = ext.replace(' ', '')
  1487. proc_ext = '.%s' % proc_ext
  1488. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1489. file_name = str(argument)
  1490. if file_name == "":
  1491. if silent is False:
  1492. self.inform.emit(_("Open GCode file failed."))
  1493. else:
  1494. self.on_fileopengcode(name=file_name, signal=None)
  1495. return
  1496. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1497. for ext in grb_list:
  1498. proc_ext = ext.replace(' ', '')
  1499. proc_ext = '.%s' % proc_ext
  1500. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1501. file_name = str(argument)
  1502. if file_name == "":
  1503. if silent is False:
  1504. self.inform.emit(_("Open Gerber file failed."))
  1505. else:
  1506. self.on_fileopengerber(name=file_name, signal=None)
  1507. return
  1508. # if it reached here without already returning then the app was registered with a file that it does not
  1509. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1510. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1511. # for arg in args_to_process:
  1512. # if 'FlatCAM.exe' in arg:
  1513. # continue
  1514. # else:
  1515. # sys.exit(2)
  1516. def set_ui_title(self, name):
  1517. """
  1518. Sets the title of the main window.
  1519. :param name: String that store the project path and project name
  1520. :return: None
  1521. """
  1522. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1523. (self.version,
  1524. ('BETA' if self.beta else ''),
  1525. platform.architecture()[0],
  1526. self.engine,
  1527. name)
  1528. )
  1529. def on_app_restart(self):
  1530. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1531. # be left in the SySTray
  1532. try:
  1533. self.trayIcon.hide()
  1534. except Exception:
  1535. pass
  1536. fcTranslate.restart_program(app=self)
  1537. def clear_pool(self):
  1538. """
  1539. Clear the multiprocessing pool and calls garbage collector.
  1540. :return: None
  1541. """
  1542. self.pool.close()
  1543. self.pool = Pool()
  1544. self.pool_recreated.emit(self.pool)
  1545. gc.collect()
  1546. def install_tools(self):
  1547. """
  1548. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1549. Instantiation of the Tools classes.
  1550. The order that the tools are installed is important as they can depend on each other install position.
  1551. :return: None
  1552. """
  1553. self.distance_tool = Distance(self)
  1554. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1555. before=self.ui.menueditorigin,
  1556. separator=False)
  1557. self.distance_min_tool = DistanceMin(self)
  1558. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1559. pos=self.ui.menuedit,
  1560. before=self.ui.menueditorigin,
  1561. separator=True)
  1562. self.dblsidedtool = DblSidedTool(self)
  1563. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1564. self.cal_exc_tool = ToolCalibration(self)
  1565. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1566. before=self.dblsidedtool.menuAction,
  1567. separator=False)
  1568. self.align_objects_tool = AlignObjects(self)
  1569. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1570. self.edrills_tool = ToolExtractDrills(self)
  1571. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1572. self.panelize_tool = Panelize(self)
  1573. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1574. self.film_tool = Film(self)
  1575. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1576. self.paste_tool = SolderPaste(self)
  1577. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1578. self.calculator_tool = ToolCalculator(self)
  1579. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1580. self.sub_tool = ToolSub(self)
  1581. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1582. pos=self.ui.menutool, separator=True)
  1583. self.rules_tool = RulesCheck(self)
  1584. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1585. pos=self.ui.menutool, separator=False)
  1586. self.optimal_tool = ToolOptimal(self)
  1587. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1588. pos=self.ui.menutool, separator=True)
  1589. self.move_tool = ToolMove(self)
  1590. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1591. before=self.ui.menueditorigin, separator=True)
  1592. self.cutout_tool = CutOut(self)
  1593. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1594. before=self.sub_tool.menuAction)
  1595. self.ncclear_tool = NonCopperClear(self)
  1596. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1597. before=self.sub_tool.menuAction, separator=True)
  1598. self.paint_tool = ToolPaint(self)
  1599. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1600. before=self.sub_tool.menuAction, separator=True)
  1601. self.copper_thieving_tool = ToolCopperThieving(self)
  1602. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1603. pos=self.ui.menutool)
  1604. self.fiducial_tool = ToolFiducials(self)
  1605. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1606. pos=self.ui.menutool)
  1607. self.qrcode_tool = QRCode(self)
  1608. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1609. pos=self.ui.menutool)
  1610. self.punch_tool = ToolPunchGerber(self)
  1611. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1612. self.invert_tool = ToolInvertGerber(self)
  1613. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1614. self.transform_tool = ToolTransform(self)
  1615. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1616. pos=self.ui.menuoptions, separator=True)
  1617. self.properties_tool = Properties(self)
  1618. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1619. pos=self.ui.menuoptions)
  1620. self.pdf_tool = ToolPDF(self)
  1621. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1622. pos=self.ui.menufileimport,
  1623. separator=True)
  1624. self.image_tool = ToolImage(self)
  1625. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1626. pos=self.ui.menufileimport,
  1627. separator=True)
  1628. self.pcb_wizard_tool = PcbWizard(self)
  1629. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1630. pos=self.ui.menufileimport)
  1631. self.log.debug("Tools are installed.")
  1632. def remove_tools(self):
  1633. """
  1634. Will remove all the actions in the Tool menu.
  1635. :return: None
  1636. """
  1637. for act in self.ui.menutool.actions():
  1638. self.ui.menutool.removeAction(act)
  1639. def init_tools(self):
  1640. """
  1641. Initialize the Tool tab in the notebook side of the central widget.
  1642. Remove the actions in the Tools menu.
  1643. Instantiate again the FlatCAM tools (plugins).
  1644. All this is required when changing the layout: standard, compact etc.
  1645. :return: None
  1646. """
  1647. log.debug("init_tools()")
  1648. # delete the data currently in the Tools Tab and the Tab itself
  1649. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1650. if widget is not None:
  1651. widget.deleteLater()
  1652. self.ui.notebook.removeTab(2)
  1653. # rebuild the Tools Tab
  1654. self.ui.tool_tab = QtWidgets.QWidget()
  1655. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1656. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1657. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1658. self.ui.tool_scroll_area = VerticalScrollArea()
  1659. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1660. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1661. # first remove all of them
  1662. self.remove_tools()
  1663. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1664. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1665. '&Command Line\tS')
  1666. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1667. # third install all of them
  1668. try:
  1669. self.install_tools()
  1670. except AttributeError:
  1671. pass
  1672. self.log.debug("Tools are initialized.")
  1673. # def parse_system_fonts(self):
  1674. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1675. # 'params': []})
  1676. def connect_toolbar_signals(self):
  1677. """
  1678. Reconnect the signals to the actions in the toolbar.
  1679. This has to be done each time after the FlatCAM tools are removed/installed.
  1680. :return: None
  1681. """
  1682. # Toolbar
  1683. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1684. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1685. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1686. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1687. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1688. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1689. self.ui.replot_btn.triggered.connect(self.plot_all)
  1690. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1691. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1692. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1693. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1694. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1695. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1696. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1697. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1698. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1699. self.ui.delete_btn.triggered.connect(self.on_delete)
  1700. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1701. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1702. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1703. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1704. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1705. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1706. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1707. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1708. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1709. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1710. # Tools Toolbar Signals
  1711. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1712. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1713. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1714. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1715. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1716. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1717. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1718. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1719. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1720. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1721. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1722. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1723. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1724. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1725. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1726. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1727. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1728. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1729. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1730. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1731. def object2editor(self):
  1732. """
  1733. Send the current Geometry or Excellon object (if any) into the it's editor.
  1734. :return: None
  1735. """
  1736. self.defaults.report_usage("object2editor()")
  1737. # disable the objects menu as it may interfere with the Editors
  1738. self.ui.menuobjects.setDisabled(True)
  1739. edited_object = self.collection.get_active()
  1740. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1741. isinstance(edited_object, ExcellonObject):
  1742. pass
  1743. else:
  1744. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1745. return
  1746. if isinstance(edited_object, GeometryObject):
  1747. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1748. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1749. # we set the notebook to hidden
  1750. # self.ui.splitter.setSizes([0, 1])
  1751. if edited_object.multigeo is True:
  1752. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1753. if len(sel_rows) > 1:
  1754. self.inform.emit('[WARNING_NOTCL] %s' %
  1755. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1756. "is not possible.\n"
  1757. "Edit only one geometry at a time."))
  1758. # determine the tool dia of the selected tool
  1759. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1760. # now find the key in the edited_object.tools that has this tooldia
  1761. multi_tool = 1
  1762. for tool in edited_object.tools:
  1763. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1764. multi_tool = tool
  1765. break
  1766. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1767. else:
  1768. self.geo_editor.edit_fcgeometry(edited_object)
  1769. # set call source to the Editor we go into
  1770. self.call_source = 'geo_editor'
  1771. elif isinstance(edited_object, ExcellonObject):
  1772. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1773. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1774. if self.ui.splitter.sizes()[0] == 0:
  1775. self.ui.splitter.setSizes([1, 1])
  1776. self.exc_editor.edit_fcexcellon(edited_object)
  1777. # set call source to the Editor we go into
  1778. self.call_source = 'exc_editor'
  1779. elif isinstance(edited_object, GerberObject):
  1780. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1781. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1782. if self.ui.splitter.sizes()[0] == 0:
  1783. self.ui.splitter.setSizes([1, 1])
  1784. self.grb_editor.edit_fcgerber(edited_object)
  1785. # set call source to the Editor we go into
  1786. self.call_source = 'grb_editor'
  1787. # reset the following variables so the UI is built again after edit
  1788. edited_object.ui_build = False
  1789. edited_object.build_aperture_storage = False
  1790. # make sure that we can't select another object while in Editor Mode:
  1791. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1792. self.ui.project_frame.setDisabled(True)
  1793. # delete any selection shape that might be active as they are not relevant in Editor
  1794. self.delete_selection_shape()
  1795. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1796. self.ui.plot_tab_area.protectTab(0)
  1797. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1798. self.should_we_save = True
  1799. def editor2object(self, cleanup=None):
  1800. """
  1801. Transfers the Geometry or Excellon from it's editor to the current object.
  1802. :return: None
  1803. """
  1804. self.defaults.report_usage("editor2object()")
  1805. # re-enable the objects menu that was disabled on entry in Editor mode
  1806. self.ui.menuobjects.setDisabled(False)
  1807. # do not update a geometry or excellon object unless it comes out of an editor
  1808. if self.call_source != 'app':
  1809. edited_obj = self.collection.get_active()
  1810. if cleanup is None:
  1811. msgbox = QtWidgets.QMessageBox()
  1812. msgbox.setText(_("Do you want to save the edited object?"))
  1813. msgbox.setWindowTitle(_("Close Editor"))
  1814. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1815. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1816. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1817. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1818. msgbox.setDefaultButton(bt_yes)
  1819. msgbox.exec_()
  1820. response = msgbox.clickedButton()
  1821. if response == bt_yes:
  1822. # clean the Tools Tab
  1823. self.ui.tool_scroll_area.takeWidget()
  1824. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1825. self.ui.notebook.setTabText(2, "Tool")
  1826. if isinstance(edited_obj, GeometryObject):
  1827. obj_type = "Geometry"
  1828. if cleanup is None:
  1829. self.geo_editor.update_fcgeometry(edited_obj)
  1830. # self.geo_editor.update_options(edited_obj)
  1831. self.geo_editor.deactivate()
  1832. # restore GUI to the Selected TAB
  1833. # Remove anything else in the GUI
  1834. self.ui.tool_scroll_area.takeWidget()
  1835. # update the geo object options so it is including the bounding box values
  1836. try:
  1837. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1838. edited_obj.options['xmin'] = xmin
  1839. edited_obj.options['ymin'] = ymin
  1840. edited_obj.options['xmax'] = xmax
  1841. edited_obj.options['ymax'] = ymax
  1842. except AttributeError as e:
  1843. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1844. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1845. edited_obj.build_ui()
  1846. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1847. elif isinstance(edited_obj, GerberObject):
  1848. obj_type = "Gerber"
  1849. if cleanup is None:
  1850. self.grb_editor.update_fcgerber()
  1851. self.grb_editor.update_options(edited_obj)
  1852. self.grb_editor.deactivate_grb_editor()
  1853. # delete the old object (the source object) if it was an empty one
  1854. try:
  1855. if len(edited_obj.solid_geometry) == 0:
  1856. old_name = edited_obj.options['name']
  1857. self.collection.set_active(old_name)
  1858. self.collection.delete_active()
  1859. except TypeError:
  1860. # if the solid_geometry is a single Polygon the len() will not work
  1861. # in any case, falling here means that we have something in the solid_geometry, even if only
  1862. # a single Polygon, therefore we pass this
  1863. pass
  1864. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1865. # restore GUI to the Selected TAB
  1866. # Remove anything else in the GUI
  1867. self.ui.selected_scroll_area.takeWidget()
  1868. elif isinstance(edited_obj, ExcellonObject):
  1869. obj_type = "Excellon"
  1870. if cleanup is None:
  1871. self.exc_editor.update_fcexcellon(edited_obj)
  1872. # self.exc_editor.update_options(edited_obj)
  1873. self.exc_editor.deactivate()
  1874. # restore GUI to the Selected TAB
  1875. # Remove anything else in the GUI
  1876. self.ui.tool_scroll_area.takeWidget()
  1877. # delete the old object (the source object) if it was an empty one
  1878. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1879. old_name = edited_obj.options['name']
  1880. self.collection.delete_by_name(name=old_name)
  1881. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1882. else:
  1883. self.inform.emit('[WARNING_NOTCL] %s' %
  1884. _("Select a Gerber, Geometry or Excellon Object to update."))
  1885. return
  1886. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1887. elif response == bt_no:
  1888. # clean the Tools Tab
  1889. self.ui.tool_scroll_area.takeWidget()
  1890. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1891. self.ui.notebook.setTabText(2, "Tool")
  1892. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1893. if isinstance(edited_obj, GeometryObject):
  1894. self.geo_editor.deactivate()
  1895. edited_obj.build_ui()
  1896. elif isinstance(edited_obj, GerberObject):
  1897. self.grb_editor.deactivate_grb_editor()
  1898. edited_obj.build_ui()
  1899. elif isinstance(edited_obj, ExcellonObject):
  1900. self.exc_editor.deactivate()
  1901. edited_obj.build_ui()
  1902. else:
  1903. self.inform.emit('[WARNING_NOTCL] %s' %
  1904. _("Select a Gerber, Geometry or Excellon Object to update."))
  1905. return
  1906. elif response == bt_cancel:
  1907. return
  1908. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1909. # edited_obj.build_ui()
  1910. # Switch notebook to Selected page
  1911. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1912. else:
  1913. if isinstance(edited_obj, GeometryObject):
  1914. self.geo_editor.deactivate()
  1915. elif isinstance(edited_obj, GerberObject):
  1916. self.grb_editor.deactivate_grb_editor()
  1917. elif isinstance(edited_obj, ExcellonObject):
  1918. self.exc_editor.deactivate()
  1919. else:
  1920. self.inform.emit('[WARNING_NOTCL] %s' %
  1921. _("Select a Gerber, Geometry or Excellon Object to update."))
  1922. return
  1923. # if notebook is hidden we show it
  1924. if self.ui.splitter.sizes()[0] == 0:
  1925. self.ui.splitter.setSizes([1, 1])
  1926. # restore the call_source to app
  1927. self.call_source = 'app'
  1928. edited_obj.plot()
  1929. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1930. self.ui.plot_tab_area.protectTab(0)
  1931. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1932. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1933. self.ui.project_frame.setDisabled(False)
  1934. def get_last_folder(self):
  1935. """
  1936. Get the folder path from where the last file was opened.
  1937. :return: String, last opened folder path
  1938. """
  1939. return self.defaults["global_last_folder"]
  1940. def get_last_save_folder(self):
  1941. """
  1942. Get the folder path from where the last file was saved.
  1943. :return: String, last saved folder path
  1944. """
  1945. loc = self.defaults["global_last_save_folder"]
  1946. if loc is None:
  1947. loc = self.defaults["global_last_folder"]
  1948. if loc is None:
  1949. loc = os.path.dirname(__file__)
  1950. return loc
  1951. def info(self, msg):
  1952. """
  1953. Informs the user. Normally on the status bar, optionally
  1954. also on the shell.
  1955. :param msg: Text to write.
  1956. :return: None
  1957. """
  1958. # Type of message in brackets at the beginning of the message.
  1959. match = re.search(r"\[(.*)\](.*)", msg)
  1960. if match:
  1961. level = match.group(1)
  1962. msg_ = match.group(2)
  1963. self.ui.fcinfo.set_status(str(msg_), level=level)
  1964. if level.lower() == "error":
  1965. self.shell_message(msg, error=True, show=True)
  1966. elif level.lower() == "warning":
  1967. self.shell_message(msg, warning=True, show=True)
  1968. elif level.lower() == "error_notcl":
  1969. self.shell_message(msg, error=True, show=False)
  1970. elif level.lower() == "warning_notcl":
  1971. self.shell_message(msg, warning=True, show=False)
  1972. elif level.lower() == "success":
  1973. self.shell_message(msg, success=True, show=False)
  1974. elif level.lower() == "selected":
  1975. self.shell_message(msg, selected=True, show=False)
  1976. else:
  1977. self.shell_message(msg, show=False)
  1978. else:
  1979. self.ui.fcinfo.set_status(str(msg), level="info")
  1980. # make sure that if the message is to clear the infobar with a space
  1981. # is not printed over and over on the shell
  1982. if msg != '':
  1983. self.shell_message(msg)
  1984. def restore_toolbar_view(self):
  1985. """
  1986. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1987. was saved in the defaults dictionary.
  1988. :return: None
  1989. """
  1990. tb = self.defaults["global_toolbar_view"]
  1991. if tb & 1:
  1992. self.ui.toolbarfile.setVisible(True)
  1993. else:
  1994. self.ui.toolbarfile.setVisible(False)
  1995. if tb & 2:
  1996. self.ui.toolbargeo.setVisible(True)
  1997. else:
  1998. self.ui.toolbargeo.setVisible(False)
  1999. if tb & 4:
  2000. self.ui.toolbarview.setVisible(True)
  2001. else:
  2002. self.ui.toolbarview.setVisible(False)
  2003. if tb & 8:
  2004. self.ui.toolbartools.setVisible(True)
  2005. else:
  2006. self.ui.toolbartools.setVisible(False)
  2007. if tb & 16:
  2008. self.ui.exc_edit_toolbar.setVisible(True)
  2009. else:
  2010. self.ui.exc_edit_toolbar.setVisible(False)
  2011. if tb & 32:
  2012. self.ui.geo_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.geo_edit_toolbar.setVisible(False)
  2015. if tb & 64:
  2016. self.ui.grb_edit_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.grb_edit_toolbar.setVisible(False)
  2019. if tb & 128:
  2020. self.ui.snap_toolbar.setVisible(True)
  2021. else:
  2022. self.ui.snap_toolbar.setVisible(False)
  2023. if tb & 256:
  2024. self.ui.toolbarshell.setVisible(True)
  2025. else:
  2026. self.ui.toolbarshell.setVisible(False)
  2027. def on_import_preferences(self):
  2028. """
  2029. Loads the application default settings from a saved file into
  2030. ``self.defaults`` dictionary.
  2031. :return: None
  2032. """
  2033. self.defaults.report_usage("on_import_preferences")
  2034. App.log.debug("App.on_import_preferences()")
  2035. # Show file chooser
  2036. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2037. try:
  2038. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2039. directory=self.data_path,
  2040. filter=filter_)
  2041. except TypeError:
  2042. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2043. filter=filter_)
  2044. filename = str(filename)
  2045. if filename == "":
  2046. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2047. return
  2048. # Load in the defaults from the chosen file
  2049. self.defaults.load(filename=filename)
  2050. self.preferencesUiManager.on_preferences_edited()
  2051. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2052. def on_export_preferences(self):
  2053. """
  2054. Save the defaults dictionary to a file.
  2055. :return: None
  2056. """
  2057. self.defaults.report_usage("on_export_preferences")
  2058. App.log.debug("on_export_preferences()")
  2059. defaults_file_content = None
  2060. # Show file chooser
  2061. date = str(datetime.today()).rpartition('.')[0]
  2062. date = ''.join(c for c in date if c not in ':-')
  2063. date = date.replace(' ', '_')
  2064. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2065. try:
  2066. filename, _f = FCFileSaveDialog.get_saved_filename(
  2067. caption=_("Export FlatCAM Preferences"),
  2068. directory=self.data_path + '/preferences_' + date,
  2069. filter=filter__
  2070. )
  2071. except TypeError:
  2072. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2073. filename = str(filename)
  2074. if filename == "":
  2075. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2076. return
  2077. # Update options
  2078. self.preferencesUiManager.defaults_read_form()
  2079. self.defaults.propagate_defaults()
  2080. # Save update options
  2081. try:
  2082. self.defaults.write(filename=filename)
  2083. except Exception:
  2084. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2085. return
  2086. if self.defaults["global_open_style"] is False:
  2087. self.file_opened.emit("preferences", filename)
  2088. self.file_saved.emit("preferences", filename)
  2089. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2090. def save_to_file(self, content_to_save, txt_content):
  2091. """
  2092. Save something to a file.
  2093. :return: None
  2094. """
  2095. self.defaults.report_usage("save_to_file")
  2096. App.log.debug("save_to_file()")
  2097. self.date = str(datetime.today()).rpartition('.')[0]
  2098. self.date = ''.join(c for c in self.date if c not in ':-')
  2099. self.date = self.date.replace(' ', '_')
  2100. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2101. path_to_save = self.defaults["global_last_save_folder"] if\
  2102. self.defaults["global_last_save_folder"] is not None else self.data_path
  2103. try:
  2104. filename, _f = FCFileSaveDialog.get_saved_filename(
  2105. caption=_("Save to file"),
  2106. directory=path_to_save + '/file_' + self.date,
  2107. filter=filter__
  2108. )
  2109. except TypeError:
  2110. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2111. filename = str(filename)
  2112. if filename == "":
  2113. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2114. return
  2115. else:
  2116. try:
  2117. with open(filename, 'w') as f:
  2118. ___ = f.read()
  2119. except PermissionError:
  2120. self.inform.emit('[WARNING] %s' %
  2121. _("Permission denied, saving not possible.\n"
  2122. "Most likely another app is holding the file open and not accessible."))
  2123. return
  2124. except IOError:
  2125. App.log.debug('Creating a new file ...')
  2126. f = open(filename, 'w')
  2127. f.close()
  2128. except Exception:
  2129. e = sys.exc_info()[0]
  2130. App.log.error("Could not load the file.")
  2131. App.log.error(str(e))
  2132. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2133. return
  2134. # Save content
  2135. if filename.rpartition('.')[2].lower() == 'html':
  2136. file_content = content_to_save
  2137. else:
  2138. file_content = txt_content
  2139. try:
  2140. with open(filename, "w") as f:
  2141. f.write(file_content)
  2142. except Exception:
  2143. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2144. return
  2145. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2146. def save_geometry(self, x, y, width, height, notebook_width):
  2147. """
  2148. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2149. launch of the application.
  2150. :param x: X position of the main window
  2151. :param y: Y position of the main window
  2152. :param width: width of the main window
  2153. :param height: height of the main window
  2154. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2155. :return: None
  2156. """
  2157. self.defaults["global_def_win_x"] = x
  2158. self.defaults["global_def_win_y"] = y
  2159. self.defaults["global_def_win_w"] = width
  2160. self.defaults["global_def_win_h"] = height
  2161. self.defaults["global_def_notebook_width"] = notebook_width
  2162. self.preferencesUiManager.save_defaults()
  2163. def restore_main_win_geom(self):
  2164. try:
  2165. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2166. self.defaults["global_def_win_y"],
  2167. self.defaults["global_def_win_w"],
  2168. self.defaults["global_def_win_h"])
  2169. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2170. except KeyError as e:
  2171. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2172. def message_dialog(self, title, message, kind="info"):
  2173. """
  2174. Builds and show a custom QMessageBox to be used in FlatCAM.
  2175. :param title: title of the QMessageBox
  2176. :param message: message to be displayed
  2177. :param kind: type of QMessageBox; will display a specific icon.
  2178. :return:
  2179. """
  2180. icon = {"info": QtWidgets.QMessageBox.Information,
  2181. "warning": QtWidgets.QMessageBox.Warning,
  2182. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2183. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2184. dlg.setText(message)
  2185. dlg.exec_()
  2186. def register_recent(self, kind, filename):
  2187. """
  2188. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2189. dictionary.
  2190. :param kind: type of file that was opened
  2191. :param filename: the path and file name for the file that was opened
  2192. :return:
  2193. """
  2194. self.log.debug("register_recent()")
  2195. self.log.debug(" %s" % kind)
  2196. self.log.debug(" %s" % filename)
  2197. record = {'kind': str(kind), 'filename': str(filename)}
  2198. if record in self.recent:
  2199. return
  2200. if record in self.recent_projects:
  2201. return
  2202. if record['kind'] == 'project':
  2203. self.recent_projects.insert(0, record)
  2204. else:
  2205. self.recent.insert(0, record)
  2206. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2207. self.recent.pop()
  2208. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2209. self.recent_projects.pop()
  2210. try:
  2211. f = open(self.data_path + '/recent.json', 'w')
  2212. except IOError:
  2213. App.log.error("Failed to open recent items file for writing.")
  2214. self.inform.emit('[ERROR_NOTCL] %s' %
  2215. _('Failed to open recent files file for writing.'))
  2216. return
  2217. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2218. f.close()
  2219. try:
  2220. fp = open(self.data_path + '/recent_projects.json', 'w')
  2221. except IOError:
  2222. App.log.error("Failed to open recent items file for writing.")
  2223. self.inform.emit('[ERROR_NOTCL] %s' %
  2224. _('Failed to open recent projects file for writing.'))
  2225. return
  2226. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2227. fp.close()
  2228. # Re-build the recent items menu
  2229. self.setup_recent_items()
  2230. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2231. """
  2232. Creates a new specialized FlatCAMObj and attaches it to the application,
  2233. this is, updates the GUI accordingly, any other records and plots it.
  2234. This method is thread-safe.
  2235. Notes:
  2236. * If the name is in use, the self.collection will modify it
  2237. when appending it to the collection. There is no need to handle
  2238. name conflicts here.
  2239. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2240. :type kind: str
  2241. :param name: Name for the object.
  2242. :type name: str
  2243. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2244. The function is called with 2 parameters: the new object and the App instance.
  2245. :type initialize: function
  2246. :param active:
  2247. :param fit:
  2248. :param plot: If to plot the resulting object
  2249. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2250. self.collection
  2251. :return: None
  2252. :rtype: None
  2253. """
  2254. App.log.debug("new_object()")
  2255. obj_plot = plot
  2256. obj_autoselected = autoselected
  2257. t0 = time.time() # Debug
  2258. # ## Create object
  2259. classdict = {
  2260. "gerber": GerberObject,
  2261. "excellon": ExcellonObject,
  2262. "cncjob": CNCJobObject,
  2263. "geometry": GeometryObject,
  2264. "script": ScriptObject,
  2265. "document": DocumentObject
  2266. }
  2267. App.log.debug("Calling object constructor...")
  2268. # Object creation/instantiation
  2269. obj = classdict[kind](name)
  2270. obj.units = self.options["units"]
  2271. # IMPORTANT
  2272. # The key names in defaults and options dictionary's are not random:
  2273. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2274. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2275. # copied to self.options. After that, below, depending on the type of
  2276. # object that is created, it will strip the name of the object and the underline (if the original key was
  2277. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2278. # "toolchange"
  2279. for option in self.options:
  2280. if option.find(kind + "_") == 0:
  2281. oname = option[len(kind) + 1:]
  2282. obj.options[oname] = self.options[option]
  2283. obj.isHovering = False
  2284. obj.notHovering = True
  2285. # Initialize as per user request
  2286. # User must take care to implement initialize
  2287. # in a thread-safe way as is is likely that we
  2288. # have been invoked in a separate thread.
  2289. t1 = time.time()
  2290. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2291. try:
  2292. return_value = initialize(obj, self)
  2293. except Exception as e:
  2294. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2295. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2296. msg += traceback.format_exc()
  2297. self.inform.emit(msg)
  2298. return "fail"
  2299. t2 = time.time()
  2300. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2301. if return_value == 'fail':
  2302. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2303. return "fail"
  2304. # Check units and convert if necessary
  2305. # This condition CAN be true because initialize() can change obj.units
  2306. if self.options["units"].upper() != obj.units.upper():
  2307. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2308. obj.convert_units(self.options["units"])
  2309. t3 = time.time()
  2310. self.log.debug("%f seconds converting units." % (t3 - t2))
  2311. # Create the bounding box for the object and then add the results to the obj.options
  2312. # But not for Scripts or for Documents
  2313. if kind != 'document' and kind != 'script':
  2314. try:
  2315. xmin, ymin, xmax, ymax = obj.bounds()
  2316. obj.options['xmin'] = xmin
  2317. obj.options['ymin'] = ymin
  2318. obj.options['xmax'] = xmax
  2319. obj.options['ymax'] = ymax
  2320. except Exception as e:
  2321. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2322. return "fail"
  2323. try:
  2324. if kind == 'excellon':
  2325. obj.fill_color = self.defaults["excellon_plot_fill"]
  2326. obj.outline_color = self.defaults["excellon_plot_line"]
  2327. if kind == 'gerber':
  2328. obj.fill_color = self.defaults["gerber_plot_fill"]
  2329. obj.outline_color = self.defaults["gerber_plot_line"]
  2330. except Exception as e:
  2331. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2332. # update the KeyWords list with the name of the file
  2333. self.myKeywords.append(obj.options['name'])
  2334. log.debug("Moving new object back to main thread.")
  2335. # Move the object to the main thread and let the app know that it is available.
  2336. obj.moveToThread(self.main_thread)
  2337. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2338. return obj
  2339. def new_excellon_object(self):
  2340. """
  2341. Creates a new, blank Excellon object.
  2342. :return: None
  2343. """
  2344. self.defaults.report_usage("new_excellon_object()")
  2345. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2346. def new_geometry_object(self):
  2347. """
  2348. Creates a new, blank and single-tool Geometry object.
  2349. :return: None
  2350. """
  2351. self.defaults.report_usage("new_geometry_object()")
  2352. def initialize(obj, app):
  2353. obj.multitool = False
  2354. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2355. def new_gerber_object(self):
  2356. """
  2357. Creates a new, blank Gerber object.
  2358. :return: None
  2359. """
  2360. self.defaults.report_usage("new_gerber_object()")
  2361. def initialize(grb_obj, app):
  2362. grb_obj.multitool = False
  2363. grb_obj.source_file = []
  2364. grb_obj.multigeo = False
  2365. grb_obj.follow = False
  2366. grb_obj.apertures = {}
  2367. grb_obj.solid_geometry = []
  2368. try:
  2369. grb_obj.options['xmin'] = 0
  2370. grb_obj.options['ymin'] = 0
  2371. grb_obj.options['xmax'] = 0
  2372. grb_obj.options['ymax'] = 0
  2373. except KeyError:
  2374. pass
  2375. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2376. def new_script_object(self, name=None, text=None):
  2377. """
  2378. Creates a new, blank TCL Script object.
  2379. :param name: a name for the new object
  2380. :param text: pass a source file to the newly created script to be loaded in it
  2381. :return: None
  2382. """
  2383. self.defaults.report_usage("new_script_object()")
  2384. if text is not None:
  2385. new_source_file = text
  2386. else:
  2387. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2388. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2389. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2390. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2391. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2392. # "ListSys, MillDrills,\n" \
  2393. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2394. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2395. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2396. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2397. # "# SubtractRectangle, Version, WriteGCode\n"
  2398. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2399. '# %s:\n' % _('TCL Tutorial is here') + \
  2400. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2401. '# %s:\n' % _("FlatCAM commands list")
  2402. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2403. "(displayed in Tcl Shell).")
  2404. def initialize(obj, app):
  2405. obj.source_file = deepcopy(new_source_file)
  2406. if name is None:
  2407. outname = 'new_script'
  2408. else:
  2409. outname = name
  2410. self.new_object('script', outname, initialize, plot=False)
  2411. def new_document_object(self):
  2412. """
  2413. Creates a new, blank Document object.
  2414. :return: None
  2415. """
  2416. self.defaults.report_usage("new_document_object()")
  2417. def initialize(obj, app):
  2418. obj.source_file = ""
  2419. self.new_object('document', 'new_document', initialize, plot=False)
  2420. def on_object_created(self, obj, plot, auto_select):
  2421. """
  2422. Event callback for object creation.
  2423. It will add the new object to the collection. After that it will plot the object in a threaded way
  2424. :param obj: The newly created FlatCAM object.
  2425. :param plot: if the newly create object t obe plotted
  2426. :param auto_select: if the newly created object to be autoselected after creation
  2427. :return: None
  2428. """
  2429. t0 = time.time() # DEBUG
  2430. self.log.debug("on_object_created()")
  2431. # The Collection might change the name if there is a collision
  2432. self.collection.append(obj)
  2433. # after adding the object to the collection always update the list of objects that are in the collection
  2434. self.all_objects_list = self.collection.get_list()
  2435. # self.inform.emit('[selected] %s created & selected: %s' %
  2436. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2437. if obj.kind == 'gerber':
  2438. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2439. kind=obj.kind.capitalize(),
  2440. color='green',
  2441. name=str(obj.options['name']), tx=_("created/selected"))
  2442. )
  2443. elif obj.kind == 'excellon':
  2444. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2445. kind=obj.kind.capitalize(),
  2446. color='brown',
  2447. name=str(obj.options['name']), tx=_("created/selected"))
  2448. )
  2449. elif obj.kind == 'cncjob':
  2450. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2451. kind=obj.kind.capitalize(),
  2452. color='blue',
  2453. name=str(obj.options['name']), tx=_("created/selected"))
  2454. )
  2455. elif obj.kind == 'geometry':
  2456. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2457. kind=obj.kind.capitalize(),
  2458. color='red',
  2459. name=str(obj.options['name']), tx=_("created/selected"))
  2460. )
  2461. elif obj.kind == 'script':
  2462. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2463. kind=obj.kind.capitalize(),
  2464. color='orange',
  2465. name=str(obj.options['name']), tx=_("created/selected"))
  2466. )
  2467. elif obj.kind == 'document':
  2468. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2469. kind=obj.kind.capitalize(),
  2470. color='darkCyan',
  2471. name=str(obj.options['name']), tx=_("created/selected"))
  2472. )
  2473. # update the SHELL auto-completer model with the name of the new object
  2474. self.shell._edit.set_model_data(self.myKeywords)
  2475. if auto_select:
  2476. # select the just opened object but deselect the previous ones
  2477. self.collection.set_all_inactive()
  2478. self.collection.set_active(obj.options["name"])
  2479. else:
  2480. self.collection.set_all_inactive()
  2481. # here it is done the object plotting
  2482. def worker_task(t_obj):
  2483. with self.proc_container.new(_("Plotting")):
  2484. if isinstance(t_obj, CNCJobObject):
  2485. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2486. else:
  2487. t_obj.plot()
  2488. t1 = time.time() # DEBUG
  2489. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2490. self.object_plotted.emit(t_obj)
  2491. # Send to worker
  2492. # self.worker.add_task(worker_task, [self])
  2493. if plot is True:
  2494. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2495. def on_object_changed(self, obj):
  2496. """
  2497. Called whenever the geometry of the object was changed in some way.
  2498. This require the update of it's bounding values so it can be the selected on canvas.
  2499. Update the bounding box data from obj.options
  2500. :param obj: the object that was changed
  2501. :return: None
  2502. """
  2503. xmin, ymin, xmax, ymax = obj.bounds()
  2504. obj.options['xmin'] = xmin
  2505. obj.options['ymin'] = ymin
  2506. obj.options['xmax'] = xmax
  2507. obj.options['ymax'] = ymax
  2508. log.debug("Object changed, updating the bounding box data on self.options")
  2509. # delete the old selection shape
  2510. self.delete_selection_shape()
  2511. self.should_we_save = True
  2512. def on_object_plotted(self):
  2513. """
  2514. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2515. :return: None
  2516. """
  2517. self.on_zoom_fit(None)
  2518. def on_about(self):
  2519. """
  2520. Displays the "about" dialog found in the Menu --> Help.
  2521. :return: None
  2522. """
  2523. self.defaults.report_usage("on_about")
  2524. version = self.version
  2525. version_date = self.version_date
  2526. beta = self.beta
  2527. class AboutDialog(QtWidgets.QDialog):
  2528. def __init__(self, app, parent=None):
  2529. QtWidgets.QDialog.__init__(self, parent)
  2530. self.app = app
  2531. # Icon and title
  2532. self.setWindowIcon(parent.app_icon)
  2533. self.setWindowTitle(_("About FlatCAM"))
  2534. self.resize(600, 200)
  2535. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2536. # self.setStyleSheet(
  2537. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2538. # "background-attachment: fixed"
  2539. # )
  2540. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2541. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2542. # palette = QtGui.QPalette()
  2543. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2544. # self.setPalette(palette)
  2545. logo = QtWidgets.QLabel()
  2546. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2547. title = QtWidgets.QLabel(
  2548. "<font size=8><B>FlatCAM</B></font><BR>"
  2549. "{title}<BR>"
  2550. "<BR>"
  2551. "<BR>"
  2552. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2553. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2554. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2555. "<B>{issue}</B></a><BR>".format(
  2556. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2557. devel=_("Development"),
  2558. down=_("DOWNLOAD"),
  2559. issue=_("Issue tracker"))
  2560. )
  2561. title.setOpenExternalLinks(True)
  2562. closebtn = QtWidgets.QPushButton(_("Close"))
  2563. tab_widget = QtWidgets.QTabWidget()
  2564. description_label = QtWidgets.QLabel(
  2565. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2566. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2567. version=version,
  2568. beta=('BETA' if beta else ''),
  2569. date=version_date,
  2570. arch=platform.architecture()[0])
  2571. )
  2572. description_label.setOpenExternalLinks(True)
  2573. lic_lbl_header = QtWidgets.QLabel(
  2574. '%s:<br>%s<br>' % (
  2575. _('Licensed under the MIT license'),
  2576. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2577. "http://www.opensource.org/licenses/mit-license.php</a>"
  2578. )
  2579. )
  2580. lic_lbl_header.setOpenExternalLinks(True)
  2581. lic_lbl_body = QtWidgets.QLabel(
  2582. _(
  2583. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2584. 'of this software and associated documentation files (the "Software"), to deal\n'
  2585. 'in the Software without restriction, including without limitation the rights\n'
  2586. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2587. 'copies of the Software, and to permit persons to whom the Software is\n'
  2588. 'furnished to do so, subject to the following conditions:\n\n'
  2589. 'The above copyright notice and this permission notice shall be included in\n'
  2590. 'all copies or substantial portions of the Software.\n\n'
  2591. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2592. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2593. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2594. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2595. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2596. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2597. 'THE SOFTWARE.'
  2598. )
  2599. )
  2600. attributions_label = QtWidgets.QLabel(
  2601. _(
  2602. 'Some of the icons used are from the following sources:<br>'
  2603. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2604. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2605. 'title="Flaticon">www.flaticon.com</a></div>'
  2606. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2607. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2608. )
  2609. )
  2610. attributions_label.setOpenExternalLinks(True)
  2611. # layouts
  2612. layout1 = QtWidgets.QVBoxLayout()
  2613. layout1_1 = QtWidgets.QHBoxLayout()
  2614. layout1_2 = QtWidgets.QHBoxLayout()
  2615. layout2 = QtWidgets.QHBoxLayout()
  2616. layout3 = QtWidgets.QHBoxLayout()
  2617. self.setLayout(layout1)
  2618. layout1.addLayout(layout1_1)
  2619. layout1.addLayout(layout1_2)
  2620. layout1.addLayout(layout2)
  2621. layout1.addLayout(layout3)
  2622. layout1_1.addStretch()
  2623. layout1_1.addWidget(description_label)
  2624. layout1_2.addWidget(tab_widget)
  2625. self.splash_tab = QtWidgets.QWidget()
  2626. self.splash_tab.setObjectName("splash_about")
  2627. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2628. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2629. tab_widget.addTab(self.splash_tab, _("Splash"))
  2630. self.programmmers_tab = QtWidgets.QWidget()
  2631. self.programmmers_tab.setObjectName("programmers_about")
  2632. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2633. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2634. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2635. self.translators_tab = QtWidgets.QWidget()
  2636. self.translators_tab.setObjectName("translators_about")
  2637. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2638. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2639. tab_widget.addTab(self.translators_tab, _("Translators"))
  2640. self.license_tab = QtWidgets.QWidget()
  2641. self.license_tab.setObjectName("license_about")
  2642. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2643. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2644. tab_widget.addTab(self.license_tab, _("License"))
  2645. self.attributions_tab = QtWidgets.QWidget()
  2646. self.attributions_tab.setObjectName("attributions_about")
  2647. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2648. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2649. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2650. self.splash_tab_layout.addWidget(logo, stretch=0)
  2651. self.splash_tab_layout.addWidget(title, stretch=1)
  2652. pal = QtGui.QPalette()
  2653. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2654. self.prog_grid_lay = QtWidgets.QGridLayout()
  2655. self.prog_grid_lay.setHorizontalSpacing(20)
  2656. self.prog_grid_lay.setColumnStretch(0, 0)
  2657. self.prog_grid_lay.setColumnStretch(2, 1)
  2658. prog_widget = QtWidgets.QWidget()
  2659. prog_widget.setLayout(self.prog_grid_lay)
  2660. prog_scroll = QtWidgets.QScrollArea()
  2661. prog_scroll.setWidget(prog_widget)
  2662. prog_scroll.setWidgetResizable(True)
  2663. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2664. prog_scroll.setPalette(pal)
  2665. self.programmmers_tab_layout.addWidget(prog_scroll)
  2666. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2667. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2668. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2712. self.translator_grid_lay = QtWidgets.QGridLayout()
  2713. self.translator_grid_lay.setColumnStretch(0, 0)
  2714. self.translator_grid_lay.setColumnStretch(1, 0)
  2715. self.translator_grid_lay.setColumnStretch(2, 1)
  2716. self.translator_grid_lay.setColumnStretch(3, 0)
  2717. # trans_widget = QtWidgets.QWidget()
  2718. # trans_widget.setLayout(self.translator_grid_lay)
  2719. # self.translators_tab_layout.addWidget(trans_widget)
  2720. # self.translators_tab_layout.addStretch()
  2721. trans_widget = QtWidgets.QWidget()
  2722. trans_widget.setLayout(self.translator_grid_lay)
  2723. trans_scroll = QtWidgets.QScrollArea()
  2724. trans_scroll.setWidget(trans_widget)
  2725. trans_scroll.setWidgetResizable(True)
  2726. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2727. trans_scroll.setPalette(pal)
  2728. self.translators_tab_layout.addWidget(trans_scroll)
  2729. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2730. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2754. self.translator_grid_lay.setColumnStretch(0, 0)
  2755. self.translators_tab_layout.addStretch()
  2756. self.license_tab_layout.addWidget(lic_lbl_header)
  2757. self.license_tab_layout.addWidget(lic_lbl_body)
  2758. self.license_tab_layout.addStretch()
  2759. self.attributions_tab_layout.addWidget(attributions_label)
  2760. self.attributions_tab_layout.addStretch()
  2761. layout3.addStretch()
  2762. layout3.addWidget(closebtn)
  2763. closebtn.clicked.connect(self.accept)
  2764. AboutDialog(app=self, parent=self.ui).exec_()
  2765. def install_bookmarks(self, book_dict=None):
  2766. """
  2767. Install the bookmarks actions in the Help menu -> Bookmarks
  2768. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2769. :return: None
  2770. """
  2771. if book_dict is None:
  2772. self.defaults["global_bookmarks"].update(
  2773. {
  2774. '1': ['FlatCAM', "http://flatcam.org"],
  2775. '2': ['Backup Site', ""]
  2776. }
  2777. )
  2778. else:
  2779. self.defaults["global_bookmarks"].clear()
  2780. self.defaults["global_bookmarks"].update(book_dict)
  2781. # first try to disconnect if somehow they get connected from elsewhere
  2782. for act in self.ui.menuhelp_bookmarks.actions():
  2783. try:
  2784. act.triggered.disconnect()
  2785. except TypeError:
  2786. pass
  2787. # clear all actions except the last one who is the Bookmark manager
  2788. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2789. pass
  2790. else:
  2791. self.ui.menuhelp_bookmarks.removeAction(act)
  2792. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2793. if self.defaults["global_bookmarks"]:
  2794. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2795. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2796. # the JSON is first making the keys as strings (therefore I have to use strings too
  2797. # or do the conversion :(
  2798. # )
  2799. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2800. # the '10' entry jsut after '1' therefore ordering as strings
  2801. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2802. key=lambda x: int(x[0]))
  2803. for entry, bookmark in sorted_bookmarks:
  2804. title = bookmark[0]
  2805. weblink = bookmark[1]
  2806. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2807. act.setText(title)
  2808. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2809. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2810. if title == 'Backup Site' and weblink == "":
  2811. act.triggered.connect(self.on_backup_site)
  2812. else:
  2813. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2814. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2815. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2816. def on_bookmarks_manager(self):
  2817. """
  2818. Adds the bookmark manager in a Tab in Plot Area
  2819. :return:
  2820. """
  2821. for idx in range(self.ui.plot_tab_area.count()):
  2822. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2823. # there can be only one instance of Bookmark Manager at one time
  2824. return
  2825. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2826. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2827. # add the tab if it was closed
  2828. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2829. # delete the absolute and relative position and messages in the infobar
  2830. self.ui.position_label.setText("")
  2831. self.ui.rel_position_label.setText("")
  2832. # Switch plot_area to preferences page
  2833. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2834. def on_backup_site(self):
  2835. msgbox = QtWidgets.QMessageBox()
  2836. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2837. "1. FlatCAM.org website is down\n"
  2838. "2. Someone forked FlatCAM project and wants to point\n"
  2839. "to his own website\n\n"
  2840. "If you can't get any informations about FlatCAM beta\n"
  2841. "use the YouTube channel link from the Help menu."))
  2842. msgbox.setWindowTitle(_("Alternative website"))
  2843. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2844. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2845. msgbox.setDefaultButton(bt_yes)
  2846. msgbox.exec_()
  2847. # response = msgbox.clickedButton()
  2848. def on_file_savedefaults(self):
  2849. """
  2850. Callback for menu item File->Save Defaults. Saves application default options
  2851. ``self.defaults`` to current_defaults.FlatConfig.
  2852. :return: None
  2853. """
  2854. self.preferencesUiManager.save_defaults()
  2855. def final_save(self):
  2856. """
  2857. Callback for doing a preferences save to file whenever the application is about to quit.
  2858. If the project has changes, it will ask the user to save the project.
  2859. :return: None
  2860. """
  2861. if self.save_in_progress:
  2862. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2863. return
  2864. if self.should_we_save and self.collection.get_list():
  2865. msgbox = QtWidgets.QMessageBox()
  2866. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2867. "\n"
  2868. "Do you want to Save the project?"))
  2869. msgbox.setWindowTitle(_("Save changes"))
  2870. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2871. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2872. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2873. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2874. msgbox.setDefaultButton(bt_yes)
  2875. msgbox.exec_()
  2876. response = msgbox.clickedButton()
  2877. if response == bt_yes:
  2878. try:
  2879. self.trayIcon.hide()
  2880. except Exception:
  2881. pass
  2882. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2883. elif response == bt_no:
  2884. try:
  2885. self.trayIcon.hide()
  2886. except Exception:
  2887. pass
  2888. self.quit_application()
  2889. elif response == bt_cancel:
  2890. return
  2891. else:
  2892. try:
  2893. self.trayIcon.hide()
  2894. except Exception:
  2895. pass
  2896. self.quit_application()
  2897. def quit_application(self):
  2898. """
  2899. Called (as a pyslot or not) when the application is quit.
  2900. :return: None
  2901. """
  2902. self.preferencesUiManager.save_defaults(silent=True)
  2903. log.debug("App.quit_application() --> App Defaults saved.")
  2904. if self.cmd_line_headless != 1:
  2905. # save app state to file
  2906. stgs = QSettings("Open Source", "FlatCAM")
  2907. stgs.setValue('saved_gui_state', self.ui.saveState())
  2908. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2909. stgs.setValue(
  2910. 'language',
  2911. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2912. )
  2913. stgs.setValue(
  2914. 'notebook_font_size',
  2915. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2916. )
  2917. stgs.setValue(
  2918. 'axis_font_size',
  2919. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2920. )
  2921. stgs.setValue(
  2922. 'textbox_font_size',
  2923. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2924. )
  2925. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2926. stgs.setValue(
  2927. 'machinist',
  2928. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2929. )
  2930. # This will write the setting to the platform specific storage.
  2931. del stgs
  2932. log.debug("App.quit_application() --> App UI state saved.")
  2933. # try to quit the QThread that run ArgsThread class
  2934. try:
  2935. self.th.quit()
  2936. except Exception as e:
  2937. log.debug("App.quit_application() --> %s" % str(e))
  2938. # try to quit the Socket opened by ArgsThread class
  2939. try:
  2940. self.new_launch.listener.close()
  2941. except Exception as err:
  2942. log.debug("App.quit_application() --> %s" % str(err))
  2943. # quit app by signalling for self.kill_app() method
  2944. # self.close_app_signal.emit()
  2945. QtWidgets.qApp.quit()
  2946. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2947. # we use the following command
  2948. # sys.exit(0)
  2949. os._exit(0) # fix to work with Python 3.8
  2950. @staticmethod
  2951. def kill_app():
  2952. # QtCore.QCoreApplication.quit()
  2953. QtWidgets.qApp.quit()
  2954. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2955. # we use the following command
  2956. sys.exit(0)
  2957. def on_portable_checked(self, state):
  2958. """
  2959. Callback called when the checkbox in Preferences GUI is checked.
  2960. It will set the application as portable by creating the preferences and recent files in the
  2961. 'config' folder found in the FlatCAM installation folder.
  2962. :param state: boolean, the state of the checkbox when clicked/checked
  2963. :return:
  2964. """
  2965. line_no = 0
  2966. data = None
  2967. if sys.platform != 'win32':
  2968. # this won't work in Linux or MacOS
  2969. return
  2970. # test if the app was frozen and choose the path for the configuration file
  2971. if getattr(sys, "frozen", False) is True:
  2972. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2973. else:
  2974. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2975. config_file = current_data_path + '\\configuration.txt'
  2976. try:
  2977. with open(config_file, 'r') as f:
  2978. try:
  2979. data = f.readlines()
  2980. except Exception as e:
  2981. log.debug('App.__init__() -->%s' % str(e))
  2982. return
  2983. except FileNotFoundError:
  2984. pass
  2985. for line in data:
  2986. line = line.strip('\n')
  2987. param = str(line).rpartition('=')
  2988. if param[0] == 'portable':
  2989. break
  2990. line_no += 1
  2991. if state:
  2992. data[line_no] = 'portable=True\n'
  2993. # create the new defauults files
  2994. # create current_defaults.FlatConfig file if there is none
  2995. try:
  2996. f = open(current_data_path + '/current_defaults.FlatConfig')
  2997. f.close()
  2998. except IOError:
  2999. App.log.debug('Creating empty current_defaults.FlatConfig')
  3000. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3001. json.dump({}, f)
  3002. f.close()
  3003. # create factory_defaults.FlatConfig file if there is none
  3004. try:
  3005. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3006. f.close()
  3007. except IOError:
  3008. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3009. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3010. json.dump({}, f)
  3011. f.close()
  3012. try:
  3013. f = open(current_data_path + '/recent.json')
  3014. f.close()
  3015. except IOError:
  3016. App.log.debug('Creating empty recent.json')
  3017. f = open(current_data_path + '/recent.json', 'w')
  3018. json.dump([], f)
  3019. f.close()
  3020. try:
  3021. fp = open(current_data_path + '/recent_projects.json')
  3022. fp.close()
  3023. except IOError:
  3024. App.log.debug('Creating empty recent_projects.json')
  3025. fp = open(current_data_path + '/recent_projects.json', 'w')
  3026. json.dump([], fp)
  3027. fp.close()
  3028. # save the current defaults to the new defaults file
  3029. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3030. else:
  3031. data[line_no] = 'portable=False\n'
  3032. with open(config_file, 'w') as f:
  3033. f.writelines(data)
  3034. def on_register_files(self, obj_type=None):
  3035. """
  3036. Called whenever there is a need to register file extensions with FlatCAM.
  3037. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3038. :param obj_type: the type of object to be register for.
  3039. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3040. :return: None
  3041. """
  3042. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3043. new_reg_path = 'Software\\Classes\\'
  3044. # find if the current user is admin
  3045. try:
  3046. is_admin = os.getuid() == 0
  3047. except AttributeError:
  3048. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3049. if is_admin is True:
  3050. root_path = winreg.HKEY_LOCAL_MACHINE
  3051. else:
  3052. root_path = winreg.HKEY_CURRENT_USER
  3053. # create the keys
  3054. def set_reg(name, root_path, new_reg_path, value):
  3055. try:
  3056. winreg.CreateKey(root_path, new_reg_path)
  3057. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3058. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3059. return True
  3060. except WindowsError:
  3061. return False
  3062. # delete key in registry
  3063. def delete_reg(root_path, reg_path, key_to_del):
  3064. key_to_del_path = reg_path + key_to_del
  3065. try:
  3066. winreg.DeleteKey(root_path, key_to_del_path)
  3067. return True
  3068. except WindowsError:
  3069. return False
  3070. if obj_type is None or obj_type == 'excellon':
  3071. exc_list = \
  3072. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3073. exc_list = [x for x in exc_list if x != '']
  3074. # register all keys in the Preferences window
  3075. for ext in exc_list:
  3076. new_k = new_reg_path + '.%s' % ext
  3077. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3078. # and unregister those that are no longer in the Preferences windows but are in the file
  3079. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3080. if ext not in exc_list:
  3081. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3082. # now write the updated extensions to the self.defaults
  3083. # new_ext = ''
  3084. # for ext in exc_list:
  3085. # new_ext = new_ext + ext + ', '
  3086. # self.defaults["fa_excellon"] = new_ext
  3087. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3088. if obj_type is None or obj_type == 'gcode':
  3089. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3090. gco_list = [x for x in gco_list if x != '']
  3091. # register all keys in the Preferences window
  3092. for ext in gco_list:
  3093. new_k = new_reg_path + '.%s' % ext
  3094. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3095. # and unregister those that are no longer in the Preferences windows but are in the file
  3096. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3097. if ext not in gco_list:
  3098. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3099. # now write the updated extensions to the self.defaults
  3100. # new_ext = ''
  3101. # for ext in gco_list:
  3102. # new_ext = new_ext + ext + ', '
  3103. # self.defaults["fa_gcode"] = new_ext
  3104. self.inform.emit('[success] %s' %
  3105. _("Selected GCode file extensions registered with FlatCAM."))
  3106. if obj_type is None or obj_type == 'gerber':
  3107. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3108. grb_list = [x for x in grb_list if x != '']
  3109. # register all keys in the Preferences window
  3110. for ext in grb_list:
  3111. new_k = new_reg_path + '.%s' % ext
  3112. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3113. # and unregister those that are no longer in the Preferences windows but are in the file
  3114. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3115. if ext not in grb_list:
  3116. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3117. # now write the updated extensions to the self.defaults
  3118. # new_ext = ''
  3119. # for ext in grb_list:
  3120. # new_ext = new_ext + ext + ', '
  3121. # self.defaults["fa_gerber"] = new_ext
  3122. self.inform.emit('[success] %s' %
  3123. _("Selected Gerber file extensions registered with FlatCAM."))
  3124. def add_extension(self, ext_type):
  3125. """
  3126. Add a file extension to the list for a specific object
  3127. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3128. :return:
  3129. """
  3130. if ext_type == 'excellon':
  3131. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3132. if new_ext == '':
  3133. return
  3134. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3135. if new_ext in old_val:
  3136. return
  3137. old_val.append(new_ext)
  3138. old_val.sort()
  3139. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3140. if ext_type == 'gcode':
  3141. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3142. if new_ext == '':
  3143. return
  3144. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3145. if new_ext in old_val:
  3146. return
  3147. old_val.append(new_ext)
  3148. old_val.sort()
  3149. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3150. if ext_type == 'gerber':
  3151. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3152. if new_ext == '':
  3153. return
  3154. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3155. if new_ext in old_val:
  3156. return
  3157. old_val.append(new_ext)
  3158. old_val.sort()
  3159. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3160. if ext_type == 'keyword':
  3161. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3162. if new_kw == '':
  3163. return
  3164. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3165. if new_kw in old_val:
  3166. return
  3167. old_val.append(new_kw)
  3168. old_val.sort()
  3169. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3170. # update the self.myKeywords so the model is updated
  3171. self.autocomplete_kw_list = \
  3172. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3173. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3174. self.shell._edit.set_model_data(self.myKeywords)
  3175. def del_extension(self, ext_type):
  3176. """
  3177. Remove a file extension from the list for a specific object
  3178. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3179. :return:
  3180. """
  3181. if ext_type == 'excellon':
  3182. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3183. if new_ext == '':
  3184. return
  3185. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3186. if new_ext not in old_val:
  3187. return
  3188. old_val.remove(new_ext)
  3189. old_val.sort()
  3190. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3191. if ext_type == 'gcode':
  3192. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3193. if new_ext == '':
  3194. return
  3195. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3196. if new_ext not in old_val:
  3197. return
  3198. old_val.remove(new_ext)
  3199. old_val.sort()
  3200. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3201. if ext_type == 'gerber':
  3202. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3203. if new_ext == '':
  3204. return
  3205. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3206. if new_ext not in old_val:
  3207. return
  3208. old_val.remove(new_ext)
  3209. old_val.sort()
  3210. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3211. if ext_type == 'keyword':
  3212. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3213. if new_kw == '':
  3214. return
  3215. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3216. if new_kw not in old_val:
  3217. return
  3218. old_val.remove(new_kw)
  3219. old_val.sort()
  3220. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3221. # update the self.myKeywords so the model is updated
  3222. self.autocomplete_kw_list = \
  3223. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3224. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3225. self.shell._edit.set_model_data(self.myKeywords)
  3226. def restore_extensions(self, ext_type):
  3227. """
  3228. Restore all file extensions associations with FlatCAM, for a specific object
  3229. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3230. :return:
  3231. """
  3232. if ext_type == 'excellon':
  3233. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3234. # for the ability to open Excellon files with .txt extension
  3235. new_exc_list = deepcopy(self.exc_list)
  3236. try:
  3237. new_exc_list.remove('txt')
  3238. except ValueError:
  3239. pass
  3240. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3241. if ext_type == 'gcode':
  3242. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3243. if ext_type == 'gerber':
  3244. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3245. if ext_type == 'keyword':
  3246. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3247. # update the self.myKeywords so the model is updated
  3248. self.autocomplete_kw_list = self.default_keywords
  3249. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3250. self.shell._edit.set_model_data(self.myKeywords)
  3251. def delete_all_extensions(self, ext_type):
  3252. """
  3253. Delete all file extensions associations with FlatCAM, for a specific object
  3254. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3255. :return:
  3256. """
  3257. if ext_type == 'excellon':
  3258. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3259. if ext_type == 'gcode':
  3260. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3261. if ext_type == 'gerber':
  3262. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3263. if ext_type == 'keyword':
  3264. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3265. # update the self.myKeywords so the model is updated
  3266. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3267. self.shell._edit.set_model_data(self.myKeywords)
  3268. def on_edit_join(self, name=None):
  3269. """
  3270. Callback for Edit->Join. Joins the selected geometry objects into
  3271. a new one.
  3272. :return: None
  3273. """
  3274. self.defaults.report_usage("on_edit_join()")
  3275. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3276. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3277. geo_type_set = set()
  3278. objs = self.collection.get_selected()
  3279. if len(objs) < 2:
  3280. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3281. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3282. return 'fail'
  3283. for obj in objs:
  3284. geo_type_set.add(obj.multigeo)
  3285. # if len(geo_type_list) == 1 means that all list elements are the same
  3286. if len(geo_type_set) != 1:
  3287. self.inform.emit('[ERROR] %s' %
  3288. _("Failed join. The Geometry objects are of different types.\n"
  3289. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3290. "convert from one to another and retry joining \n"
  3291. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3292. "the result may not be what was expected. \n"
  3293. "Check the generated GCODE."))
  3294. return
  3295. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3296. if True in geo_type_set:
  3297. def initialize(geo_obj, app):
  3298. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  3299. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3300. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3301. for v in geo_obj.tools.values():
  3302. v['data']['name'] = obj_name_multi
  3303. self.new_object("geometry", obj_name_multi, initialize)
  3304. else:
  3305. def initialize(geo_obj, app):
  3306. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  3307. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3308. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3309. for v in geo_obj.tools.values():
  3310. v['data']['name'] = obj_name_single
  3311. self.new_object("geometry", obj_name_single, initialize)
  3312. self.should_we_save = True
  3313. def on_edit_join_exc(self):
  3314. """
  3315. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3316. a new Excellon.
  3317. :return: None
  3318. """
  3319. self.defaults.report_usage("on_edit_join_exc()")
  3320. objs = self.collection.get_selected()
  3321. for obj in objs:
  3322. if not isinstance(obj, ExcellonObject):
  3323. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3324. return
  3325. if len(objs) < 2:
  3326. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3327. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3328. return 'fail'
  3329. def initialize(exc_obj, app):
  3330. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj)
  3331. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3332. self.new_object("excellon", 'Combo_Excellon', initialize)
  3333. self.should_we_save = True
  3334. def on_edit_join_grb(self):
  3335. """
  3336. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3337. a new Gerber object.
  3338. :return: None
  3339. """
  3340. self.defaults.report_usage("on_edit_join_grb()")
  3341. objs = self.collection.get_selected()
  3342. for obj in objs:
  3343. if not isinstance(obj, GerberObject):
  3344. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3345. return
  3346. if len(objs) < 2:
  3347. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3348. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3349. return 'fail'
  3350. def initialize(grb_obj, app):
  3351. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  3352. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3353. self.new_object("gerber", 'Combo_Gerber', initialize)
  3354. self.should_we_save = True
  3355. def on_convert_singlegeo_to_multigeo(self):
  3356. """
  3357. Called for converting a Geometry object from single-geo to multi-geo.
  3358. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3359. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3360. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3361. the solid-geometry of that tool.
  3362. :return: None
  3363. """
  3364. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3365. obj = self.collection.get_active()
  3366. if obj is None:
  3367. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3368. return
  3369. if not isinstance(obj, GeometryObject):
  3370. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3371. return
  3372. obj.multigeo = True
  3373. for tooluid, dict_value in obj.tools.items():
  3374. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3375. if not isinstance(obj.solid_geometry, list):
  3376. obj.solid_geometry = [obj.solid_geometry]
  3377. obj.solid_geometry[:] = []
  3378. obj.plot()
  3379. self.should_we_save = True
  3380. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3381. def on_convert_multigeo_to_singlegeo(self):
  3382. """
  3383. Called for converting a Geometry object from multi-geo to single-geo.
  3384. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3385. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3386. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3387. the solid-geometry of that tool.
  3388. :return: None
  3389. """
  3390. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3391. obj = self.collection.get_active()
  3392. if obj is None:
  3393. self.inform.emit('[ERROR_NOTCL] %s' %
  3394. _("Failed. Select a Geometry Object and try again."))
  3395. return
  3396. if not isinstance(obj, GeometryObject):
  3397. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3398. (_("Expected a GeometryObject, got"), type(obj)))
  3399. return
  3400. obj.multigeo = False
  3401. total_solid_geometry = []
  3402. for tooluid, dict_value in obj.tools.items():
  3403. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3404. # clear the original geometry
  3405. dict_value['solid_geometry'][:] = []
  3406. obj.solid_geometry = deepcopy(total_solid_geometry)
  3407. obj.plot()
  3408. self.should_we_save = True
  3409. self.inform.emit('[success] %s' %
  3410. _("A Geometry object was converted to SingleGeo type."))
  3411. def on_defaults_dict_change(self, field):
  3412. """
  3413. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3414. Edit -> Preferences tab window.
  3415. :param field: the key of the self.defaults dictionary that was changed.
  3416. :return: None
  3417. """
  3418. self.preferencesUiManager.defaults_write_form_field(field=field)
  3419. if field == "units":
  3420. self.set_screen_units(self.defaults['units'])
  3421. def set_screen_units(self, units):
  3422. """
  3423. Set the FlatCAM units on the status bar.
  3424. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3425. :return: None
  3426. """
  3427. self.ui.units_label.setText("[" + units.lower() + "]")
  3428. def on_toggle_units_click(self):
  3429. try:
  3430. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3431. except (TypeError, AttributeError):
  3432. pass
  3433. if self.defaults["units"] == 'MM':
  3434. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3435. else:
  3436. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3437. self.on_toggle_units(no_pref=True)
  3438. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3439. lambda: self.on_toggle_units(no_pref=False))
  3440. def on_toggle_units(self, no_pref=False):
  3441. """
  3442. Callback for the Units radio-button change in the Preferences tab.
  3443. Changes the application's default units adn for the project too.
  3444. If changing the project's units, the change propagates to all of
  3445. the objects in the project.
  3446. :return: None
  3447. """
  3448. self.defaults.report_usage("on_toggle_units")
  3449. if self.toggle_units_ignore:
  3450. return
  3451. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3452. # If option is the same, then ignore
  3453. if new_units == self.defaults["units"].upper():
  3454. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3455. return
  3456. # Options to scale
  3457. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  3458. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3459. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3460. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3461. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3462. "excellon_feedrate_probe",
  3463. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3464. "excellon_editor_slot_lin_pitch",
  3465. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3466. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3467. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3468. "geometry_z_pdepth",
  3469. "geometry_feedrate_probe", "geometry_startz",
  3470. 'cncjob_tooldia',
  3471. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3472. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3473. "tools_nccnewdia",
  3474. "tools_2sided_drilldia", "tools_film_boundary",
  3475. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3476. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3477. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3478. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3479. "tools_transform_offset_y",
  3480. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3481. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3482. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3483. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3484. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3485. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3486. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  3487. "tools_fiducials_line_thickness",
  3488. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3489. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3490. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3491. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3492. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3493. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3494. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3495. def scale_defaults(sfactor):
  3496. for dim in dimensions:
  3497. if dim == 'excellon_toolchangexy':
  3498. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3499. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3500. coords_xy[0] *= sfactor
  3501. coords_xy[1] *= sfactor
  3502. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3503. self.decimals, coords_xy[1])
  3504. elif dim == 'geometry_toolchangexy':
  3505. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3506. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3507. coords_xy[0] *= sfactor
  3508. coords_xy[1] *= sfactor
  3509. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3510. self.decimals, coords_xy[1])
  3511. elif dim == 'excellon_endxy':
  3512. coordinates = self.defaults["excellon_endxy"].split(",")
  3513. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3514. end_coords_xy[0] *= sfactor
  3515. end_coords_xy[1] *= sfactor
  3516. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3517. self.decimals, end_coords_xy[1])
  3518. elif dim == 'geometry_endxy':
  3519. coordinates = self.defaults["geometry_endxy"].split(",")
  3520. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3521. end_coords_xy[0] *= sfactor
  3522. end_coords_xy[1] *= sfactor
  3523. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3524. self.decimals, end_coords_xy[1])
  3525. elif dim == 'geometry_cnctooldia':
  3526. if type(self.defaults["geometry_cnctooldia"]) == float:
  3527. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3528. else:
  3529. try:
  3530. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3531. tools_diameters = [eval(a) for a in tools_string if a != '']
  3532. except Exception as e:
  3533. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3534. continue
  3535. self.defaults['geometry_cnctooldia'] = ''
  3536. for t in range(len(tools_diameters)):
  3537. tools_diameters[t] *= sfactor
  3538. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3539. elif dim == 'tools_ncctools':
  3540. if type(self.defaults["tools_ncctools"]) == float:
  3541. ncctools = [self.defaults["tools_ncctools"]]
  3542. else:
  3543. try:
  3544. tools_string = self.defaults["tools_ncctools"].split(",")
  3545. ncctools = [eval(a) for a in tools_string if a != '']
  3546. except Exception as e:
  3547. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3548. continue
  3549. self.defaults['tools_ncctools'] = ''
  3550. for t in range(len(ncctools)):
  3551. ncctools[t] *= sfactor
  3552. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3553. elif dim == 'tools_solderpaste_tools':
  3554. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3555. sptools = [self.defaults["tools_solderpaste_tools"]]
  3556. else:
  3557. try:
  3558. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3559. sptools = [eval(a) for a in tools_string if a != '']
  3560. except Exception as e:
  3561. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3562. continue
  3563. self.defaults['tools_solderpaste_tools'] = ""
  3564. for t in range(len(sptools)):
  3565. sptools[t] *= sfactor
  3566. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3567. elif dim == 'tools_solderpaste_xy_toolchange':
  3568. try:
  3569. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3570. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3571. sp_coords[0] *= sfactor
  3572. sp_coords[1] *= sfactor
  3573. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3574. self.decimals, sp_coords[1])
  3575. except Exception as e:
  3576. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3577. continue
  3578. elif dim == 'global_gridx' or dim == 'global_gridy':
  3579. if new_units == 'IN':
  3580. try:
  3581. val = float(self.defaults[dim]) * sfactor
  3582. except Exception as e:
  3583. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3584. continue
  3585. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3586. else:
  3587. try:
  3588. val = float(self.defaults[dim]) * sfactor
  3589. except Exception as e:
  3590. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3591. continue
  3592. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3593. else:
  3594. if self.defaults[dim]:
  3595. try:
  3596. val = float(self.defaults[dim]) * sfactor
  3597. except Exception as e:
  3598. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3599. continue
  3600. self.defaults[dim] = val
  3601. # The scaling factor depending on choice of units.
  3602. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3603. # Changing project units. Warn user.
  3604. msgbox = QtWidgets.QMessageBox()
  3605. msgbox.setWindowTitle(_("Toggle Units"))
  3606. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3607. msgbox.setText(_("Changing the units of the project\n"
  3608. "will scale all objects.\n\n"
  3609. "Do you want to continue?"))
  3610. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3611. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3612. msgbox.setDefaultButton(bt_ok)
  3613. msgbox.exec_()
  3614. response = msgbox.clickedButton()
  3615. if response == bt_ok:
  3616. if no_pref is False:
  3617. self.preferencesUiManager.defaults_read_form()
  3618. scale_defaults(factor)
  3619. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3620. self.defaults["units"] = new_units
  3621. # update the defaults from form, some may assume that the conversion is enough and it's not
  3622. self.on_options_app2project()
  3623. # update the objects
  3624. for obj in self.collection.get_list():
  3625. obj.convert_units(new_units)
  3626. # make that the properties stored in the object are also updated
  3627. self.object_changed.emit(obj)
  3628. # rebuild the object UI
  3629. obj.build_ui()
  3630. # change this only if the workspace is active
  3631. if self.defaults['global_workspace'] is True:
  3632. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3633. # adjust the grid values on the main toolbar
  3634. val_x = float(self.defaults['global_gridx']) * factor
  3635. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3636. current = self.collection.get_active()
  3637. if current is not None:
  3638. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3639. if not isinstance(current, GeometryObject):
  3640. current.to_form()
  3641. # replot all objects
  3642. self.plot_all()
  3643. # set the status labels to reflect the current FlatCAM units
  3644. self.set_screen_units(new_units)
  3645. # signal to the app that we changed the object properties and it shoud save the project
  3646. self.should_we_save = True
  3647. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3648. else:
  3649. # Undo toggling
  3650. self.toggle_units_ignore = True
  3651. if self.defaults['units'].upper() == 'MM':
  3652. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3653. else:
  3654. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3655. self.toggle_units_ignore = False
  3656. # store the grid values so they are not changed in the next step
  3657. val_x = float(self.defaults['global_gridx'])
  3658. val_y = float(self.defaults['global_gridy'])
  3659. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3660. self.preferencesUiManager.defaults_read_form()
  3661. # the self.preferencesUiManager.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  3662. # I don't want it for the grid values, so I update them here
  3663. self.defaults['global_gridx'] = val_x
  3664. self.defaults['global_gridy'] = val_y
  3665. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3666. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3667. def on_fullscreen(self, disable=False):
  3668. self.defaults.report_usage("on_fullscreen()")
  3669. flags = self.ui.windowFlags()
  3670. if self.toggle_fscreen is False and disable is False:
  3671. # self.ui.showFullScreen()
  3672. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3673. a = self.ui.geometry()
  3674. self.x_pos = a.x()
  3675. self.y_pos = a.y()
  3676. self.width = a.width()
  3677. self.height = a.height()
  3678. # set new geometry to full desktop rect
  3679. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3680. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3681. # everything else will not work without this hack. This happen in Windows.
  3682. # https://bugreports.qt.io/browse/QTBUG-41309
  3683. desktop = QtWidgets.QApplication.desktop()
  3684. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3685. rec = desktop.screenGeometry(screen)
  3686. x = rec.x() - 1
  3687. y = rec.y() - 1
  3688. h = rec.height() + 2
  3689. w = rec.width() + 2
  3690. self.ui.setGeometry(x, y, w, h)
  3691. self.ui.show()
  3692. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3693. tb.setVisible(False)
  3694. self.ui.splitter_left.setVisible(False)
  3695. self.toggle_fscreen = True
  3696. elif self.toggle_fscreen is True or disable is True:
  3697. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3698. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3699. self.ui.showNormal()
  3700. self.restore_toolbar_view()
  3701. self.ui.splitter_left.setVisible(True)
  3702. self.toggle_fscreen = False
  3703. def on_toggle_plotarea(self):
  3704. self.defaults.report_usage("on_toggle_plotarea()")
  3705. try:
  3706. name = self.ui.plot_tab_area.widget(0).objectName()
  3707. except AttributeError:
  3708. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3709. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3710. self.ui.plot_tab_area.protectTab(0)
  3711. return
  3712. if name != 'plotarea':
  3713. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3714. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3715. self.ui.plot_tab_area.protectTab(0)
  3716. else:
  3717. self.ui.plot_tab_area.closeTab(0)
  3718. def on_toggle_notebook(self):
  3719. if self.ui.splitter.sizes()[0] == 0:
  3720. self.ui.splitter.setSizes([1, 1])
  3721. self.ui.menu_toggle_nb.setChecked(True)
  3722. else:
  3723. self.ui.splitter.setSizes([0, 1])
  3724. self.ui.menu_toggle_nb.setChecked(False)
  3725. def on_toggle_axis(self):
  3726. self.defaults.report_usage("on_toggle_axis()")
  3727. if self.toggle_axis is False:
  3728. if self.is_legacy is False:
  3729. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3730. parent=self.plotcanvas.view.scene)
  3731. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3732. parent=self.plotcanvas.view.scene)
  3733. else:
  3734. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3735. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3736. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3737. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3738. self.plotcanvas.canvas.draw()
  3739. self.toggle_axis = True
  3740. else:
  3741. if self.is_legacy is False:
  3742. self.plotcanvas.v_line.parent = None
  3743. self.plotcanvas.h_line.parent = None
  3744. else:
  3745. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3746. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3747. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3748. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3749. self.plotcanvas.canvas.draw()
  3750. self.toggle_axis = False
  3751. def on_toggle_grid(self):
  3752. self.defaults.report_usage("on_toggle_grid()")
  3753. self.ui.grid_snap_btn.trigger()
  3754. self.on_grid_snap_triggered(state=True)
  3755. def on_toggle_grid_lines(self):
  3756. self.defaults.report_usage("on_toggle_grd_lines()")
  3757. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3758. if tt_settings.contains("theme"):
  3759. theme = tt_settings.value('theme', type=str)
  3760. else:
  3761. theme = 'white'
  3762. if self.toggle_grid_lines is False:
  3763. if self.is_legacy is False:
  3764. if theme == 'white':
  3765. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3766. else:
  3767. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3768. else:
  3769. self.plotcanvas.axes.grid(True)
  3770. try:
  3771. self.plotcanvas.canvas.draw()
  3772. except IndexError:
  3773. pass
  3774. pass
  3775. self.toggle_grid_lines = True
  3776. else:
  3777. if self.is_legacy is False:
  3778. if theme == 'white':
  3779. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3780. else:
  3781. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3782. else:
  3783. self.plotcanvas.axes.grid(False)
  3784. try:
  3785. self.plotcanvas.canvas.draw()
  3786. except IndexError:
  3787. pass
  3788. self.toggle_grid_lines = False
  3789. if self.is_legacy is False:
  3790. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3791. # - perhaps is a bug in VisPy implementation
  3792. if self.grid_status() is True:
  3793. self.app_cursor.enabled = False
  3794. self.app_cursor.enabled = True
  3795. else:
  3796. self.app_cursor.enabled = True
  3797. self.app_cursor.enabled = False
  3798. def on_update_exc_export(self, state):
  3799. """
  3800. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3801. if the update_excellon_cb checkbox is checked
  3802. :param state: state of the checkbox whose signals is tied to his slot
  3803. :return:
  3804. """
  3805. if state:
  3806. # first try to disconnect
  3807. try:
  3808. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3809. disconnect(self.on_excellon_format_changed)
  3810. except TypeError:
  3811. pass
  3812. try:
  3813. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3814. disconnect(self.on_excellon_format_changed)
  3815. except TypeError:
  3816. pass
  3817. try:
  3818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3819. disconnect(self.on_excellon_format_changed)
  3820. except TypeError:
  3821. pass
  3822. try:
  3823. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3824. disconnect(self.on_excellon_format_changed)
  3825. except TypeError:
  3826. pass
  3827. try:
  3828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3829. disconnect(self.on_excellon_zeros_changed)
  3830. except TypeError:
  3831. pass
  3832. try:
  3833. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3834. disconnect(self.on_excellon_zeros_changed)
  3835. except TypeError:
  3836. pass
  3837. # the connect them
  3838. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3839. self.on_excellon_format_changed)
  3840. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3841. self.on_excellon_format_changed)
  3842. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3843. self.on_excellon_format_changed)
  3844. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3845. self.on_excellon_format_changed)
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3847. self.on_excellon_zeros_changed)
  3848. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3849. self.on_excellon_units_changed)
  3850. else:
  3851. # disconnect the signals
  3852. try:
  3853. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3854. disconnect(self.on_excellon_format_changed)
  3855. except TypeError:
  3856. pass
  3857. try:
  3858. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3859. disconnect(self.on_excellon_format_changed)
  3860. except TypeError:
  3861. pass
  3862. try:
  3863. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3864. disconnect(self.on_excellon_format_changed)
  3865. except TypeError:
  3866. pass
  3867. try:
  3868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3869. disconnect(self.on_excellon_format_changed)
  3870. except TypeError:
  3871. pass
  3872. try:
  3873. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3874. disconnect(self.on_excellon_zeros_changed)
  3875. except TypeError:
  3876. pass
  3877. try:
  3878. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3879. disconnect(self.on_excellon_zeros_changed)
  3880. except TypeError:
  3881. pass
  3882. def on_excellon_format_changed(self):
  3883. """
  3884. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3885. :return: None
  3886. """
  3887. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3888. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3889. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3890. )
  3891. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3892. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3893. )
  3894. else:
  3895. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3897. )
  3898. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3899. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3900. )
  3901. def on_excellon_zeros_changed(self):
  3902. """
  3903. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3904. :return: None
  3905. """
  3906. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3907. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3908. )
  3909. def on_excellon_units_changed(self):
  3910. """
  3911. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3912. :return: None
  3913. """
  3914. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3915. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3916. )
  3917. self.on_excellon_format_changed()
  3918. def on_film_color_entry(self):
  3919. self.defaults['tools_film_color'] = \
  3920. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3921. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3922. "background-color:%s;"
  3923. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3924. )
  3925. def on_film_color_button(self):
  3926. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3927. c_dialog = QtWidgets.QColorDialog()
  3928. film_color = c_dialog.getColor(initial=current_color)
  3929. if film_color.isValid() is False:
  3930. return
  3931. # if new color is different then mark that the Preferences are changed
  3932. if film_color != current_color:
  3933. self.preferencesUiManager.on_preferences_edited()
  3934. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3935. "background-color:%s;"
  3936. "border-color: dimgray" % str(film_color.name())
  3937. )
  3938. new_val_sel = str(film_color.name())
  3939. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3940. self.defaults['tools_film_color'] = new_val_sel
  3941. def on_qrcode_fill_color_entry(self):
  3942. self.defaults['tools_qrcode_fill_color'] = \
  3943. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3944. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3945. "background-color:%s;"
  3946. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3947. )
  3948. def on_qrcode_fill_color_button(self):
  3949. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3950. c_dialog = QtWidgets.QColorDialog()
  3951. fill_color = c_dialog.getColor(initial=current_color)
  3952. if fill_color.isValid() is False:
  3953. return
  3954. # if new color is different then mark that the Preferences are changed
  3955. if fill_color != current_color:
  3956. self.preferencesUiManager.on_preferences_edited()
  3957. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3958. "background-color:%s;"
  3959. "border-color: dimgray" % str(fill_color.name())
  3960. )
  3961. new_val_sel = str(fill_color.name())
  3962. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3963. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3964. def on_qrcode_back_color_entry(self):
  3965. self.defaults['tools_qrcode_back_color'] = \
  3966. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3967. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3968. "background-color:%s;"
  3969. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3970. )
  3971. def on_qrcode_back_color_button(self):
  3972. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3973. c_dialog = QtWidgets.QColorDialog()
  3974. back_color = c_dialog.getColor(initial=current_color)
  3975. if back_color.isValid() is False:
  3976. return
  3977. # if new color is different then mark that the Preferences are changed
  3978. if back_color != current_color:
  3979. self.preferencesUiManager.on_preferences_edited()
  3980. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3981. "background-color:%s;"
  3982. "border-color: dimgray" % str(back_color.name())
  3983. )
  3984. new_val_sel = str(back_color.name())
  3985. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3986. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3987. def on_tab_rmb_click(self, checked):
  3988. self.ui.notebook.set_detachable(val=checked)
  3989. self.defaults["global_tabs_detachable"] = checked
  3990. self.ui.plot_tab_area.set_detachable(val=checked)
  3991. self.defaults["global_tabs_detachable"] = checked
  3992. def on_tab_setup_context_menu(self):
  3993. initial_checked = self.defaults["global_tabs_detachable"]
  3994. action_name = str(_("Detachable Tabs"))
  3995. action = QtWidgets.QAction(self)
  3996. action.setCheckable(True)
  3997. action.setText(action_name)
  3998. action.setChecked(initial_checked)
  3999. self.ui.notebook.tabBar.addAction(action)
  4000. self.ui.plot_tab_area.tabBar.addAction(action)
  4001. try:
  4002. action.triggered.disconnect()
  4003. except TypeError:
  4004. pass
  4005. action.triggered.connect(self.on_tab_rmb_click)
  4006. def on_deselect_all(self):
  4007. self.collection.set_all_inactive()
  4008. self.delete_selection_shape()
  4009. def on_workspace_modified(self):
  4010. # self.save_defaults(silent=True)
  4011. if self.is_legacy is True:
  4012. self.plotcanvas.delete_workspace()
  4013. self.preferencesUiManager.defaults_read_form()
  4014. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4015. def on_workspace(self):
  4016. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4017. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4018. else:
  4019. self.plotcanvas.delete_workspace()
  4020. self.preferencesUiManager.defaults_read_form()
  4021. # self.save_defaults(silent=True)
  4022. def on_workspace_toggle(self):
  4023. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4024. try:
  4025. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4026. except TypeError:
  4027. pass
  4028. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4029. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4030. self.on_workspace()
  4031. def on_cursor_type(self, val):
  4032. """
  4033. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4034. :return: None
  4035. """
  4036. self.app_cursor.enabled = False
  4037. if val == 'small':
  4038. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4039. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4040. self.app_cursor = self.plotcanvas.new_cursor()
  4041. else:
  4042. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4043. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4044. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4045. if self.ui.grid_snap_btn.isChecked():
  4046. self.app_cursor.enabled = True
  4047. else:
  4048. self.app_cursor.enabled = False
  4049. def on_tool_add_keypress(self):
  4050. # ## Current application units in Upper Case
  4051. self.units = self.defaults['units'].upper()
  4052. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4053. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4054. if notebook_widget_name == 'selected_tab':
  4055. if self.collection.get_active().kind == 'geometry':
  4056. # Tool add works for Geometry only if Advanced is True in Preferences
  4057. if self.defaults["global_app_level"] == 'a':
  4058. tool_add_popup = FCInputDialog(title="New Tool ...",
  4059. text='Enter a Tool Diameter:',
  4060. min=0.0000, max=99.9999, decimals=4)
  4061. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4062. val, ok = tool_add_popup.get_value()
  4063. if ok:
  4064. if float(val) == 0:
  4065. self.inform.emit('[WARNING_NOTCL] %s' %
  4066. _("Please enter a tool diameter with non-zero value, in Float format."))
  4067. return
  4068. self.collection.get_active().on_tool_add(dia=float(val))
  4069. else:
  4070. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4071. else:
  4072. msgbox = QtWidgets.QMessageBox()
  4073. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4074. "Go to Preferences -> General - Show Advanced Options."))
  4075. msgbox.setWindowTitle("Tool adding ...")
  4076. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4077. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4078. msgbox.setDefaultButton(bt_ok)
  4079. msgbox.exec_()
  4080. # work only if the notebook tab on focus is the Tools_Tab
  4081. if notebook_widget_name == 'tool_tab':
  4082. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4083. # and only if the tool is NCC Tool
  4084. if tool_widget == self.ncclear_tool.toolName:
  4085. self.ncclear_tool.on_add_tool_by_key()
  4086. # and only if the tool is Paint Area Tool
  4087. elif tool_widget == self.paint_tool.toolName:
  4088. self.paint_tool.on_add_tool_by_key()
  4089. # and only if the tool is Solder Paste Dispensing Tool
  4090. elif tool_widget == self.paste_tool.toolName:
  4091. self.paste_tool.on_add_tool_by_key()
  4092. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4093. # See description bellow.
  4094. def on_delete_keypress(self):
  4095. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4096. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4097. if notebook_widget_name == 'selected_tab':
  4098. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4099. self.collection.get_active().on_tool_delete()
  4100. # work only if the notebook tab on focus is the Tools_Tab
  4101. elif notebook_widget_name == 'tool_tab':
  4102. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4103. # and only if the tool is NCC Tool
  4104. if tool_widget == self.ncclear_tool.toolName:
  4105. self.ncclear_tool.on_tool_delete()
  4106. # and only if the tool is Paint Tool
  4107. elif tool_widget == self.paint_tool.toolName:
  4108. self.paint_tool.on_tool_delete()
  4109. # and only if the tool is Solder Paste Dispensing Tool
  4110. elif tool_widget == self.paste_tool.toolName:
  4111. self.paste_tool.on_tool_delete()
  4112. else:
  4113. self.on_delete()
  4114. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4115. # some screens you have to be careful where you hover with your mouse.
  4116. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4117. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4118. # Complicated, I know :)
  4119. def on_delete(self, force_deletion=False):
  4120. """
  4121. Delete the currently selected FlatCAMObjs.
  4122. :param force_deletion: used by Tcl command
  4123. :return: None
  4124. """
  4125. self.defaults.report_usage("on_delete()")
  4126. response = None
  4127. bt_ok = None
  4128. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4129. # a geometry object before we update it.
  4130. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4131. and self.grb_editor.editor_active is False:
  4132. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4133. msgbox = QtWidgets.QMessageBox()
  4134. msgbox.setWindowTitle(_("Delete objects"))
  4135. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4136. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4137. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4138. "the selected objects?"))
  4139. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4140. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4141. msgbox.setDefaultButton(bt_ok)
  4142. msgbox.exec_()
  4143. response = msgbox.clickedButton()
  4144. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4145. response = bt_ok
  4146. if response == bt_ok:
  4147. if self.collection.get_active():
  4148. self.log.debug("App.on_delete()")
  4149. for obj_active in self.collection.get_selected():
  4150. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4151. if isinstance(obj_active, GerberObject):
  4152. for el in obj_active.mark_shapes:
  4153. obj_active.mark_shapes[el].clear(update=True)
  4154. obj_active.mark_shapes[el].enabled = False
  4155. # obj_active.mark_shapes[el] = None
  4156. del el
  4157. elif isinstance(obj_active, CNCJobObject):
  4158. try:
  4159. obj_active.text_col.enabled = False
  4160. del obj_active.text_col
  4161. obj_active.annotation.clear(update=True)
  4162. del obj_active.annotation
  4163. except AttributeError as e:
  4164. log.debug(
  4165. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4166. )
  4167. while self.collection.get_selected():
  4168. self.delete_first_selected()
  4169. self.inform.emit('%s...' % _("Object(s) deleted"))
  4170. # make sure that the selection shape is deleted, too
  4171. self.delete_selection_shape()
  4172. else:
  4173. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4174. else:
  4175. self.inform.emit(_("Save the work in Editor and try again ..."))
  4176. def delete_first_selected(self):
  4177. # Keep this for later
  4178. try:
  4179. sel_obj = self.collection.get_active()
  4180. name = sel_obj.options["name"]
  4181. isPlotted = sel_obj.options["plot"]
  4182. except AttributeError:
  4183. self.log.debug("Nothing selected for deletion")
  4184. return
  4185. if self.is_legacy is True:
  4186. # Remove plot only if the object was plotted otherwise delaxes will fail
  4187. if isPlotted:
  4188. try:
  4189. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4190. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4191. except Exception as e:
  4192. log.debug("App.delete_first_selected() --> %s" % str(e))
  4193. self.plotcanvas.auto_adjust_axes()
  4194. # Remove from dictionary
  4195. self.collection.delete_active()
  4196. # Clear form
  4197. self.setup_component_editor()
  4198. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4199. def on_set_origin(self):
  4200. """
  4201. Set the origin to the left mouse click position
  4202. :return: None
  4203. """
  4204. # display the message for the user
  4205. # and ask him to click on the desired position
  4206. self.defaults.report_usage("on_set_origin()")
  4207. def origin_replot():
  4208. def worker_task():
  4209. with self.proc_container.new('%s...' % _("Plotting")):
  4210. for obj in self.collection.get_list():
  4211. obj.plot()
  4212. self.plotcanvas.fit_view()
  4213. if self.is_legacy:
  4214. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4215. else:
  4216. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4217. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4218. self.inform.emit(_('Click to set the origin ...'))
  4219. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4220. # first disconnect it as it may have been used by something else
  4221. try:
  4222. self.replot_signal.disconnect()
  4223. except TypeError:
  4224. pass
  4225. self.replot_signal[list].connect(origin_replot)
  4226. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4227. """
  4228. :param event:
  4229. :param location:
  4230. :param noplot:
  4231. :param use_thread:
  4232. :return:
  4233. """
  4234. noplot_sig = noplot
  4235. def worker_task():
  4236. with self.proc_container.new(_("Setting Origin...")):
  4237. obj_list = self.collection.get_list()
  4238. for obj in obj_list:
  4239. obj.offset((x, y))
  4240. self.object_changed.emit(obj)
  4241. # Update the object bounding box options
  4242. a, b, c, d = obj.bounds()
  4243. obj.options['xmin'] = a
  4244. obj.options['ymin'] = b
  4245. obj.options['xmax'] = c
  4246. obj.options['ymax'] = d
  4247. self.inform.emit('[success] %s...' % _('Origin set'))
  4248. for obj in obj_list:
  4249. out_name = obj.options["name"]
  4250. if obj.kind == 'gerber':
  4251. obj.source_file = self.export_gerber(
  4252. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4253. elif obj.kind == 'excellon':
  4254. obj.source_file = self.export_excellon(
  4255. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4256. if noplot_sig is False:
  4257. self.replot_signal.emit([])
  4258. if location is not None:
  4259. if len(location) != 2:
  4260. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4261. return 'fail'
  4262. x, y = location
  4263. if use_thread is True:
  4264. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4265. else:
  4266. worker_task()
  4267. self.should_we_save = True
  4268. return
  4269. if event.button == 1:
  4270. if self.is_legacy is False:
  4271. event_pos = event.pos
  4272. else:
  4273. event_pos = (event.xdata, event.ydata)
  4274. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4275. if self.grid_status():
  4276. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4277. else:
  4278. pos = pos_canvas
  4279. x = 0 - pos[0]
  4280. y = 0 - pos[1]
  4281. if use_thread is True:
  4282. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4283. else:
  4284. worker_task()
  4285. self.should_we_save = True
  4286. def on_move2origin(self, use_thread=True):
  4287. """
  4288. Move selected objects to origin.
  4289. :param use_thread: Control if to use threaded operation. Boolean.
  4290. :return:
  4291. """
  4292. def worker_task():
  4293. with self.proc_container.new(_("Moving to Origin...")):
  4294. obj_list = self.collection.get_selected()
  4295. if not obj_list:
  4296. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4297. return
  4298. xminlist = []
  4299. yminlist = []
  4300. # first get a bounding box to fit all
  4301. for obj in obj_list:
  4302. xmin, ymin, xmax, ymax = obj.bounds()
  4303. xminlist.append(xmin)
  4304. yminlist.append(ymin)
  4305. # get the minimum x,y for all objects selected
  4306. x = min(xminlist)
  4307. y = min(yminlist)
  4308. for obj in obj_list:
  4309. obj.offset((-x, -y))
  4310. self.object_changed.emit(obj)
  4311. # Update the object bounding box options
  4312. a, b, c, d = obj.bounds()
  4313. obj.options['xmin'] = a
  4314. obj.options['ymin'] = b
  4315. obj.options['xmax'] = c
  4316. obj.options['ymax'] = d
  4317. for obj in obj_list:
  4318. obj.plot()
  4319. for obj in obj_list:
  4320. out_name = obj.options["name"]
  4321. if obj.kind == 'gerber':
  4322. obj.source_file = self.export_gerber(
  4323. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4324. elif obj.kind == 'excellon':
  4325. obj.source_file = self.export_excellon(
  4326. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4327. self.inform.emit('[success] %s...' % _('Origin set'))
  4328. if use_thread is True:
  4329. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4330. else:
  4331. worker_task()
  4332. self.should_we_save = True
  4333. def on_jump_to(self, custom_location=None, fit_center=True):
  4334. """
  4335. Jump to a location by setting the mouse cursor location.
  4336. :param custom_location: Jump to a specified point. (x, y) tuple.
  4337. :param fit_center: If to fit view. Boolean.
  4338. :return:
  4339. """
  4340. self.defaults.report_usage("on_jump_to()")
  4341. if not custom_location:
  4342. dia_box_location = None
  4343. try:
  4344. dia_box_location = eval(self.clipboard.text())
  4345. except Exception:
  4346. pass
  4347. if type(dia_box_location) == tuple:
  4348. dia_box_location = str(dia_box_location)
  4349. else:
  4350. dia_box_location = None
  4351. # dia_box = Dialog_box(title=_("Jump to ..."),
  4352. # label=_("Enter the coordinates in format X,Y:"),
  4353. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4354. # initial_text=dia_box_location)
  4355. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4356. label=_("Enter the coordinates in format X,Y:"),
  4357. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4358. initial_text=dia_box_location,
  4359. reference=self.defaults['global_jump_ref'])
  4360. if dia_box.ok is True:
  4361. try:
  4362. location = eval(dia_box.location)
  4363. if not isinstance(location, tuple):
  4364. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4365. return
  4366. if dia_box.reference == 'rel':
  4367. rel_x = self.mouse[0] + location[0]
  4368. rel_y = self.mouse[1] + location[1]
  4369. location = (rel_x, rel_y)
  4370. self.defaults['global_jump_ref'] = dia_box.reference
  4371. except Exception:
  4372. return
  4373. else:
  4374. return
  4375. else:
  4376. location = custom_location
  4377. self.jump_signal.emit(location)
  4378. if fit_center:
  4379. self.plotcanvas.fit_center(loc=location)
  4380. cursor = QtGui.QCursor()
  4381. if self.is_legacy is False:
  4382. # I don't know where those differences come from but they are constant for the current
  4383. # execution of the application and they are multiples of a value around 0.0263mm.
  4384. # In a random way sometimes they are more sometimes they are less
  4385. # if units == 'MM':
  4386. # cal_factor = 0.0263
  4387. # else:
  4388. # cal_factor = 0.0263 / 25.4
  4389. cal_location = (location[0], location[1])
  4390. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4391. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4392. j_pos = (
  4393. int(canvas_origin.x() + round(jump_loc[0])),
  4394. int(canvas_origin.y() + round(jump_loc[1]))
  4395. )
  4396. cursor.setPos(j_pos[0], j_pos[1])
  4397. else:
  4398. # find the canvas origin which is in the top left corner
  4399. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4400. # determine the coordinates for the lowest left point of the canvas
  4401. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4402. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4403. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4404. # canvas) and the point (width, height) is in the top-right location
  4405. loc = self.plotcanvas.axes.transData.transform_point(location)
  4406. j_pos = (
  4407. int(x0 + loc[0]),
  4408. int(y0 - loc[1])
  4409. )
  4410. cursor.setPos(j_pos[0], j_pos[1])
  4411. self.plotcanvas.mouse = [location[0], location[1]]
  4412. if self.defaults["global_cursor_color_enabled"] is True:
  4413. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4414. else:
  4415. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4416. if self.grid_status():
  4417. # Update cursor
  4418. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4419. symbol='++', edge_color=self.cursor_color_3D,
  4420. edge_width=self.defaults["global_cursor_width"],
  4421. size=self.defaults["global_cursor_size"])
  4422. # Set the position label
  4423. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4424. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4425. # Set the relative position label
  4426. dx = location[0] - float(self.rel_point1[0])
  4427. dy = location[1] - float(self.rel_point1[1])
  4428. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4429. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4430. self.inform.emit('[success] %s' % _("Done."))
  4431. return location
  4432. def on_locate(self, obj, fit_center=True):
  4433. """
  4434. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4435. :param obj: The object on which to locate certain points
  4436. :param fit_center: If to fit view. Boolean.
  4437. :return: A point location. (x, y) tuple.
  4438. """
  4439. self.defaults.report_usage("on_locate()")
  4440. if obj is None:
  4441. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4442. return 'fail'
  4443. class DialogBoxChoice(QtWidgets.QDialog):
  4444. def __init__(self, title=None, icon=None, choice='bl'):
  4445. """
  4446. :param title: string with the window title
  4447. """
  4448. super(DialogBoxChoice, self).__init__()
  4449. self.ok = False
  4450. self.setWindowIcon(icon)
  4451. self.setWindowTitle(str(title))
  4452. self.form = QtWidgets.QFormLayout(self)
  4453. self.ref_radio = RadioSet([
  4454. {"label": _("Bottom-Left"), "value": "bl"},
  4455. {"label": _("Top-Left"), "value": "tl"},
  4456. {"label": _("Bottom-Right"), "value": "br"},
  4457. {"label": _("Top-Right"), "value": "tr"},
  4458. {"label": _("Center"), "value": "c"}
  4459. ], orientation='vertical', stretch=False)
  4460. self.ref_radio.set_value(choice)
  4461. self.form.addRow(self.ref_radio)
  4462. self.button_box = QtWidgets.QDialogButtonBox(
  4463. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4464. Qt.Horizontal, parent=self)
  4465. self.form.addRow(self.button_box)
  4466. self.button_box.accepted.connect(self.accept)
  4467. self.button_box.rejected.connect(self.reject)
  4468. if self.exec_() == QtWidgets.QDialog.Accepted:
  4469. self.ok = True
  4470. self.location_point = self.ref_radio.get_value()
  4471. else:
  4472. self.ok = False
  4473. self.location_point = None
  4474. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4475. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4476. choice=self.defaults['global_locate_pt'])
  4477. if dia_box.ok is True:
  4478. try:
  4479. location_point = dia_box.location_point
  4480. self.defaults['global_locate_pt'] = dia_box.location_point
  4481. except Exception:
  4482. return
  4483. else:
  4484. return
  4485. loc_b = obj.bounds()
  4486. if location_point == 'bl':
  4487. location = (loc_b[0], loc_b[1])
  4488. elif location_point == 'tl':
  4489. location = (loc_b[0], loc_b[3])
  4490. elif location_point == 'br':
  4491. location = (loc_b[2], loc_b[1])
  4492. elif location_point == 'tr':
  4493. location = (loc_b[2], loc_b[3])
  4494. else:
  4495. # center
  4496. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4497. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4498. location = (cx, cy)
  4499. self.locate_signal.emit(location, location_point)
  4500. if fit_center:
  4501. self.plotcanvas.fit_center(loc=location)
  4502. cursor = QtGui.QCursor()
  4503. if self.is_legacy is False:
  4504. # I don't know where those differences come from but they are constant for the current
  4505. # execution of the application and they are multiples of a value around 0.0263mm.
  4506. # In a random way sometimes they are more sometimes they are less
  4507. # if units == 'MM':
  4508. # cal_factor = 0.0263
  4509. # else:
  4510. # cal_factor = 0.0263 / 25.4
  4511. cal_location = (location[0], location[1])
  4512. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4513. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4514. j_pos = (
  4515. int(canvas_origin.x() + round(jump_loc[0])),
  4516. int(canvas_origin.y() + round(jump_loc[1]))
  4517. )
  4518. cursor.setPos(j_pos[0], j_pos[1])
  4519. else:
  4520. # find the canvas origin which is in the top left corner
  4521. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4522. # determine the coordinates for the lowest left point of the canvas
  4523. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4524. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4525. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4526. # canvas) and the point (width, height) is in the top-right location
  4527. loc = self.plotcanvas.axes.transData.transform_point(location)
  4528. j_pos = (
  4529. int(x0 + loc[0]),
  4530. int(y0 - loc[1])
  4531. )
  4532. cursor.setPos(j_pos[0], j_pos[1])
  4533. self.plotcanvas.mouse = [location[0], location[1]]
  4534. if self.defaults["global_cursor_color_enabled"] is True:
  4535. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4536. else:
  4537. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4538. if self.grid_status():
  4539. # Update cursor
  4540. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4541. symbol='++', edge_color=self.cursor_color_3D,
  4542. edge_width=self.defaults["global_cursor_width"],
  4543. size=self.defaults["global_cursor_size"])
  4544. # Set the position label
  4545. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4546. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4547. # Set the relative position label
  4548. self.dx = location[0] - float(self.rel_point1[0])
  4549. self.dy = location[1] - float(self.rel_point1[1])
  4550. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4551. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4552. self.inform.emit('[success] %s' % _("Done."))
  4553. return location
  4554. def on_copy_command(self):
  4555. """
  4556. Will copy a selection of objects, creating new objects.
  4557. :return:
  4558. """
  4559. self.defaults.report_usage("on_copy_command()")
  4560. def initialize(obj_init, app):
  4561. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4562. try:
  4563. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4564. except AttributeError:
  4565. pass
  4566. try:
  4567. obj_init.apertures = deepcopy(obj.apertures)
  4568. except AttributeError:
  4569. pass
  4570. try:
  4571. if obj.tools:
  4572. obj_init.tools = deepcopy(obj.tools)
  4573. except Exception as err:
  4574. log.debug("App.on_copy_command() --> %s" % str(err))
  4575. try:
  4576. obj_init.source_file = deepcopy(obj.source_file)
  4577. except (AttributeError, TypeError):
  4578. pass
  4579. def initialize_excellon(obj_init, app):
  4580. obj_init.source_file = deepcopy(obj.source_file)
  4581. obj_init.tools = deepcopy(obj.tools)
  4582. # drills are offset, so they need to be deep copied
  4583. obj_init.drills = deepcopy(obj.drills)
  4584. # slots are offset, so they need to be deep copied
  4585. obj_init.slots = deepcopy(obj.slots)
  4586. obj_init.create_geometry()
  4587. def initialize_script(obj_init, app_obj):
  4588. obj_init.source_file = deepcopy(obj.source_file)
  4589. def initialize_document(obj_init, app_obj):
  4590. obj_init.source_file = deepcopy(obj.source_file)
  4591. for obj in self.collection.get_selected():
  4592. obj_name = obj.options["name"]
  4593. try:
  4594. if isinstance(obj, ExcellonObject):
  4595. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4596. elif isinstance(obj, GerberObject):
  4597. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4598. elif isinstance(obj, GeometryObject):
  4599. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4600. elif isinstance(obj, ScriptObject):
  4601. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4602. elif isinstance(obj, DocumentObject):
  4603. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4604. except Exception as e:
  4605. return "Operation failed: %s" % str(e)
  4606. def on_copy_object2(self, custom_name):
  4607. def initialize_geometry(obj_init, app):
  4608. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4609. try:
  4610. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4611. except AttributeError:
  4612. pass
  4613. try:
  4614. obj_init.apertures = deepcopy(obj.apertures)
  4615. except AttributeError:
  4616. pass
  4617. try:
  4618. if obj.tools:
  4619. obj_init.tools = deepcopy(obj.tools)
  4620. except Exception as ee:
  4621. log.debug("on_copy_object2() --> %s" % str(ee))
  4622. def initialize_gerber(obj_init, app):
  4623. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4624. obj_init.apertures = deepcopy(obj.apertures)
  4625. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4626. def initialize_excellon(obj_init, app):
  4627. obj_init.tools = deepcopy(obj.tools)
  4628. # drills are offset, so they need to be deep copied
  4629. obj_init.drills = deepcopy(obj.drills)
  4630. # slots are offset, so they need to be deep copied
  4631. obj_init.slots = deepcopy(obj.slots)
  4632. obj_init.create_geometry()
  4633. for obj in self.collection.get_selected():
  4634. obj_name = obj.options["name"]
  4635. try:
  4636. if isinstance(obj, ExcellonObject):
  4637. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4638. elif isinstance(obj, GerberObject):
  4639. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4640. elif isinstance(obj, GeometryObject):
  4641. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4642. except Exception as er:
  4643. return "Operation failed: %s" % str(er)
  4644. def on_rename_object(self, text):
  4645. """
  4646. Will rename an object.
  4647. :param text: New name for the object.
  4648. :return:
  4649. """
  4650. self.defaults.report_usage("on_rename_object()")
  4651. named_obj = self.collection.get_active()
  4652. for obj in named_obj:
  4653. if obj is list:
  4654. self.on_rename_object(text)
  4655. else:
  4656. try:
  4657. obj.options['name'] = text
  4658. except Exception as e:
  4659. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4660. def convert_any2geo(self):
  4661. """
  4662. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4663. :return:
  4664. """
  4665. self.defaults.report_usage("convert_any2geo()")
  4666. def initialize(obj_init, app):
  4667. obj_init.solid_geometry = obj.solid_geometry
  4668. try:
  4669. obj_init.follow_geometry = obj.follow_geometry
  4670. except AttributeError:
  4671. pass
  4672. try:
  4673. obj_init.apertures = obj.apertures
  4674. except AttributeError:
  4675. pass
  4676. try:
  4677. if obj.tools:
  4678. obj_init.tools = obj.tools
  4679. except AttributeError:
  4680. pass
  4681. def initialize_excellon(obj_init, app):
  4682. # objs = self.collection.get_selected()
  4683. # GeometryObject.merge(objs, obj)
  4684. solid_geo = []
  4685. for tool in obj.tools:
  4686. for geo in obj.tools[tool]['solid_geometry']:
  4687. solid_geo.append(geo)
  4688. obj_init.solid_geometry = deepcopy(solid_geo)
  4689. if not self.collection.get_selected():
  4690. log.warning("App.convert_any2geo --> No object selected")
  4691. self.inform.emit('[WARNING_NOTCL] %s' %
  4692. _("No object is selected. Select an object and try again."))
  4693. return
  4694. for obj in self.collection.get_selected():
  4695. obj_name = obj.options["name"]
  4696. try:
  4697. if isinstance(obj, ExcellonObject):
  4698. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4699. else:
  4700. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4701. except Exception as e:
  4702. return "Operation failed: %s" % str(e)
  4703. def convert_any2gerber(self):
  4704. """
  4705. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4706. :return:
  4707. """
  4708. self.defaults.report_usage("convert_any2gerber()")
  4709. def initialize_geometry(obj_init, app):
  4710. apertures = {}
  4711. apid = 0
  4712. apertures[str(apid)] = {}
  4713. apertures[str(apid)]['geometry'] = []
  4714. for obj_orig in obj.solid_geometry:
  4715. new_elem = {}
  4716. new_elem['solid'] = obj_orig
  4717. try:
  4718. new_elem['follow'] = obj_orig.exterior
  4719. except AttributeError:
  4720. pass
  4721. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4722. apertures[str(apid)]['size'] = 0.0
  4723. apertures[str(apid)]['type'] = 'C'
  4724. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4725. obj_init.apertures = deepcopy(apertures)
  4726. def initialize_excellon(obj_init, app):
  4727. apertures = {}
  4728. apid = 10
  4729. for tool in obj.tools:
  4730. apertures[str(apid)] = {}
  4731. apertures[str(apid)]['geometry'] = []
  4732. for geo in obj.tools[tool]['solid_geometry']:
  4733. new_el = {}
  4734. new_el['solid'] = geo
  4735. new_el['follow'] = geo.exterior
  4736. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4737. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4738. apertures[str(apid)]['type'] = 'C'
  4739. apid += 1
  4740. # create solid_geometry
  4741. solid_geometry = []
  4742. for apid in apertures:
  4743. for geo_el in apertures[apid]['geometry']:
  4744. solid_geometry.append(geo_el['solid'])
  4745. solid_geometry = MultiPolygon(solid_geometry)
  4746. solid_geometry = solid_geometry.buffer(0.0000001)
  4747. obj_init.solid_geometry = deepcopy(solid_geometry)
  4748. obj_init.apertures = deepcopy(apertures)
  4749. # clear the working objects (perhaps not necessary due of Python GC)
  4750. apertures.clear()
  4751. if not self.collection.get_selected():
  4752. log.warning("App.convert_any2gerber --> No object selected")
  4753. self.inform.emit('[WARNING_NOTCL] %s' %
  4754. _("No object is selected. Select an object and try again."))
  4755. return
  4756. for obj in self.collection.get_selected():
  4757. obj_name = obj.options["name"]
  4758. try:
  4759. if isinstance(obj, ExcellonObject):
  4760. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4761. elif isinstance(obj, GeometryObject):
  4762. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4763. else:
  4764. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4765. except Exception as e:
  4766. return "Operation failed: %s" % str(e)
  4767. def abort_all_tasks(self):
  4768. """
  4769. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4770. on the first possible occasion.
  4771. :return:
  4772. """
  4773. if self.abort_flag is False:
  4774. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4775. self.abort_flag = True
  4776. self.cleanup.emit()
  4777. def app_is_idle(self):
  4778. if self.abort_flag:
  4779. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4780. self.abort_flag = False
  4781. def on_selectall(self):
  4782. """
  4783. Will draw a selection box shape around the selected objects.
  4784. :return:
  4785. """
  4786. self.defaults.report_usage("on_selectall()")
  4787. # delete the possible selection box around a possible selected object
  4788. self.delete_selection_shape()
  4789. for name in self.collection.get_names():
  4790. self.collection.set_active(name)
  4791. curr_sel_obj = self.collection.get_by_name(name)
  4792. # create the selection box around the selected object
  4793. if self.defaults['global_selection_shape'] is True:
  4794. self.draw_selection_shape(curr_sel_obj)
  4795. def on_preferences(self):
  4796. """
  4797. Adds the Preferences in a Tab in Plot Area
  4798. :return:
  4799. """
  4800. # add the tab if it was closed
  4801. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4802. # delete the absolute and relative position and messages in the infobar
  4803. self.ui.position_label.setText("")
  4804. self.ui.rel_position_label.setText("")
  4805. # Switch plot_area to preferences page
  4806. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4807. # self.ui.show()
  4808. # detect changes in the preferences
  4809. for idx in range(self.ui.pref_tab_area.count()):
  4810. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4811. try:
  4812. try:
  4813. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4814. except (TypeError, AttributeError):
  4815. pass
  4816. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4817. except AttributeError:
  4818. pass
  4819. try:
  4820. try:
  4821. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4822. except (TypeError, AttributeError):
  4823. pass
  4824. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4825. except AttributeError:
  4826. pass
  4827. try:
  4828. try:
  4829. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4830. except (TypeError, AttributeError):
  4831. pass
  4832. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4833. except AttributeError:
  4834. pass
  4835. try:
  4836. try:
  4837. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4838. except (TypeError, AttributeError):
  4839. pass
  4840. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4841. except AttributeError:
  4842. pass
  4843. try:
  4844. try:
  4845. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4846. except (TypeError, AttributeError):
  4847. pass
  4848. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4849. except AttributeError:
  4850. pass
  4851. def on_tools_database(self, source='app'):
  4852. """
  4853. Adds the Tools Database in a Tab in Plot Area.
  4854. :return:
  4855. """
  4856. for idx in range(self.ui.plot_tab_area.count()):
  4857. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4858. # there can be only one instance of Tools Database at one time
  4859. return
  4860. if source == 'app':
  4861. self.tools_db_tab = ToolsDB2(
  4862. app=self,
  4863. parent=self.ui,
  4864. callback_on_edited=self.on_tools_db_edited,
  4865. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4866. )
  4867. elif source == 'ncc':
  4868. self.tools_db_tab = ToolsDB2(
  4869. app=self,
  4870. parent=self.ui,
  4871. callback_on_edited=self.on_tools_db_edited,
  4872. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4873. )
  4874. elif source == 'paint':
  4875. self.tools_db_tab = ToolsDB2(
  4876. app=self,
  4877. parent=self.ui,
  4878. callback_on_edited=self.on_tools_db_edited,
  4879. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4880. )
  4881. # add the tab if it was closed
  4882. try:
  4883. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4884. self.tools_db_tab.setObjectName("database_tab")
  4885. except Exception as e:
  4886. log.debug("App.on_tools_database() --> %s" % str(e))
  4887. return
  4888. # delete the absolute and relative position and messages in the infobar
  4889. self.ui.position_label.setText("")
  4890. self.ui.rel_position_label.setText("")
  4891. # Switch plot_area to preferences page
  4892. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4893. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4894. self.tools_db_tab.ui_connect()
  4895. def on_tools_db_edited(self):
  4896. """
  4897. Executed whenever a tool is edited in Tools Database.
  4898. Will color the text of the Tools Database tab to Red color.
  4899. :return:
  4900. """
  4901. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4902. for idx in range(self.ui.plot_tab_area.count()):
  4903. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4904. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4905. self.tools_db_changed_flag = True
  4906. def on_geometry_tool_add_from_db_executed(self, tool):
  4907. """
  4908. Here add the tool from DB in the selected geometry object.
  4909. :return:
  4910. """
  4911. tool_from_db = deepcopy(tool)
  4912. obj = self.collection.get_active()
  4913. if isinstance(obj, GeometryObject):
  4914. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4915. # close the tab and delete it
  4916. for idx in range(self.ui.plot_tab_area.count()):
  4917. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4918. wdg = self.ui.plot_tab_area.widget(idx)
  4919. wdg.deleteLater()
  4920. self.ui.plot_tab_area.removeTab(idx)
  4921. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4922. else:
  4923. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4924. def on_plot_area_tab_closed(self, title):
  4925. """
  4926. Executed whenever a tab is closed in the Plot Area.
  4927. :param title: The name of the tab that was closed.
  4928. :return:
  4929. """
  4930. # FIXME: doing this based on translated title doesn't seem very robust.
  4931. if title == _("Preferences"):
  4932. self.uiPreferencesManager.on_close_preferences_tab()
  4933. if title == _("Tools Database"):
  4934. # disconnect the signals from the table widget in tab
  4935. self.tools_db_tab.ui_disconnect()
  4936. if self.tools_db_changed_flag is True:
  4937. msgbox = QtWidgets.QMessageBox()
  4938. msgbox.setText(_("One or more Tools are edited.\n"
  4939. "Do you want to update the Tools Database?"))
  4940. msgbox.setWindowTitle(_("Save Tools Database"))
  4941. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4942. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4943. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4944. msgbox.setDefaultButton(bt_yes)
  4945. msgbox.exec_()
  4946. response = msgbox.clickedButton()
  4947. if response == bt_yes:
  4948. self.tools_db_tab.on_save_tools_db()
  4949. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4950. else:
  4951. self.tools_db_changed_flag = False
  4952. self.inform.emit('')
  4953. return
  4954. self.tools_db_tab.deleteLater()
  4955. if title == _("Code Editor"):
  4956. self.toggle_codeeditor = False
  4957. if title == _("Bookmarks Manager"):
  4958. self.book_dialog_tab.rebuild_actions()
  4959. self.book_dialog_tab.deleteLater()
  4960. def on_flipy(self):
  4961. """
  4962. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4963. :return:
  4964. """
  4965. self.defaults.report_usage("on_flipy()")
  4966. obj_list = self.collection.get_selected()
  4967. xminlist = []
  4968. yminlist = []
  4969. xmaxlist = []
  4970. ymaxlist = []
  4971. if not obj_list:
  4972. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4973. else:
  4974. try:
  4975. # first get a bounding box to fit all
  4976. for obj in obj_list:
  4977. xmin, ymin, xmax, ymax = obj.bounds()
  4978. xminlist.append(xmin)
  4979. yminlist.append(ymin)
  4980. xmaxlist.append(xmax)
  4981. ymaxlist.append(ymax)
  4982. # get the minimum x,y and maximum x,y for all objects selected
  4983. xminimal = min(xminlist)
  4984. yminimal = min(yminlist)
  4985. xmaximal = max(xmaxlist)
  4986. ymaximal = max(ymaxlist)
  4987. px = 0.5 * (xminimal + xmaximal)
  4988. py = 0.5 * (yminimal + ymaximal)
  4989. # execute mirroring
  4990. for obj in obj_list:
  4991. obj.mirror('X', [px, py])
  4992. obj.plot()
  4993. self.object_changed.emit(obj)
  4994. self.inform.emit('[success] %s' %
  4995. _("Flip on Y axis done."))
  4996. except Exception as e:
  4997. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4998. return
  4999. def on_flipx(self):
  5000. """
  5001. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5002. :return:
  5003. """
  5004. self.defaults.report_usage("on_flipx()")
  5005. obj_list = self.collection.get_selected()
  5006. xminlist = []
  5007. yminlist = []
  5008. xmaxlist = []
  5009. ymaxlist = []
  5010. if not obj_list:
  5011. self.inform.emit('[WARNING_NOTCL] %s' %
  5012. _("No object selected to Flip on X axis."))
  5013. else:
  5014. try:
  5015. # first get a bounding box to fit all
  5016. for obj in obj_list:
  5017. xmin, ymin, xmax, ymax = obj.bounds()
  5018. xminlist.append(xmin)
  5019. yminlist.append(ymin)
  5020. xmaxlist.append(xmax)
  5021. ymaxlist.append(ymax)
  5022. # get the minimum x,y and maximum x,y for all objects selected
  5023. xminimal = min(xminlist)
  5024. yminimal = min(yminlist)
  5025. xmaximal = max(xmaxlist)
  5026. ymaximal = max(ymaxlist)
  5027. px = 0.5 * (xminimal + xmaximal)
  5028. py = 0.5 * (yminimal + ymaximal)
  5029. # execute mirroring
  5030. for obj in obj_list:
  5031. obj.mirror('Y', [px, py])
  5032. obj.plot()
  5033. self.object_changed.emit(obj)
  5034. self.inform.emit('[success] %s' %
  5035. _("Flip on X axis done."))
  5036. except Exception as e:
  5037. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5038. return
  5039. def on_rotate(self, silent=False, preset=None):
  5040. """
  5041. Executed when Options -> Rotate Selection menu entry is clicked.
  5042. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5043. :param preset: A value to be used as predefined angle for rotation.
  5044. :return:
  5045. """
  5046. self.defaults.report_usage("on_rotate()")
  5047. obj_list = self.collection.get_selected()
  5048. xminlist = []
  5049. yminlist = []
  5050. xmaxlist = []
  5051. ymaxlist = []
  5052. if not obj_list:
  5053. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5054. else:
  5055. if silent is False:
  5056. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5057. min=-360, max=360, decimals=4,
  5058. init_val=float(self.defaults['tools_transform_rotate']))
  5059. num, ok = rotatebox.get_value()
  5060. else:
  5061. num = preset
  5062. ok = True
  5063. if ok:
  5064. try:
  5065. # first get a bounding box to fit all
  5066. for obj in obj_list:
  5067. xmin, ymin, xmax, ymax = obj.bounds()
  5068. xminlist.append(xmin)
  5069. yminlist.append(ymin)
  5070. xmaxlist.append(xmax)
  5071. ymaxlist.append(ymax)
  5072. # get the minimum x,y and maximum x,y for all objects selected
  5073. xminimal = min(xminlist)
  5074. yminimal = min(yminlist)
  5075. xmaximal = max(xmaxlist)
  5076. ymaximal = max(ymaxlist)
  5077. px = 0.5 * (xminimal + xmaximal)
  5078. py = 0.5 * (yminimal + ymaximal)
  5079. for sel_obj in obj_list:
  5080. sel_obj.rotate(-float(num), point=(px, py))
  5081. sel_obj.plot()
  5082. self.object_changed.emit(sel_obj)
  5083. self.inform.emit('[success] %s' %
  5084. _("Rotation done."))
  5085. except Exception as e:
  5086. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5087. return
  5088. def on_skewx(self):
  5089. """
  5090. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5091. :return:
  5092. """
  5093. self.defaults.report_usage("on_skewx()")
  5094. obj_list = self.collection.get_selected()
  5095. xminlist = []
  5096. yminlist = []
  5097. if not obj_list:
  5098. self.inform.emit('[WARNING_NOTCL] %s' %
  5099. _("No object selected to Skew/Shear on X axis."))
  5100. else:
  5101. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5102. min=-360, max=360, decimals=4,
  5103. init_val=float(self.defaults['tools_transform_skew_x']))
  5104. num, ok = skewxbox.get_value()
  5105. if ok:
  5106. # first get a bounding box to fit all
  5107. for obj in obj_list:
  5108. xmin, ymin, xmax, ymax = obj.bounds()
  5109. xminlist.append(xmin)
  5110. yminlist.append(ymin)
  5111. # get the minimum x,y and maximum x,y for all objects selected
  5112. xminimal = min(xminlist)
  5113. yminimal = min(yminlist)
  5114. for obj in obj_list:
  5115. obj.skew(num, 0, point=(xminimal, yminimal))
  5116. obj.plot()
  5117. self.object_changed.emit(obj)
  5118. self.inform.emit('[success] %s' %
  5119. _("Skew on X axis done."))
  5120. def on_skewy(self):
  5121. """
  5122. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5123. :return:
  5124. """
  5125. self.defaults.report_usage("on_skewy()")
  5126. obj_list = self.collection.get_selected()
  5127. xminlist = []
  5128. yminlist = []
  5129. if not obj_list:
  5130. self.inform.emit('[WARNING_NOTCL] %s' %
  5131. _("No object selected to Skew/Shear on Y axis."))
  5132. else:
  5133. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5134. min=-360, max=360, decimals=4,
  5135. init_val=float(self.defaults['tools_transform_skew_y']))
  5136. num, ok = skewybox.get_value()
  5137. if ok:
  5138. # first get a bounding box to fit all
  5139. for obj in obj_list:
  5140. xmin, ymin, xmax, ymax = obj.bounds()
  5141. xminlist.append(xmin)
  5142. yminlist.append(ymin)
  5143. # get the minimum x,y and maximum x,y for all objects selected
  5144. xminimal = min(xminlist)
  5145. yminimal = min(yminlist)
  5146. for obj in obj_list:
  5147. obj.skew(0, num, point=(xminimal, yminimal))
  5148. obj.plot()
  5149. self.object_changed.emit(obj)
  5150. self.inform.emit('[success] %s' %
  5151. _("Skew on Y axis done."))
  5152. def on_plots_updated(self):
  5153. """
  5154. Callback used to report when the plots have changed.
  5155. Adjust axes and zooms to fit.
  5156. :return: None
  5157. """
  5158. if self.is_legacy is False:
  5159. self.plotcanvas.update()
  5160. else:
  5161. self.plotcanvas.auto_adjust_axes()
  5162. self.on_zoom_fit(None)
  5163. self.collection.update_view()
  5164. # self.inform.emit(_("Plots updated ..."))
  5165. def on_toolbar_replot(self):
  5166. """
  5167. Callback for toolbar button. Re-plots all objects.
  5168. :return: None
  5169. """
  5170. self.defaults.report_usage("on_toolbar_replot")
  5171. self.log.debug("on_toolbar_replot()")
  5172. try:
  5173. self.collection.get_active().read_form()
  5174. except AttributeError:
  5175. self.log.debug("on_toolbar_replot(): AttributeError")
  5176. pass
  5177. self.plot_all()
  5178. def on_row_activated(self, index):
  5179. if index.isValid():
  5180. if index.internalPointer().parent_item != self.collection.root_item:
  5181. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5182. self.collection.on_item_activated(index)
  5183. def on_row_selected(self, obj_name):
  5184. """
  5185. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5186. It mean we clicked outside of the items and deselected all
  5187. :param obj_name:
  5188. :return:
  5189. """
  5190. if obj_name == 'none':
  5191. for act in self.ui.menuobjects.actions():
  5192. act.setChecked(False)
  5193. return
  5194. # get the name of the selected objects and add them to a list
  5195. name_list = []
  5196. for obj in self.collection.get_selected():
  5197. name_list.append(obj.options['name'])
  5198. # set all actions as unchecked but the ones selected make them checked
  5199. for act in self.ui.menuobjects.actions():
  5200. act.setChecked(False)
  5201. if act.text() in name_list:
  5202. act.setChecked(True)
  5203. def on_collection_updated(self, obj, state, old_name):
  5204. """
  5205. Create a menu from the object loaded in the collection.
  5206. :param obj: object that was changed (added, deleted, renamed)
  5207. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5208. :param old_name: the old name of the object before the action that triggered this slot happened
  5209. :return: None
  5210. """
  5211. icon_files = {
  5212. "gerber": self.resource_location + "/flatcam_icon16.png",
  5213. "excellon": self.resource_location + "/drill16.png",
  5214. "cncjob": self.resource_location + "/cnc16.png",
  5215. "geometry": self.resource_location + "/geometry16.png",
  5216. "script": self.resource_location + "/script_new16.png",
  5217. "document": self.resource_location + "/notes16_1.png"
  5218. }
  5219. if state == 'append':
  5220. for act in self.ui.menuobjects.actions():
  5221. try:
  5222. act.triggered.disconnect()
  5223. except TypeError:
  5224. pass
  5225. self.ui.menuobjects.clear()
  5226. gerber_list = []
  5227. exc_list = []
  5228. cncjob_list = []
  5229. geo_list = []
  5230. script_list = []
  5231. doc_list = []
  5232. for name in self.collection.get_names():
  5233. obj_named = self.collection.get_by_name(name)
  5234. if obj_named.kind == 'gerber':
  5235. gerber_list.append(name)
  5236. elif obj_named.kind == 'excellon':
  5237. exc_list.append(name)
  5238. elif obj_named.kind == 'cncjob':
  5239. cncjob_list.append(name)
  5240. elif obj_named.kind == 'geometry':
  5241. geo_list.append(name)
  5242. elif obj_named.kind == 'script':
  5243. script_list.append(name)
  5244. elif obj_named.kind == 'document':
  5245. doc_list.append(name)
  5246. def add_act(o_name):
  5247. obj_for_icon = self.collection.get_by_name(o_name)
  5248. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5249. add_action.setCheckable(True)
  5250. add_action.setText(o_name)
  5251. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5252. add_action.triggered.connect(
  5253. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5254. self.collection.set_inactive(o_name))
  5255. self.ui.menuobjects.addAction(add_action)
  5256. for name in gerber_list:
  5257. add_act(name)
  5258. self.ui.menuobjects.addSeparator()
  5259. for name in exc_list:
  5260. add_act(name)
  5261. self.ui.menuobjects.addSeparator()
  5262. for name in cncjob_list:
  5263. add_act(name)
  5264. self.ui.menuobjects.addSeparator()
  5265. for name in geo_list:
  5266. add_act(name)
  5267. self.ui.menuobjects.addSeparator()
  5268. for name in script_list:
  5269. add_act(name)
  5270. self.ui.menuobjects.addSeparator()
  5271. for name in doc_list:
  5272. add_act(name)
  5273. self.ui.menuobjects.addSeparator()
  5274. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5275. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5276. _('Select All')
  5277. )
  5278. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5279. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5280. _('Deselect All')
  5281. )
  5282. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5283. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5284. elif state == 'delete':
  5285. for act in self.ui.menuobjects.actions():
  5286. if act.text() == obj.options['name']:
  5287. try:
  5288. act.triggered.disconnect()
  5289. except TypeError:
  5290. pass
  5291. self.ui.menuobjects.removeAction(act)
  5292. break
  5293. elif state == 'rename':
  5294. for act in self.ui.menuobjects.actions():
  5295. if act.text() == old_name:
  5296. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5297. add_action.setText(obj.options['name'])
  5298. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5299. add_action.triggered.connect(
  5300. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5301. self.collection.set_inactive(obj.options['name']))
  5302. self.ui.menuobjects.insertAction(act, add_action)
  5303. try:
  5304. act.triggered.disconnect()
  5305. except TypeError:
  5306. pass
  5307. self.ui.menuobjects.removeAction(act)
  5308. break
  5309. elif state == 'delete_all':
  5310. for act in self.ui.menuobjects.actions():
  5311. try:
  5312. act.triggered.disconnect()
  5313. except TypeError:
  5314. pass
  5315. self.ui.menuobjects.clear()
  5316. self.ui.menuobjects.addSeparator()
  5317. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5318. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5319. _('Select All')
  5320. )
  5321. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5322. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5323. _('Deselect All')
  5324. )
  5325. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5326. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5327. def on_objects_selection(self, on_off):
  5328. obj_list = self.collection.get_names()
  5329. if on_off is True:
  5330. self.collection.set_all_active()
  5331. for act in self.ui.menuobjects.actions():
  5332. try:
  5333. act.setChecked(True)
  5334. except Exception:
  5335. pass
  5336. if obj_list:
  5337. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5338. else:
  5339. self.collection.set_all_inactive()
  5340. for act in self.ui.menuobjects.actions():
  5341. try:
  5342. act.setChecked(False)
  5343. except Exception:
  5344. pass
  5345. if obj_list:
  5346. self.inform.emit('%s' % _("Objects selection is cleared."))
  5347. else:
  5348. self.inform.emit('')
  5349. def grid_status(self):
  5350. if self.ui.grid_snap_btn.isChecked():
  5351. return True
  5352. else:
  5353. return False
  5354. def populate_cmenu_grids(self):
  5355. units = self.defaults['units'].lower()
  5356. # for act in self.ui.cmenu_gridmenu.actions():
  5357. # act.triggered.disconnect()
  5358. self.ui.cmenu_gridmenu.clear()
  5359. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5360. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5361. _("Grid On/Off"))
  5362. grid_toggle.setCheckable(True)
  5363. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5364. self.ui.cmenu_gridmenu.addSeparator()
  5365. for grid in sorted_list:
  5366. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5367. "%s" % str(grid))
  5368. action.triggered.connect(self.set_grid)
  5369. self.ui.cmenu_gridmenu.addSeparator()
  5370. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5371. _("Add"))
  5372. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5373. _("Delete"))
  5374. grid_add.triggered.connect(self.on_grid_add)
  5375. grid_delete.triggered.connect(self.on_grid_delete)
  5376. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5377. def set_grid(self):
  5378. menu_action = self.sender()
  5379. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5380. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5381. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5382. def on_grid_add(self):
  5383. # ## Current application units in lower Case
  5384. units = self.defaults['units'].lower()
  5385. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5386. text=_('Enter a Grid Value:'),
  5387. min=0.0000, max=99.9999, decimals=4)
  5388. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5389. val, ok = grid_add_popup.get_value()
  5390. if ok:
  5391. if float(val) == 0:
  5392. self.inform.emit('[WARNING_NOTCL] %s' %
  5393. _("Please enter a grid value with non-zero value, in Float format."))
  5394. return
  5395. else:
  5396. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5397. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5398. self.inform.emit('[success] %s...' %
  5399. _("New Grid added"))
  5400. else:
  5401. self.inform.emit('[WARNING_NOTCL] %s...' %
  5402. _("Grid already exists"))
  5403. else:
  5404. self.inform.emit('[WARNING_NOTCL] %s...' %
  5405. _("Adding New Grid cancelled"))
  5406. def on_grid_delete(self):
  5407. # ## Current application units in lower Case
  5408. units = self.defaults['units'].lower()
  5409. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5410. text='Enter a Grid Value:',
  5411. min=0.0000, max=99.9999, decimals=4)
  5412. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5413. val, ok = grid_del_popup.get_value()
  5414. if ok:
  5415. if float(val) == 0:
  5416. self.inform.emit('[WARNING_NOTCL] %s' %
  5417. _("Please enter a grid value with non-zero value, in Float format."))
  5418. return
  5419. else:
  5420. try:
  5421. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5422. except ValueError:
  5423. self.inform.emit('[ERROR_NOTCL]%s...' %
  5424. _(" Grid Value does not exist"))
  5425. return
  5426. self.inform.emit('[success] %s...' %
  5427. _("Grid Value deleted"))
  5428. else:
  5429. self.inform.emit('[WARNING_NOTCL] %s...' %
  5430. _("Delete Grid value cancelled"))
  5431. def on_shortcut_list(self):
  5432. self.defaults.report_usage("on_shortcut_list()")
  5433. # add the tab if it was closed
  5434. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5435. # delete the absolute and relative position and messages in the infobar
  5436. self.ui.position_label.setText("")
  5437. self.ui.rel_position_label.setText("")
  5438. # Switch plot_area to preferences page
  5439. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5440. # self.ui.show()
  5441. def on_select_tab(self, name):
  5442. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5443. if self.ui.splitter.sizes()[0] == 0:
  5444. self.ui.splitter.setSizes([1, 1])
  5445. else:
  5446. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5447. self.ui.splitter.setSizes([0, 1])
  5448. if name == 'project':
  5449. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5450. elif name == 'selected':
  5451. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5452. elif name == 'tool':
  5453. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5454. def on_copy_name(self):
  5455. self.defaults.report_usage("on_copy_name()")
  5456. obj = self.collection.get_active()
  5457. try:
  5458. name = obj.options["name"]
  5459. except AttributeError:
  5460. log.debug("on_copy_name() --> No object selected to copy it's name")
  5461. self.inform.emit('[WARNING_NOTCL]%s' %
  5462. _(" No object selected to copy it's name"))
  5463. return
  5464. self.clipboard.setText(name)
  5465. self.inform.emit(_("Name copied on clipboard ..."))
  5466. def on_mouse_click_over_plot(self, event):
  5467. """
  5468. Default actions are:
  5469. :param event: Contains information about the event, like which button
  5470. was clicked, the pixel coordinates and the axes coordinates.
  5471. :return: None
  5472. """
  5473. self.pos = []
  5474. if self.is_legacy is False:
  5475. event_pos = event.pos
  5476. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5477. # # Set the mouse button for panning
  5478. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5479. else:
  5480. event_pos = (event.xdata, event.ydata)
  5481. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5482. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5483. # So it can receive key presses
  5484. self.plotcanvas.native.setFocus()
  5485. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5486. if self.grid_status():
  5487. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5488. else:
  5489. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5490. try:
  5491. if event.button == 1:
  5492. # Reset here the relative coordinates so there is a new reference on the click position
  5493. if self.rel_point1 is None:
  5494. self.rel_point1 = self.pos
  5495. else:
  5496. self.rel_point2 = copy(self.rel_point1)
  5497. self.rel_point1 = self.pos
  5498. self.on_mouse_move_over_plot(event, origin_click=True)
  5499. except Exception as e:
  5500. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5501. def on_mouse_double_click_over_plot(self, event):
  5502. if event.button == 1:
  5503. self.doubleclick = True
  5504. def on_mouse_move_over_plot(self, event, origin_click=None):
  5505. """
  5506. Callback for the mouse motion event over the plot.
  5507. :param event: Contains information about the event.
  5508. :param origin_click
  5509. :return: None
  5510. """
  5511. if self.is_legacy is False:
  5512. event_pos = event.pos
  5513. if self.defaults["global_pan_button"] == '2':
  5514. pan_button = 2
  5515. else:
  5516. pan_button = 3
  5517. self.event_is_dragging = event.is_dragging
  5518. else:
  5519. event_pos = (event.xdata, event.ydata)
  5520. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5521. if self.defaults["global_pan_button"] == '2':
  5522. pan_button = 3
  5523. else:
  5524. pan_button = 2
  5525. self.event_is_dragging = self.plotcanvas.is_dragging
  5526. # So it can receive key presses but not when the Tcl Shell is active
  5527. if not self.ui.shell_dock.isVisible():
  5528. if not self.plotcanvas.native.hasFocus():
  5529. self.plotcanvas.native.setFocus()
  5530. self.pos_jump = event_pos
  5531. self.ui.popMenu.mouse_is_panning = False
  5532. if origin_click is None:
  5533. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5534. if event.button == pan_button and self.event_is_dragging == 1:
  5535. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5536. if self.ui.popMenu.popup_active:
  5537. self.ui.popMenu.popup_active = False
  5538. return
  5539. self.ui.popMenu.mouse_is_panning = True
  5540. return
  5541. if self.rel_point1 is not None:
  5542. try: # May fail in case mouse not within axes
  5543. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5544. if self.grid_status():
  5545. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5546. # Update cursor
  5547. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5548. symbol='++', edge_color=self.cursor_color_3D,
  5549. edge_width=self.defaults["global_cursor_width"],
  5550. size=self.defaults["global_cursor_size"])
  5551. else:
  5552. pos = (pos_canvas[0], pos_canvas[1])
  5553. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5554. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5555. self.dx = pos[0] - float(self.rel_point1[0])
  5556. self.dy = pos[1] - float(self.rel_point1[1])
  5557. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5558. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5559. self.mouse = [pos[0], pos[1]]
  5560. # if the mouse is moved and the LMB is clicked then the action is a selection
  5561. if self.event_is_dragging == 1 and event.button == 1:
  5562. self.delete_selection_shape()
  5563. if self.dx < 0:
  5564. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5565. face_color=self.defaults['global_alt_sel_fill'])
  5566. self.selection_type = False
  5567. elif self.dx >= 0:
  5568. self.draw_moving_selection_shape(self.pos, pos)
  5569. self.selection_type = True
  5570. else:
  5571. self.selection_type = None
  5572. else:
  5573. self.selection_type = None
  5574. # hover effect - enabled in Preferences -> General -> GUI Settings
  5575. if self.defaults['global_hover']:
  5576. for obj in self.collection.get_list():
  5577. try:
  5578. # select the object(s) only if it is enabled (plotted)
  5579. if obj.options['plot']:
  5580. if obj not in self.collection.get_selected():
  5581. poly_obj = Polygon(
  5582. [(obj.options['xmin'], obj.options['ymin']),
  5583. (obj.options['xmax'], obj.options['ymin']),
  5584. (obj.options['xmax'], obj.options['ymax']),
  5585. (obj.options['xmin'], obj.options['ymax'])]
  5586. )
  5587. if Point(pos).within(poly_obj):
  5588. if obj.isHovering is False:
  5589. obj.isHovering = True
  5590. obj.notHovering = True
  5591. # create the selection box around the selected object
  5592. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5593. else:
  5594. if obj.notHovering is True:
  5595. obj.notHovering = False
  5596. obj.isHovering = False
  5597. self.delete_hover_shape()
  5598. except Exception:
  5599. # the Exception here will happen if we try to select on screen and we have an
  5600. # newly (and empty) just created Geometry or Excellon object that do not have the
  5601. # xmin, xmax, ymin, ymax options.
  5602. # In this case poly_obj creation (see above) will fail
  5603. pass
  5604. except Exception:
  5605. self.ui.position_label.setText("")
  5606. self.ui.rel_position_label.setText("")
  5607. self.mouse = None
  5608. def on_mouse_click_release_over_plot(self, event):
  5609. """
  5610. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5611. and has been registered in ''self.__init__()''.
  5612. :param event: contains information about the event.
  5613. :return:
  5614. """
  5615. if self.is_legacy is False:
  5616. event_pos = event.pos
  5617. right_button = 2
  5618. else:
  5619. event_pos = (event.xdata, event.ydata)
  5620. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5621. right_button = 3
  5622. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5623. if self.grid_status():
  5624. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5625. else:
  5626. pos = (pos_canvas[0], pos_canvas[1])
  5627. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5628. # canvas menu
  5629. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5630. self.ui.popMenu.mouse_is_panning = False
  5631. self.cursor = QtGui.QCursor()
  5632. self.populate_cmenu_grids()
  5633. self.ui.popMenu.popup(self.cursor.pos())
  5634. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5635. # selection and then select a type of selection ("enclosing" or "touching")
  5636. if event.button == 1: # left click
  5637. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5638. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5639. if modifiers == QtCore.Qt.ShiftModifier:
  5640. # do not auto open the Project Tab
  5641. self.click_noproject = True
  5642. self.clipboard.setText(
  5643. self.defaults["global_point_clipboard_format"] %
  5644. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5645. )
  5646. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5647. return
  5648. if self.doubleclick is True:
  5649. self.doubleclick = False
  5650. if self.collection.get_selected():
  5651. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5652. if self.ui.splitter.sizes()[0] == 0:
  5653. self.ui.splitter.setSizes([1, 1])
  5654. try:
  5655. # delete the selection shape(S) as it may be in the way
  5656. self.delete_selection_shape()
  5657. self.delete_hover_shape()
  5658. except Exception as e:
  5659. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5660. return
  5661. else:
  5662. # WORKAROUND for LEGACY MODE
  5663. if self.is_legacy is True:
  5664. # if there is no move on canvas then we have no dragging selection
  5665. if self.dx == 0 or self.dy == 0:
  5666. self.selection_type = None
  5667. if self.selection_type is not None:
  5668. try:
  5669. self.selection_area_handler(self.pos, pos, self.selection_type)
  5670. self.selection_type = None
  5671. except Exception as e:
  5672. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5673. return
  5674. else:
  5675. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5676. if key_modifier == QtCore.Qt.ShiftModifier:
  5677. mod_key = 'Shift'
  5678. elif key_modifier == QtCore.Qt.ControlModifier:
  5679. mod_key = 'Control'
  5680. else:
  5681. mod_key = None
  5682. try:
  5683. if mod_key == self.defaults["global_mselect_key"]:
  5684. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5685. # deselect, and if it's not selected then it will be selected
  5686. # If there is no active command (self.command_active is None) then we check if we clicked
  5687. # on a object by checking the bounding limits against mouse click position
  5688. if self.command_active is None:
  5689. self.select_objects(key='multisel')
  5690. self.delete_hover_shape()
  5691. else:
  5692. # If there is no active command (self.command_active is None) then we check if we clicked
  5693. # on a object by checking the bounding limits against mouse click position
  5694. if self.command_active is None:
  5695. self.select_objects()
  5696. self.delete_hover_shape()
  5697. except Exception as e:
  5698. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5699. return
  5700. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5701. """
  5702. :param start_pos: mouse position when the selection LMB click was done
  5703. :param end_pos: mouse position when the left mouse button is released
  5704. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5705. :return:
  5706. """
  5707. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5708. # delete previous selection shape
  5709. self.delete_selection_shape()
  5710. # make all objects inactive
  5711. self.collection.set_all_inactive()
  5712. for obj in self.collection.get_list():
  5713. try:
  5714. # select the object(s) only if it is enabled (plotted)
  5715. if obj.options['plot']:
  5716. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5717. (obj.options['xmax'], obj.options['ymin']),
  5718. (obj.options['xmax'], obj.options['ymax']),
  5719. (obj.options['xmin'], obj.options['ymax'])])
  5720. if sel_type is True:
  5721. if poly_obj.within(poly_selection):
  5722. # create the selection box around the selected object
  5723. if self.defaults['global_selection_shape'] is True:
  5724. self.draw_selection_shape(obj)
  5725. self.collection.set_active(obj.options['name'])
  5726. else:
  5727. if poly_selection.intersects(poly_obj):
  5728. # create the selection box around the selected object
  5729. if self.defaults['global_selection_shape'] is True:
  5730. self.draw_selection_shape(obj)
  5731. self.collection.set_active(obj.options['name'])
  5732. obj.selection_shape_drawn = True
  5733. except Exception as e:
  5734. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5735. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5736. # In this case poly_obj creation (see above) will fail
  5737. log.debug("App.selection_area_handler() --> %s" % str(e))
  5738. def select_objects(self, key=None):
  5739. """
  5740. Will select objects clicked on canvas
  5741. :param key: for future use in cumulative selection
  5742. :return:
  5743. """
  5744. # list where we store the overlapped objects under our mouse left click position
  5745. if key is None:
  5746. self.objects_under_the_click_list = []
  5747. # Populate the list with the overlapped objects on the click position
  5748. curr_x, curr_y = self.pos
  5749. for obj in self.all_objects_list:
  5750. # ScriptObject and DocumentObject objects can't be selected
  5751. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5752. continue
  5753. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5754. continue
  5755. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5756. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5757. if obj.options['name'] not in self.objects_under_the_click_list:
  5758. if obj.options['plot']:
  5759. # add objects to the objects_under_the_click list only if the object is plotted
  5760. # (active and not disabled)
  5761. self.objects_under_the_click_list.append(obj.options['name'])
  5762. try:
  5763. if self.objects_under_the_click_list:
  5764. curr_sel_obj = self.collection.get_active()
  5765. # case when there is only an object under the click and we toggle it
  5766. if len(self.objects_under_the_click_list) == 1:
  5767. if curr_sel_obj is None:
  5768. self.collection.set_active(self.objects_under_the_click_list[0])
  5769. curr_sel_obj = self.collection.get_active()
  5770. # create the selection box around the selected object
  5771. if self.defaults['global_selection_shape'] is True:
  5772. self.draw_selection_shape(curr_sel_obj)
  5773. curr_sel_obj.selection_shape_drawn = True
  5774. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5775. self.on_objects_selection(False)
  5776. self.delete_selection_shape()
  5777. curr_sel_obj.selection_shape_drawn = False
  5778. self.collection.set_active(self.objects_under_the_click_list[0])
  5779. curr_sel_obj = self.collection.get_active()
  5780. # create the selection box around the selected object
  5781. if self.defaults['global_selection_shape'] is True:
  5782. self.draw_selection_shape(curr_sel_obj)
  5783. curr_sel_obj.selection_shape_drawn = True
  5784. self.selected_message(curr_sel_obj=curr_sel_obj)
  5785. elif curr_sel_obj.selection_shape_drawn is False:
  5786. if self.defaults['global_selection_shape'] is True:
  5787. self.draw_selection_shape(curr_sel_obj)
  5788. curr_sel_obj.selection_shape_drawn = True
  5789. else:
  5790. self.on_objects_selection(False)
  5791. self.delete_selection_shape()
  5792. if self.call_source != 'app':
  5793. self.call_source = 'app'
  5794. self.selected_message(curr_sel_obj=curr_sel_obj)
  5795. else:
  5796. # If there is no selected object
  5797. # make active the first element of the overlapped objects list
  5798. if self.collection.get_active() is None:
  5799. self.collection.set_active(self.objects_under_the_click_list[0])
  5800. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5801. name_sel_obj = self.collection.get_active().options['name']
  5802. # In case that there is a selected object but it is not in the overlapped object list
  5803. # make that object inactive and activate the first element in the overlapped object list
  5804. if name_sel_obj not in self.objects_under_the_click_list:
  5805. self.collection.set_inactive(name_sel_obj)
  5806. name_sel_obj = self.objects_under_the_click_list[0]
  5807. self.collection.set_active(name_sel_obj)
  5808. else:
  5809. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5810. self.collection.set_all_inactive()
  5811. self.collection.set_active(
  5812. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5813. curr_sel_obj = self.collection.get_active()
  5814. # delete the possible selection box around a possible selected object
  5815. self.delete_selection_shape()
  5816. curr_sel_obj.selection_shape_drawn = False
  5817. # create the selection box around the selected object
  5818. if self.defaults['global_selection_shape'] is True:
  5819. self.draw_selection_shape(curr_sel_obj)
  5820. curr_sel_obj.selection_shape_drawn = True
  5821. self.selected_message(curr_sel_obj=curr_sel_obj)
  5822. else:
  5823. # deselect everything
  5824. self.on_objects_selection(False)
  5825. # delete the possible selection box around a possible selected object
  5826. self.delete_selection_shape()
  5827. for o in self.collection.get_list():
  5828. o.selection_shape_drawn = False
  5829. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5830. # only when working on App
  5831. if self.call_source == 'app':
  5832. if self.click_noproject is False:
  5833. # if the Tool Tab is in focus don't change focus to Project Tab
  5834. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5835. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5836. else:
  5837. # restore auto open the Project Tab
  5838. self.click_noproject = False
  5839. # delete any text in the status bar, implicitly the last object name that was selected
  5840. # self.inform.emit("")
  5841. else:
  5842. self.call_source = 'app'
  5843. except Exception as e:
  5844. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5845. def selected_message(self, curr_sel_obj):
  5846. if curr_sel_obj:
  5847. if curr_sel_obj.kind == 'gerber':
  5848. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5849. color='green',
  5850. name=str(curr_sel_obj.options['name']),
  5851. tx=_("selected"))
  5852. )
  5853. elif curr_sel_obj.kind == 'excellon':
  5854. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5855. color='brown',
  5856. name=str(curr_sel_obj.options['name']),
  5857. tx=_("selected"))
  5858. )
  5859. elif curr_sel_obj.kind == 'cncjob':
  5860. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5861. color='blue',
  5862. name=str(curr_sel_obj.options['name']),
  5863. tx=_("selected"))
  5864. )
  5865. elif curr_sel_obj.kind == 'geometry':
  5866. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5867. color='red',
  5868. name=str(curr_sel_obj.options['name']),
  5869. tx=_("selected"))
  5870. )
  5871. def delete_hover_shape(self):
  5872. self.hover_shapes.clear()
  5873. self.hover_shapes.redraw()
  5874. def draw_hover_shape(self, sel_obj, color=None):
  5875. """
  5876. :param sel_obj: The object for which the hover shape must be drawn
  5877. :param color: The color of the hover shape
  5878. :return: None
  5879. """
  5880. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5881. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5882. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5883. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5884. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5885. if self.defaults['units'].upper() == 'MM':
  5886. hover_rect = hover_rect.buffer(-0.1)
  5887. hover_rect = hover_rect.buffer(0.2)
  5888. else:
  5889. hover_rect = hover_rect.buffer(-0.00393)
  5890. hover_rect = hover_rect.buffer(0.00787)
  5891. # if color:
  5892. # face = Color(color)
  5893. # face.alpha = 0.2
  5894. # outline = Color(color, alpha=0.8)
  5895. # else:
  5896. # face = Color(self.defaults['global_sel_fill'])
  5897. # face.alpha = 0.2
  5898. # outline = self.defaults['global_sel_line']
  5899. if color:
  5900. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5901. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5902. else:
  5903. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5904. outline = self.defaults['global_sel_line']
  5905. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5906. if self.is_legacy is True:
  5907. self.hover_shapes.redraw()
  5908. def delete_selection_shape(self):
  5909. self.move_tool.sel_shapes.clear()
  5910. self.move_tool.sel_shapes.redraw()
  5911. def draw_selection_shape(self, sel_obj, color=None):
  5912. """
  5913. Will draw a selection shape around the selected object.
  5914. :param sel_obj: The object for which the selection shape must be drawn
  5915. :param color: The color for the selection shape.
  5916. :return: None
  5917. """
  5918. if sel_obj is None:
  5919. return
  5920. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5921. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5922. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5923. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5924. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5925. if self.defaults['units'].upper() == 'MM':
  5926. sel_rect = sel_rect.buffer(-0.1)
  5927. sel_rect = sel_rect.buffer(0.2)
  5928. else:
  5929. sel_rect = sel_rect.buffer(-0.00393)
  5930. sel_rect = sel_rect.buffer(0.00787)
  5931. if color:
  5932. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5933. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5934. else:
  5935. if self.is_legacy is False:
  5936. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5937. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5938. else:
  5939. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5940. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5941. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5942. color=outline,
  5943. face_color=face,
  5944. update=True,
  5945. layer=0,
  5946. tolerance=None))
  5947. if self.is_legacy is True:
  5948. self.move_tool.sel_shapes.redraw()
  5949. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5950. """
  5951. Will draw a selection shape when dragging mouse on canvas.
  5952. :param old_coords: Old coordinates
  5953. :param coords: New coordinates
  5954. :param kwargs: Keyword arguments
  5955. :return:
  5956. """
  5957. if 'color' in kwargs:
  5958. color = kwargs['color']
  5959. else:
  5960. color = self.defaults['global_sel_line']
  5961. if 'face_color' in kwargs:
  5962. face_color = kwargs['face_color']
  5963. else:
  5964. face_color = self.defaults['global_sel_fill']
  5965. if 'face_alpha' in kwargs:
  5966. face_alpha = kwargs['face_alpha']
  5967. else:
  5968. face_alpha = 0.3
  5969. x0, y0 = old_coords
  5970. x1, y1 = coords
  5971. pt1 = (x0, y0)
  5972. pt2 = (x1, y0)
  5973. pt3 = (x1, y1)
  5974. pt4 = (x0, y1)
  5975. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5976. # color_t = Color(face_color)
  5977. # color_t.alpha = face_alpha
  5978. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5979. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5980. layer=0, tolerance=None)
  5981. if self.is_legacy is True:
  5982. self.move_tool.sel_shapes.redraw()
  5983. def on_file_new_click(self):
  5984. """
  5985. Callback for menu item File -> New.
  5986. Executed on clicking the Menu -> File -> New Project
  5987. :return:
  5988. """
  5989. if self.collection.get_list() and self.should_we_save:
  5990. msgbox = QtWidgets.QMessageBox()
  5991. # msgbox.setText("<B>Save changes ...</B>")
  5992. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5993. "Creating a New project will delete them.\n"
  5994. "Do you want to Save the project?"))
  5995. msgbox.setWindowTitle(_("Save changes"))
  5996. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5997. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5998. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5999. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6000. msgbox.setDefaultButton(bt_yes)
  6001. msgbox.exec_()
  6002. response = msgbox.clickedButton()
  6003. if response == bt_yes:
  6004. self.on_file_saveprojectas()
  6005. elif response == bt_cancel:
  6006. return
  6007. elif response == bt_no:
  6008. self.on_file_new()
  6009. else:
  6010. self.on_file_new()
  6011. self.inform.emit('[success] %s...' % _("New Project created"))
  6012. def on_file_new(self, cli=None):
  6013. """
  6014. Returns the application to its startup state. This method is thread-safe.
  6015. :param cli: Boolean. If True this method was run from command line
  6016. :return: None
  6017. """
  6018. self.defaults.report_usage("on_file_new")
  6019. # Remove everything from memory
  6020. App.log.debug("on_file_new()")
  6021. if self.call_source != 'app':
  6022. self.editor2object(cleanup=True)
  6023. # ## EDITOR section
  6024. self.geo_editor = FlatCAMGeoEditor(self)
  6025. self.exc_editor = FlatCAMExcEditor(self)
  6026. self.grb_editor = FlatCAMGrbEditor(self)
  6027. # Clear pool
  6028. self.clear_pool()
  6029. for obj in self.collection.get_list():
  6030. # delete shapes left drawn from mark shape_collections, if any
  6031. if isinstance(obj, GerberObject):
  6032. try:
  6033. for el in obj.mark_shapes:
  6034. obj.mark_shapes[el].clear(update=True)
  6035. obj.mark_shapes[el].enabled = False
  6036. del el
  6037. except AttributeError:
  6038. pass
  6039. # also delete annotation shapes, if any
  6040. elif isinstance(obj, CNCJobObject):
  6041. try:
  6042. obj.text_col.enabled = False
  6043. del obj.text_col
  6044. obj.annotation.clear(update=True)
  6045. del obj.annotation
  6046. except AttributeError:
  6047. pass
  6048. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6049. self.shell.init_tcl()
  6050. self.delete_selection_shape()
  6051. self.collection.delete_all()
  6052. self.setup_component_editor()
  6053. # Clear project filename
  6054. self.project_filename = None
  6055. # Load the application defaults
  6056. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  6057. # Re-fresh project options
  6058. self.on_options_app2project()
  6059. # Init Tools
  6060. self.init_tools()
  6061. if cli is None:
  6062. # Close any Tabs opened in the Plot Tab Area section
  6063. for index in range(self.ui.plot_tab_area.count()):
  6064. self.ui.plot_tab_area.closeTab(index)
  6065. # for whatever reason previous command does not close the last tab so I do it manually
  6066. self.ui.plot_tab_area.closeTab(0)
  6067. # # And then add again the Plot Area
  6068. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6069. self.ui.plot_tab_area.protectTab(0)
  6070. # take the focus of the Notebook on Project Tab.
  6071. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6072. self.set_ui_title(name=_("New Project - Not saved"))
  6073. def obj_properties(self):
  6074. """
  6075. Will launch the object Properties Tool
  6076. :return:
  6077. """
  6078. self.defaults.report_usage("obj_properties()")
  6079. self.properties_tool.run(toggle=False)
  6080. def on_project_context_save(self):
  6081. """
  6082. Wrapper, will save the object function of it's type
  6083. :return:
  6084. """
  6085. obj = self.collection.get_active()
  6086. if type(obj) == GeometryObject:
  6087. self.on_file_exportdxf()
  6088. elif type(obj) == ExcellonObject:
  6089. self.on_file_saveexcellon()
  6090. elif type(obj) == CNCJobObject:
  6091. obj.on_exportgcode_button_click()
  6092. elif type(obj) == GerberObject:
  6093. self.on_file_savegerber()
  6094. elif type(obj) == ScriptObject:
  6095. self.on_file_savescript()
  6096. elif type(obj) == DocumentObject:
  6097. self.on_file_savedocument()
  6098. def obj_move(self):
  6099. """
  6100. Callback for the Move menu entry in various Context Menu's.
  6101. :return:
  6102. """
  6103. self.defaults.report_usage("obj_move()")
  6104. self.move_tool.run(toggle=False)
  6105. def on_fileopengerber(self, signal, name=None):
  6106. """
  6107. File menu callback for opening a Gerber.
  6108. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6109. :param name:
  6110. :return: None
  6111. """
  6112. self.defaults.report_usage("on_fileopengerber")
  6113. App.log.debug("on_fileopengerber()")
  6114. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6115. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6116. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6117. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6118. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6119. "*.mil);;" \
  6120. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6121. "Allegro Files (*.art);;" \
  6122. "Mentor Files (*.pho *.gdo);;" \
  6123. "All Files (*.*)"
  6124. if name is None:
  6125. try:
  6126. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6127. directory=self.get_last_folder(),
  6128. filter=_filter_)
  6129. except TypeError:
  6130. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6131. filenames = [str(filename) for filename in filenames]
  6132. else:
  6133. filenames = [name]
  6134. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6135. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6136. _("Opening Gerber file.")),
  6137. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6138. color=QtGui.QColor("gray"))
  6139. if len(filenames) == 0:
  6140. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6141. else:
  6142. for filename in filenames:
  6143. if filename != '':
  6144. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6145. def on_fileopenexcellon(self, signal, name=None):
  6146. """
  6147. File menu callback for opening an Excellon file.
  6148. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6149. :param name:
  6150. :return: None
  6151. """
  6152. self.defaults.report_usage("on_fileopenexcellon")
  6153. App.log.debug("on_fileopenexcellon()")
  6154. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6155. "All Files (*.*)"
  6156. if name is None:
  6157. try:
  6158. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6159. directory=self.get_last_folder(),
  6160. filter=_filter_)
  6161. except TypeError:
  6162. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6163. filenames = [str(filename) for filename in filenames]
  6164. else:
  6165. filenames = [str(name)]
  6166. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6167. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6168. _("Opening Excellon file.")),
  6169. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6170. color=QtGui.QColor("gray"))
  6171. if len(filenames) == 0:
  6172. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6173. else:
  6174. for filename in filenames:
  6175. if filename != '':
  6176. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6177. def on_fileopengcode(self, signal, name=None):
  6178. """
  6179. File menu call back for opening gcode.
  6180. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6181. :param name:
  6182. :return:
  6183. """
  6184. self.defaults.report_usage("on_fileopengcode")
  6185. App.log.debug("on_fileopengcode()")
  6186. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6187. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6188. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6189. "All Files (*.*)"
  6190. if name is None:
  6191. try:
  6192. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6193. directory=self.get_last_folder(),
  6194. filter=_filter_)
  6195. except TypeError:
  6196. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6197. filenames = [str(filename) for filename in filenames]
  6198. else:
  6199. filenames = [name]
  6200. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6201. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6202. _("Opening G-Code file.")),
  6203. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6204. color=QtGui.QColor("gray"))
  6205. if len(filenames) == 0:
  6206. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6207. else:
  6208. for filename in filenames:
  6209. if filename != '':
  6210. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6211. def on_file_openproject(self, signal):
  6212. """
  6213. File menu callback for opening a project.
  6214. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6215. :return: None
  6216. """
  6217. self.defaults.report_usage("on_file_openproject")
  6218. App.log.debug("on_file_openproject()")
  6219. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6220. try:
  6221. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6222. directory=self.get_last_folder(), filter=_filter_)
  6223. except TypeError:
  6224. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6225. # The Qt methods above will return a QString which can cause problems later.
  6226. # So far json.dump() will fail to serialize it.
  6227. # TODO: Improve the serialization methods and remove this fix.
  6228. filename = str(filename)
  6229. if filename == "":
  6230. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6231. else:
  6232. # self.worker_task.emit({'fcn': self.open_project,
  6233. # 'params': [filename]})
  6234. # The above was failing because open_project() is not
  6235. # thread safe. The new_project()
  6236. self.open_project(filename)
  6237. def on_fileopenhpgl2(self, signal, name=None):
  6238. """
  6239. File menu callback for opening a HPGL2.
  6240. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6241. :param name:
  6242. :return: None
  6243. """
  6244. self.defaults.report_usage("on_fileopenhpgl2")
  6245. App.log.debug("on_fileopenhpgl2()")
  6246. _filter_ = "HPGL2 Files (*.plt);;" \
  6247. "All Files (*.*)"
  6248. if name is None:
  6249. try:
  6250. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6251. directory=self.get_last_folder(),
  6252. filter=_filter_)
  6253. except TypeError:
  6254. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6255. filenames = [str(filename) for filename in filenames]
  6256. else:
  6257. filenames = [name]
  6258. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6259. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6260. _("Opening HPGL2 file.")),
  6261. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6262. color=QtGui.QColor("gray"))
  6263. if len(filenames) == 0:
  6264. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6265. else:
  6266. for filename in filenames:
  6267. if filename != '':
  6268. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6269. def on_file_openconfig(self, signal):
  6270. """
  6271. File menu callback for opening a config file.
  6272. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6273. :return: None
  6274. """
  6275. self.defaults.report_usage("on_file_openconfig")
  6276. App.log.debug("on_file_openconfig()")
  6277. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6278. try:
  6279. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6280. directory=self.data_path, filter=_filter_)
  6281. except TypeError:
  6282. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6283. filter=_filter_)
  6284. if filename == "":
  6285. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6286. else:
  6287. self.open_config_file(filename)
  6288. def on_file_exportsvg(self):
  6289. """
  6290. Callback for menu item File->Export SVG.
  6291. :return: None
  6292. """
  6293. self.defaults.report_usage("on_file_exportsvg")
  6294. App.log.debug("on_file_exportsvg()")
  6295. obj = self.collection.get_active()
  6296. if obj is None:
  6297. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6298. msg = _("Please Select a Geometry object to export")
  6299. msgbox = QtWidgets.QMessageBox()
  6300. msgbox.setInformativeText(msg)
  6301. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6302. msgbox.setDefaultButton(bt_ok)
  6303. msgbox.exec_()
  6304. return
  6305. # Check for more compatible types and add as required
  6306. if (not isinstance(obj, GeometryObject)
  6307. and not isinstance(obj, GerberObject)
  6308. and not isinstance(obj, CNCJobObject)
  6309. and not isinstance(obj, ExcellonObject)):
  6310. msg = '[ERROR_NOTCL] %s' % \
  6311. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6312. msgbox = QtWidgets.QMessageBox()
  6313. msgbox.setInformativeText(msg)
  6314. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6315. msgbox.setDefaultButton(bt_ok)
  6316. msgbox.exec_()
  6317. return
  6318. name = obj.options["name"]
  6319. _filter = "SVG File (*.svg);;All Files (*.*)"
  6320. try:
  6321. filename, _f = FCFileSaveDialog.get_saved_filename(
  6322. caption=_("Export SVG"),
  6323. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6324. filter=_filter)
  6325. except TypeError:
  6326. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6327. filename = str(filename)
  6328. if filename == "":
  6329. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6330. return
  6331. else:
  6332. self.export_svg(name, filename)
  6333. if self.defaults["global_open_style"] is False:
  6334. self.file_opened.emit("SVG", filename)
  6335. self.file_saved.emit("SVG", filename)
  6336. def on_file_exportpng(self):
  6337. self.defaults.report_usage("on_file_exportpng")
  6338. App.log.debug("on_file_exportpng()")
  6339. self.date = str(datetime.today()).rpartition('.')[0]
  6340. self.date = ''.join(c for c in self.date if c not in ':-')
  6341. self.date = self.date.replace(' ', '_')
  6342. if self.is_legacy is False:
  6343. image = _screenshot()
  6344. data = np.asarray(image)
  6345. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6346. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6347. return
  6348. filter_ = "PNG File (*.png);;All Files (*.*)"
  6349. try:
  6350. filename, _f = FCFileSaveDialog.get_saved_filename(
  6351. caption=_("Export PNG Image"),
  6352. directory=self.get_last_save_folder() + '/png_' + self.date,
  6353. filter=filter_)
  6354. except TypeError:
  6355. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6356. filename = str(filename)
  6357. if filename == "":
  6358. self.inform.emit(_("Cancelled."))
  6359. return
  6360. else:
  6361. if self.is_legacy is False:
  6362. write_png(filename, data)
  6363. else:
  6364. self.plotcanvas.figure.savefig(filename)
  6365. if self.defaults["global_open_style"] is False:
  6366. self.file_opened.emit("png", filename)
  6367. self.file_saved.emit("png", filename)
  6368. def on_file_savegerber(self):
  6369. """
  6370. Callback for menu item in Project context menu.
  6371. :return: None
  6372. """
  6373. self.defaults.report_usage("on_file_savegerber")
  6374. App.log.debug("on_file_savegerber()")
  6375. obj = self.collection.get_active()
  6376. if obj is None:
  6377. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6378. return
  6379. # Check for more compatible types and add as required
  6380. if not isinstance(obj, GerberObject):
  6381. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6382. return
  6383. name = self.collection.get_active().options["name"]
  6384. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6385. try:
  6386. filename, _f = FCFileSaveDialog.get_saved_filename(
  6387. caption="Save Gerber source file",
  6388. directory=self.get_last_save_folder() + '/' + name,
  6389. filter=_filter)
  6390. except TypeError:
  6391. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6392. filename = str(filename)
  6393. if filename == "":
  6394. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6395. return
  6396. else:
  6397. self.save_source_file(name, filename)
  6398. if self.defaults["global_open_style"] is False:
  6399. self.file_opened.emit("Gerber", filename)
  6400. self.file_saved.emit("Gerber", filename)
  6401. def on_file_savescript(self):
  6402. """
  6403. Callback for menu item in Project context menu.
  6404. :return: None
  6405. """
  6406. self.defaults.report_usage("on_file_savescript")
  6407. App.log.debug("on_file_savescript()")
  6408. obj = self.collection.get_active()
  6409. if obj is None:
  6410. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6411. return
  6412. # Check for more compatible types and add as required
  6413. if not isinstance(obj, ScriptObject):
  6414. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6415. return
  6416. name = self.collection.get_active().options["name"]
  6417. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6418. try:
  6419. filename, _f = FCFileSaveDialog.get_saved_filename(
  6420. caption="Save Script source file",
  6421. directory=self.get_last_save_folder() + '/' + name,
  6422. filter=_filter)
  6423. except TypeError:
  6424. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6425. filename = str(filename)
  6426. if filename == "":
  6427. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6428. return
  6429. else:
  6430. self.save_source_file(name, filename)
  6431. if self.defaults["global_open_style"] is False:
  6432. self.file_opened.emit("Script", filename)
  6433. self.file_saved.emit("Script", filename)
  6434. def on_file_savedocument(self):
  6435. """
  6436. Callback for menu item in Project context menu.
  6437. :return: None
  6438. """
  6439. self.defaults.report_usage("on_file_savedocument")
  6440. App.log.debug("on_file_savedocument()")
  6441. obj = self.collection.get_active()
  6442. if obj is None:
  6443. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6444. return
  6445. # Check for more compatible types and add as required
  6446. if not isinstance(obj, ScriptObject):
  6447. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6448. return
  6449. name = self.collection.get_active().options["name"]
  6450. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6451. try:
  6452. filename, _f = FCFileSaveDialog.get_saved_filename(
  6453. caption="Save Document source file",
  6454. directory=self.get_last_save_folder() + '/' + name,
  6455. filter=_filter)
  6456. except TypeError:
  6457. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6458. filename = str(filename)
  6459. if filename == "":
  6460. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6461. return
  6462. else:
  6463. self.save_source_file(name, filename)
  6464. if self.defaults["global_open_style"] is False:
  6465. self.file_opened.emit("Document", filename)
  6466. self.file_saved.emit("Document", filename)
  6467. def on_file_saveexcellon(self):
  6468. """
  6469. Callback for menu item in project context menu.
  6470. :return: None
  6471. """
  6472. self.defaults.report_usage("on_file_saveexcellon")
  6473. App.log.debug("on_file_saveexcellon()")
  6474. obj = self.collection.get_active()
  6475. if obj is None:
  6476. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6477. return
  6478. # Check for more compatible types and add as required
  6479. if not isinstance(obj, ExcellonObject):
  6480. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6481. return
  6482. name = self.collection.get_active().options["name"]
  6483. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6484. try:
  6485. filename, _f = FCFileSaveDialog.get_saved_filename(
  6486. caption=_("Save Excellon source file"),
  6487. directory=self.get_last_save_folder() + '/' + name,
  6488. filter=_filter)
  6489. except TypeError:
  6490. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6491. filename = str(filename)
  6492. if filename == "":
  6493. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6494. return
  6495. else:
  6496. self.save_source_file(name, filename)
  6497. if self.defaults["global_open_style"] is False:
  6498. self.file_opened.emit("Excellon", filename)
  6499. self.file_saved.emit("Excellon", filename)
  6500. def on_file_exportexcellon(self):
  6501. """
  6502. Callback for menu item File->Export->Excellon.
  6503. :return: None
  6504. """
  6505. self.defaults.report_usage("on_file_exportexcellon")
  6506. App.log.debug("on_file_exportexcellon()")
  6507. obj = self.collection.get_active()
  6508. if obj is None:
  6509. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6510. return
  6511. # Check for more compatible types and add as required
  6512. if not isinstance(obj, ExcellonObject):
  6513. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6514. return
  6515. name = self.collection.get_active().options["name"]
  6516. _filter = self.defaults["excellon_save_filters"]
  6517. try:
  6518. filename, _f = FCFileSaveDialog.get_saved_filename(
  6519. caption=_("Export Excellon"),
  6520. directory=self.get_last_save_folder() + '/' + name,
  6521. filter=_filter)
  6522. except TypeError:
  6523. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6524. filename = str(filename)
  6525. if filename == "":
  6526. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6527. return
  6528. else:
  6529. used_extension = filename.rpartition('.')[2]
  6530. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6531. self.export_excellon(name, filename)
  6532. if self.defaults["global_open_style"] is False:
  6533. self.file_opened.emit("Excellon", filename)
  6534. self.file_saved.emit("Excellon", filename)
  6535. def on_file_exportgerber(self):
  6536. """
  6537. Callback for menu item File->Export->Gerber.
  6538. :return: None
  6539. """
  6540. self.defaults.report_usage("on_file_exportgerber")
  6541. App.log.debug("on_file_exportgerber()")
  6542. obj = self.collection.get_active()
  6543. if obj is None:
  6544. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6545. return
  6546. # Check for more compatible types and add as required
  6547. if not isinstance(obj, GerberObject):
  6548. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6549. return
  6550. name = self.collection.get_active().options["name"]
  6551. _filter_ = self.defaults['gerber_save_filters']
  6552. try:
  6553. filename, _f = FCFileSaveDialog.get_saved_filename(
  6554. caption=_("Export Gerber"),
  6555. directory=self.get_last_save_folder() + '/' + name,
  6556. filter=_filter_)
  6557. except TypeError:
  6558. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6559. filename = str(filename)
  6560. if filename == "":
  6561. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6562. return
  6563. else:
  6564. used_extension = filename.rpartition('.')[2]
  6565. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6566. self.export_gerber(name, filename)
  6567. if self.defaults["global_open_style"] is False:
  6568. self.file_opened.emit("Gerber", filename)
  6569. self.file_saved.emit("Gerber", filename)
  6570. def on_file_exportdxf(self):
  6571. """
  6572. Callback for menu item File->Export DXF.
  6573. :return: None
  6574. """
  6575. self.defaults.report_usage("on_file_exportdxf")
  6576. App.log.debug("on_file_exportdxf()")
  6577. obj = self.collection.get_active()
  6578. if obj is None:
  6579. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6580. msg = _("Please Select a Geometry object to export")
  6581. msgbox = QtWidgets.QMessageBox()
  6582. msgbox.setInformativeText(msg)
  6583. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6584. msgbox.setDefaultButton(bt_ok)
  6585. msgbox.exec_()
  6586. return
  6587. # Check for more compatible types and add as required
  6588. if not isinstance(obj, GeometryObject):
  6589. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6590. msgbox = QtWidgets.QMessageBox()
  6591. msgbox.setInformativeText(msg)
  6592. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6593. msgbox.setDefaultButton(bt_ok)
  6594. msgbox.exec_()
  6595. return
  6596. name = self.collection.get_active().options["name"]
  6597. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6598. try:
  6599. filename, _f = FCFileSaveDialog.get_saved_filename(
  6600. caption=_("Export DXF"),
  6601. directory=self.get_last_save_folder() + '/' + name,
  6602. filter=_filter_)
  6603. except TypeError:
  6604. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6605. filename = str(filename)
  6606. if filename == "":
  6607. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6608. return
  6609. else:
  6610. self.export_dxf(name, filename)
  6611. if self.defaults["global_open_style"] is False:
  6612. self.file_opened.emit("DXF", filename)
  6613. self.file_saved.emit("DXF", filename)
  6614. def on_file_importsvg(self, type_of_obj):
  6615. """
  6616. Callback for menu item File->Import SVG.
  6617. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6618. :type type_of_obj: str
  6619. :return: None
  6620. """
  6621. self.defaults.report_usage("on_file_importsvg")
  6622. App.log.debug("on_file_importsvg()")
  6623. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6624. try:
  6625. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6626. directory=self.get_last_folder(), filter=_filter_)
  6627. except TypeError:
  6628. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6629. filter=_filter_)
  6630. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6631. type_of_obj = "geometry"
  6632. filenames = [str(filename) for filename in filenames]
  6633. if len(filenames) == 0:
  6634. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6635. else:
  6636. for filename in filenames:
  6637. if filename != '':
  6638. self.worker_task.emit({'fcn': self.import_svg,
  6639. 'params': [filename, type_of_obj]})
  6640. def on_file_importdxf(self, type_of_obj):
  6641. """
  6642. Callback for menu item File->Import DXF.
  6643. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6644. :type type_of_obj: str
  6645. :return: None
  6646. """
  6647. self.defaults.report_usage("on_file_importdxf")
  6648. App.log.debug("on_file_importdxf()")
  6649. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6650. try:
  6651. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6652. directory=self.get_last_folder(),
  6653. filter=_filter_)
  6654. except TypeError:
  6655. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6656. filter=_filter_)
  6657. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6658. type_of_obj = "geometry"
  6659. filenames = [str(filename) for filename in filenames]
  6660. if len(filenames) == 0:
  6661. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6662. else:
  6663. for filename in filenames:
  6664. if filename != '':
  6665. self.worker_task.emit({'fcn': self.import_dxf,
  6666. 'params': [filename, type_of_obj]})
  6667. # ###############################################################################################################
  6668. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6669. # ###############################################################################################################
  6670. def init_code_editor(self, name):
  6671. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6672. # add the tab if it was closed
  6673. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6674. self.text_editor_tab.setObjectName('text_editor_tab')
  6675. # delete the absolute and relative position and messages in the infobar
  6676. self.ui.position_label.setText("")
  6677. self.ui.rel_position_label.setText("")
  6678. # first clear previous text in text editor (if any)
  6679. self.text_editor_tab.code_editor.clear()
  6680. self.text_editor_tab.code_editor.setReadOnly(False)
  6681. self.toggle_codeeditor = True
  6682. self.text_editor_tab.code_editor.completer_enable = False
  6683. self.text_editor_tab.buttonRun.hide()
  6684. # make sure to keep a reference to the code editor
  6685. self.reference_code_editor = self.text_editor_tab.code_editor
  6686. # Switch plot_area to CNCJob tab
  6687. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6688. def on_view_source(self):
  6689. """
  6690. Called when the user wants to see the source file of the selected object
  6691. :return:
  6692. """
  6693. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6694. self.proc_container.view.set_busy(_("Loading..."))
  6695. try:
  6696. obj = self.collection.get_active()
  6697. except Exception as e:
  6698. log.debug("App.on_view_source() --> %s" % str(e))
  6699. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6700. return 'fail'
  6701. if obj is None:
  6702. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6703. return 'fail'
  6704. flt = "All Files (*.*)"
  6705. if obj.kind == 'gerber':
  6706. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6707. elif obj.kind == 'excellon':
  6708. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6709. elif obj.kind == 'cncjob':
  6710. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6711. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6712. # add the tab if it was closed
  6713. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6714. self.source_editor_tab.setObjectName('source_editor_tab')
  6715. # delete the absolute and relative position and messages in the infobar
  6716. self.ui.position_label.setText("")
  6717. self.ui.rel_position_label.setText("")
  6718. # first clear previous text in text editor (if any)
  6719. self.source_editor_tab.code_editor.clear()
  6720. self.source_editor_tab.code_editor.setReadOnly(False)
  6721. self.source_editor_tab.code_editor.completer_enable = False
  6722. self.source_editor_tab.buttonRun.hide()
  6723. # Switch plot_area to CNCJob tab
  6724. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6725. try:
  6726. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6727. except TypeError:
  6728. pass
  6729. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6730. try:
  6731. self.source_editor_tab.buttonSave.clicked.disconnect()
  6732. except TypeError:
  6733. pass
  6734. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6735. # then append the text from GCode to the text editor
  6736. if obj.kind == 'cncjob':
  6737. try:
  6738. file = obj.export_gcode(
  6739. preamble=self.defaults["cncjob_prepend"],
  6740. postamble=self.defaults["cncjob_append"],
  6741. to_file=True)
  6742. if file == 'fail':
  6743. return 'fail'
  6744. except AttributeError:
  6745. self.inform.emit('[WARNING_NOTCL] %s' %
  6746. _("There is no selected object for which to see it's source file code."))
  6747. return 'fail'
  6748. else:
  6749. try:
  6750. file = StringIO(obj.source_file)
  6751. except (AttributeError, TypeError):
  6752. self.inform.emit('[WARNING_NOTCL] %s' %
  6753. _("There is no selected object for which to see it's source file code."))
  6754. return 'fail'
  6755. self.source_editor_tab.t_frame.hide()
  6756. try:
  6757. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6758. # for line in file:
  6759. # QtWidgets.QApplication.processEvents()
  6760. # proc_line = str(line).strip('\n')
  6761. # self.source_editor_tab.code_editor.append(proc_line)
  6762. except Exception as e:
  6763. log.debug('App.on_view_source() -->%s' % str(e))
  6764. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6765. return
  6766. self.source_editor_tab.handleTextChanged()
  6767. self.source_editor_tab.t_frame.show()
  6768. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6769. self.proc_container.view.set_idle()
  6770. # self.ui.show()
  6771. def on_toggle_code_editor(self):
  6772. self.defaults.report_usage("on_toggle_code_editor()")
  6773. if self.toggle_codeeditor is False:
  6774. self.init_code_editor(name=_("Code Editor"))
  6775. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6776. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6777. self.text_editor_tab.buttonSave.clicked.disconnect()
  6778. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6779. else:
  6780. for idx in range(self.ui.plot_tab_area.count()):
  6781. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6782. self.ui.plot_tab_area.closeTab(idx)
  6783. break
  6784. self.toggle_codeeditor = False
  6785. def on_code_editor_close(self):
  6786. self.toggle_codeeditor = False
  6787. def goto_text_line(self):
  6788. """
  6789. Will scroll a text to the specified text line.
  6790. :return: None
  6791. """
  6792. dia_box = Dialog_box(title=_("Go to Line ..."),
  6793. label=_("Line:"),
  6794. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6795. initial_text='')
  6796. try:
  6797. line = int(dia_box.location) - 1
  6798. except (ValueError, TypeError):
  6799. line = 0
  6800. if dia_box.ok:
  6801. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6802. # at the top of the window
  6803. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6804. # get the document() of the TextEditor
  6805. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6806. # create a Text Cursor based on the searched line
  6807. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6808. # set cursor of the code editor with the cursor at the searcehd line
  6809. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6810. def on_filenewscript(self, silent=False, name=None, text=None):
  6811. """
  6812. Will create a new script file and open it in the Code Editor
  6813. :param silent: if True will not display status messages
  6814. :param name: if specified will be the name of the new script
  6815. :param text: pass a source file to the newly created script to be loaded in it
  6816. :return: None
  6817. """
  6818. if silent is False:
  6819. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6820. # delete the absolute and relative position and messages in the infobar
  6821. self.ui.position_label.setText("")
  6822. self.ui.rel_position_label.setText("")
  6823. if name is not None:
  6824. self.new_script_object(name=name, text=text)
  6825. else:
  6826. self.new_script_object(text=text)
  6827. # script_text = script_obj.source_file
  6828. #
  6829. # self.proc_container.view.set_busy(_("Loading..."))
  6830. # script_obj.script_editor_tab.t_frame.hide()
  6831. #
  6832. # script_obj.script_editor_tab.t_frame.show()
  6833. # self.proc_container.view.set_idle()
  6834. def on_fileopenscript(self, name=None, silent=False):
  6835. """
  6836. Will open a Tcl script file into the Code Editor
  6837. :param silent: if True will not display status messages
  6838. :param name: name of a Tcl script file to open
  6839. :return:
  6840. """
  6841. self.defaults.report_usage("on_fileopenscript")
  6842. App.log.debug("on_fileopenscript()")
  6843. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6844. "All Files (*.*)"
  6845. if name:
  6846. filenames = [name]
  6847. else:
  6848. try:
  6849. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6850. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6851. except TypeError:
  6852. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6853. if len(filenames) == 0:
  6854. if silent is False:
  6855. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6856. else:
  6857. for filename in filenames:
  6858. if filename != '':
  6859. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6860. def on_fileopenscript_example(self, name=None, silent=False):
  6861. """
  6862. Will open a Tcl script file into the Code Editor
  6863. :param silent: if True will not display status messages
  6864. :param name: name of a Tcl script file to open
  6865. :return:
  6866. """
  6867. self.report_usage("on_fileopenscript_example")
  6868. App.log.debug("on_fileopenscript_example()")
  6869. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6870. "All Files (*.*)"
  6871. # test if the app was frozen and choose the path for the configuration file
  6872. if getattr(sys, "frozen", False) is True:
  6873. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6874. else:
  6875. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6876. if name:
  6877. filenames = [name]
  6878. else:
  6879. try:
  6880. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6881. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6882. except TypeError:
  6883. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6884. if len(filenames) == 0:
  6885. if silent is False:
  6886. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6887. else:
  6888. for filename in filenames:
  6889. if filename != '':
  6890. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6891. def on_filerunscript(self, name=None, silent=False):
  6892. """
  6893. File menu callback for loading and running a TCL script.
  6894. :param silent: if True will not display status messages
  6895. :param name: name of a Tcl script file to be run by FlatCAM
  6896. :return: None
  6897. """
  6898. self.defaults.report_usage("on_filerunscript")
  6899. App.log.debug("on_file_runscript()")
  6900. if name:
  6901. filename = name
  6902. if self.cmd_line_headless != 1:
  6903. self.splash.showMessage('%s: %ssec\n%s' %
  6904. (_("Canvas initialization started.\n"
  6905. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6906. _("Executing ScriptObject file.")
  6907. ),
  6908. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6909. color=QtGui.QColor("gray"))
  6910. else:
  6911. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6912. "All Files (*.*)"
  6913. try:
  6914. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6915. directory=self.get_last_folder(), filter=_filter_)
  6916. except TypeError:
  6917. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6918. # The Qt methods above will return a QString which can cause problems later.
  6919. # So far json.dump() will fail to serialize it.
  6920. filename = str(filename)
  6921. if filename == "":
  6922. if silent is False:
  6923. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6924. else:
  6925. if self.cmd_line_headless != 1:
  6926. if self.ui.shell_dock.isHidden():
  6927. self.ui.shell_dock.show()
  6928. try:
  6929. with open(filename, "r") as tcl_script:
  6930. cmd_line_shellfile_content = tcl_script.read()
  6931. if self.cmd_line_headless != 1:
  6932. self.shell.exec_command(cmd_line_shellfile_content)
  6933. else:
  6934. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6935. if silent is False:
  6936. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6937. except Exception as e:
  6938. log.debug("App.on_filerunscript() -> %s" % str(e))
  6939. sys.exit(2)
  6940. def on_file_saveproject(self, silent=False):
  6941. """
  6942. Callback for menu item File->Save Project. Saves the project to
  6943. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6944. if set to None. The project is saved by calling ``self.save_project()``.
  6945. :param silent: if True will not display status messages
  6946. :return: None
  6947. """
  6948. self.defaults.report_usage("on_file_saveproject")
  6949. if self.project_filename is None:
  6950. self.on_file_saveprojectas()
  6951. else:
  6952. self.worker_task.emit({'fcn': self.save_project,
  6953. 'params': [self.project_filename, silent]})
  6954. if self.defaults["global_open_style"] is False:
  6955. self.file_opened.emit("project", self.project_filename)
  6956. self.file_saved.emit("project", self.project_filename)
  6957. self.set_ui_title(name=self.project_filename)
  6958. self.should_we_save = False
  6959. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6960. """
  6961. Callback for menu item File->Save Project As... Opens a file
  6962. chooser and saves the project to the given file via
  6963. ``self.save_project()``.
  6964. :param make_copy if to be create a copy of the project; boolean
  6965. :param use_thread: if to be run in a separate thread; boolean
  6966. :param quit_action: if to be followed by quiting the application; boolean
  6967. :return: None
  6968. """
  6969. self.defaults.report_usage("on_file_saveprojectas")
  6970. self.date = str(datetime.today()).rpartition('.')[0]
  6971. self.date = ''.join(c for c in self.date if c not in ':-')
  6972. self.date = self.date.replace(' ', '_')
  6973. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6974. try:
  6975. filename, _f = FCFileSaveDialog.get_saved_filename(
  6976. caption=_("Save Project As ..."),
  6977. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6978. proj=_("Project")),
  6979. filter=filter_
  6980. )
  6981. except TypeError:
  6982. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6983. filename = str(filename)
  6984. if filename == '':
  6985. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6986. return
  6987. if use_thread is True:
  6988. self.worker_task.emit({'fcn': self.save_project,
  6989. 'params': [filename, quit_action]})
  6990. else:
  6991. self.save_project(filename, quit_action)
  6992. # self.save_project(filename)
  6993. if self.defaults["global_open_style"] is False:
  6994. self.file_opened.emit("project", filename)
  6995. self.file_saved.emit("project", filename)
  6996. if not make_copy:
  6997. self.project_filename = filename
  6998. self.set_ui_title(name=self.project_filename)
  6999. self.should_we_save = False
  7000. def on_file_save_objects_pdf(self, use_thread=True):
  7001. self.date = str(datetime.today()).rpartition('.')[0]
  7002. self.date = ''.join(c for c in self.date if c not in ':-')
  7003. self.date = self.date.replace(' ', '_')
  7004. try:
  7005. obj_selection = self.collection.get_selected()
  7006. if len(obj_selection) == 1:
  7007. obj_name = str(obj_selection[0].options['name'])
  7008. else:
  7009. obj_name = _("FlatCAM objects print")
  7010. except AttributeError as err:
  7011. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7012. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7013. return
  7014. if not obj_selection:
  7015. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7016. return
  7017. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7018. try:
  7019. filename, _f = FCFileSaveDialog.get_saved_filename(
  7020. caption=_("Save Object as PDF ..."),
  7021. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7022. obj_name=obj_name,
  7023. date=self.date),
  7024. filter=filter_
  7025. )
  7026. except TypeError:
  7027. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7028. filename = str(filename)
  7029. if filename == '':
  7030. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7031. return
  7032. if use_thread is True:
  7033. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  7034. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7035. else:
  7036. self.save_pdf(filename, obj_selection)
  7037. # self.save_project(filename)
  7038. if self.defaults["global_open_style"] is False:
  7039. self.file_opened.emit("pdf", filename)
  7040. self.file_saved.emit("pdf", filename)
  7041. def save_pdf(self, file_name, obj_selection):
  7042. p_size = self.defaults['global_workspaceT']
  7043. orientation = self.defaults['global_workspace_orientation']
  7044. color = 'black'
  7045. transparency_level = 1.0
  7046. self.pagesize = {}
  7047. self.pagesize.update(
  7048. {
  7049. 'Bounds': None,
  7050. 'A0': (841 * mm, 1189 * mm),
  7051. 'A1': (594 * mm, 841 * mm),
  7052. 'A2': (420 * mm, 594 * mm),
  7053. 'A3': (297 * mm, 420 * mm),
  7054. 'A4': (210 * mm, 297 * mm),
  7055. 'A5': (148 * mm, 210 * mm),
  7056. 'A6': (105 * mm, 148 * mm),
  7057. 'A7': (74 * mm, 105 * mm),
  7058. 'A8': (52 * mm, 74 * mm),
  7059. 'A9': (37 * mm, 52 * mm),
  7060. 'A10': (26 * mm, 37 * mm),
  7061. 'B0': (1000 * mm, 1414 * mm),
  7062. 'B1': (707 * mm, 1000 * mm),
  7063. 'B2': (500 * mm, 707 * mm),
  7064. 'B3': (353 * mm, 500 * mm),
  7065. 'B4': (250 * mm, 353 * mm),
  7066. 'B5': (176 * mm, 250 * mm),
  7067. 'B6': (125 * mm, 176 * mm),
  7068. 'B7': (88 * mm, 125 * mm),
  7069. 'B8': (62 * mm, 88 * mm),
  7070. 'B9': (44 * mm, 62 * mm),
  7071. 'B10': (31 * mm, 44 * mm),
  7072. 'C0': (917 * mm, 1297 * mm),
  7073. 'C1': (648 * mm, 917 * mm),
  7074. 'C2': (458 * mm, 648 * mm),
  7075. 'C3': (324 * mm, 458 * mm),
  7076. 'C4': (229 * mm, 324 * mm),
  7077. 'C5': (162 * mm, 229 * mm),
  7078. 'C6': (114 * mm, 162 * mm),
  7079. 'C7': (81 * mm, 114 * mm),
  7080. 'C8': (57 * mm, 81 * mm),
  7081. 'C9': (40 * mm, 57 * mm),
  7082. 'C10': (28 * mm, 40 * mm),
  7083. # American paper sizes
  7084. 'LETTER': (8.5 * inch, 11 * inch),
  7085. 'LEGAL': (8.5 * inch, 14 * inch),
  7086. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7087. # From https://en.wikipedia.org/wiki/Paper_size
  7088. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7089. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7090. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7091. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7092. 'LEDGER': (17 * inch, 11 * inch),
  7093. }
  7094. )
  7095. exported_svg = []
  7096. for obj in obj_selection:
  7097. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7098. scale_factor_x=None, scale_factor_y=None,
  7099. skew_factor_x=None, skew_factor_y=None,
  7100. mirror=None)
  7101. if obj.kind.lower() == 'gerber':
  7102. # color = self.defaults["gerber_plot_fill"][:-2]
  7103. color = obj.fill_color[:-2]
  7104. elif obj.kind.lower() == 'excellon':
  7105. color = '#C40000'
  7106. elif obj.kind.lower() == 'geometry':
  7107. color = self.defaults["global_draw_color"]
  7108. # Change the attributes of the exported SVG
  7109. # We don't need stroke-width
  7110. # We set opacity to maximum
  7111. # We set the colour to WHITE
  7112. root = ET.fromstring(svg_obj)
  7113. for child in root:
  7114. child.set('fill', str(color))
  7115. child.set('opacity', str(transparency_level))
  7116. child.set('stroke', str(color))
  7117. exported_svg.append(ET.tostring(root))
  7118. xmin = Inf
  7119. ymin = Inf
  7120. xmax = -Inf
  7121. ymax = -Inf
  7122. for obj in obj_selection:
  7123. try:
  7124. gxmin, gymin, gxmax, gymax = obj.bounds()
  7125. xmin = min([xmin, gxmin])
  7126. ymin = min([ymin, gymin])
  7127. xmax = max([xmax, gxmax])
  7128. ymax = max([ymax, gymax])
  7129. except Exception as e:
  7130. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7131. # Determine bounding area for svg export
  7132. bounds = [xmin, ymin, xmax, ymax]
  7133. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7134. # This contain the measure units
  7135. uom = obj_selection[0].units.lower()
  7136. # Define a boundary around SVG of about 1.0mm (~39mils)
  7137. if uom in "mm":
  7138. boundary = 1.0
  7139. else:
  7140. boundary = 0.0393701
  7141. # Convert everything to strings for use in the xml doc
  7142. svgwidth = str(size[0] + (2 * boundary))
  7143. svgheight = str(size[1] + (2 * boundary))
  7144. minx = str(bounds[0] - boundary)
  7145. miny = str(bounds[1] + boundary + size[1])
  7146. # Add a SVG Header and footer to the svg output from shapely
  7147. # The transform flips the Y Axis so that everything renders
  7148. # properly within svg apps such as inkscape
  7149. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7150. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7151. svg_header += 'width="' + svgwidth + uom + '" '
  7152. svg_header += 'height="' + svgheight + uom + '" '
  7153. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7154. svg_header += '>'
  7155. svg_header += '<g transform="scale(1,-1)">'
  7156. svg_footer = '</g> </svg>'
  7157. svg_elem = str(svg_header)
  7158. for svg_item in exported_svg:
  7159. svg_elem += str(svg_item)
  7160. svg_elem += str(svg_footer)
  7161. # Parse the xml through a xml parser just to add line feeds
  7162. # and to make it look more pretty for the output
  7163. doc = parse_xml_string(svg_elem)
  7164. doc_final = doc.toprettyxml()
  7165. try:
  7166. if self.defaults['units'].upper() == 'IN':
  7167. unit = inch
  7168. else:
  7169. unit = mm
  7170. doc_final = StringIO(doc_final)
  7171. drawing = svg2rlg(doc_final)
  7172. if p_size == 'Bounds':
  7173. renderPDF.drawToFile(drawing, file_name)
  7174. else:
  7175. if orientation == 'p':
  7176. page_size = portrait(self.pagesize[p_size])
  7177. else:
  7178. page_size = landscape(self.pagesize[p_size])
  7179. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7180. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7181. renderPDF.draw(drawing, my_canvas, 0, 0)
  7182. my_canvas.save()
  7183. except Exception as e:
  7184. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7185. return 'fail'
  7186. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7187. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7188. """
  7189. Exports a Geometry Object to an SVG file.
  7190. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7191. :param filename: Path to the SVG file to save to.
  7192. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7193. :return:
  7194. """
  7195. self.defaults.report_usage("export_svg()")
  7196. if filename is None:
  7197. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7198. is not None else self.defaults["global_last_folder"]
  7199. self.log.debug("export_svg()")
  7200. try:
  7201. obj = self.collection.get_by_name(str(obj_name))
  7202. except Exception:
  7203. # TODO: The return behavior has not been established... should raise exception?
  7204. return "Could not retrieve object: %s" % obj_name
  7205. with self.proc_container.new(_("Exporting SVG")) as proc:
  7206. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7207. # Determine bounding area for svg export
  7208. bounds = obj.bounds()
  7209. size = obj.size()
  7210. # Convert everything to strings for use in the xml doc
  7211. svgwidth = str(size[0])
  7212. svgheight = str(size[1])
  7213. minx = str(bounds[0])
  7214. miny = str(bounds[1] - size[1])
  7215. uom = obj.units.lower()
  7216. # Add a SVG Header and footer to the svg output from shapely
  7217. # The transform flips the Y Axis so that everything renders
  7218. # properly within svg apps such as inkscape
  7219. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7220. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7221. svg_header += 'width="' + svgwidth + uom + '" '
  7222. svg_header += 'height="' + svgheight + uom + '" '
  7223. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7224. svg_header += '<g transform="scale(1,-1)">'
  7225. svg_footer = '</g> </svg>'
  7226. svg_elem = svg_header + exported_svg + svg_footer
  7227. # Parse the xml through a xml parser just to add line feeds
  7228. # and to make it look more pretty for the output
  7229. svgcode = parse_xml_string(svg_elem)
  7230. svgcode = svgcode.toprettyxml()
  7231. try:
  7232. with open(filename, 'w') as fp:
  7233. fp.write(svgcode)
  7234. except PermissionError:
  7235. self.inform.emit('[WARNING] %s' %
  7236. _("Permission denied, saving not possible.\n"
  7237. "Most likely another app is holding the file open and not accessible."))
  7238. return 'fail'
  7239. if self.defaults["global_open_style"] is False:
  7240. self.file_opened.emit("SVG", filename)
  7241. self.file_saved.emit("SVG", filename)
  7242. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7243. def save_source_file(self, obj_name, filename, use_thread=True):
  7244. """
  7245. Exports a FlatCAM Object to an Gerber/Excellon file.
  7246. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7247. :param filename: Path to the Gerber file to save to.
  7248. :param use_thread: if to be run in a separate thread
  7249. :return:
  7250. """
  7251. self.defaults.report_usage("save source file()")
  7252. if filename is None:
  7253. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7254. is not None else self.defaults["global_last_folder"]
  7255. self.log.debug("save source file()")
  7256. obj = self.collection.get_by_name(obj_name)
  7257. file_string = StringIO(obj.source_file)
  7258. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7259. if file_string.getvalue() == '':
  7260. self.inform.emit('[ERROR_NOTCL] %s' %
  7261. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7262. return 'fail'
  7263. try:
  7264. with open(filename, 'w') as file:
  7265. file.writelines('G04*\n')
  7266. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7267. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7268. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7269. file.writelines('G04 Created on : %s*\n' % time_string)
  7270. for line in file_string:
  7271. file.writelines(line)
  7272. except PermissionError:
  7273. self.inform.emit('[WARNING] %s' %
  7274. _("Permission denied, saving not possible.\n"
  7275. "Most likely another app is holding the file open and not accessible."))
  7276. return 'fail'
  7277. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7278. """
  7279. Exports a Excellon Object to an Excellon file.
  7280. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7281. :param filename: Path to the Excellon file to save to.
  7282. :param local_use:
  7283. :param use_thread: if to be run in a separate thread
  7284. :return:
  7285. """
  7286. self.defaults.report_usage("export_excellon()")
  7287. if filename is None:
  7288. if self.defaults["global_last_save_folder"]:
  7289. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7290. else:
  7291. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7292. self.log.debug("export_excellon()")
  7293. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7294. self.defaults["excellon_exp_decimals"]
  7295. )
  7296. if local_use is None:
  7297. try:
  7298. obj = self.collection.get_by_name(str(obj_name))
  7299. except Exception:
  7300. return "Could not retrieve object: %s" % obj_name
  7301. else:
  7302. obj = local_use
  7303. if not isinstance(obj, ExcellonObject):
  7304. self.inform.emit('[ERROR_NOTCL] %s' %
  7305. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7306. return
  7307. # updated units
  7308. eunits = self.defaults["excellon_exp_units"]
  7309. ewhole = self.defaults["excellon_exp_integer"]
  7310. efract = self.defaults["excellon_exp_decimals"]
  7311. ezeros = self.defaults["excellon_exp_zeros"]
  7312. eformat = self.defaults["excellon_exp_format"]
  7313. slot_type = self.defaults["excellon_exp_slot_type"]
  7314. fc_units = self.defaults['units'].upper()
  7315. if fc_units == 'MM':
  7316. factor = 1 if eunits == 'METRIC' else 0.03937
  7317. else:
  7318. factor = 25.4 if eunits == 'METRIC' else 1
  7319. def make_excellon():
  7320. try:
  7321. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7322. header = 'M48\n'
  7323. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7324. (str(self.version), str(self.version_date))
  7325. header += ';Filename: %s' % str(obj_name) + '\n'
  7326. header += ';Created on : %s' % time_str + '\n'
  7327. if eformat == 'dec':
  7328. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7329. header += eunits + '\n'
  7330. for tool in obj.tools:
  7331. if eunits == 'METRIC':
  7332. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7333. tool=str(tool),
  7334. dec=2)
  7335. else:
  7336. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7337. tool=str(tool),
  7338. dec=4)
  7339. else:
  7340. if ezeros == 'LZ':
  7341. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7342. form='ndec', e_zeros='LZ', factor=factor,
  7343. slot_type=slot_type)
  7344. header += '%s,%s\n' % (eunits, 'LZ')
  7345. header += format_exc
  7346. for tool in obj.tools:
  7347. if eunits == 'METRIC':
  7348. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7349. tool=str(tool),
  7350. dec=2)
  7351. else:
  7352. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7353. tool=str(tool),
  7354. dec=4)
  7355. else:
  7356. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7357. form='ndec', e_zeros='TZ', factor=factor,
  7358. slot_type=slot_type)
  7359. header += '%s,%s\n' % (eunits, 'TZ')
  7360. header += format_exc
  7361. for tool in obj.tools:
  7362. if eunits == 'METRIC':
  7363. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7364. tool=str(tool),
  7365. dec=2)
  7366. else:
  7367. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7368. tool=str(tool),
  7369. dec=4)
  7370. header += '%\n'
  7371. footer = 'M30\n'
  7372. exported_excellon = header
  7373. exported_excellon += excellon_code
  7374. exported_excellon += footer
  7375. if local_use is None:
  7376. try:
  7377. with open(filename, 'w') as fp:
  7378. fp.write(exported_excellon)
  7379. except PermissionError:
  7380. self.inform.emit('[WARNING] %s' %
  7381. _("Permission denied, saving not possible.\n"
  7382. "Most likely another app is holding the file open and not accessible."))
  7383. return 'fail'
  7384. if self.defaults["global_open_style"] is False:
  7385. self.file_opened.emit("Excellon", filename)
  7386. self.file_saved.emit("Excellon", filename)
  7387. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7388. else:
  7389. return exported_excellon
  7390. except Exception as e:
  7391. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7392. return 'fail'
  7393. if use_thread is True:
  7394. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7395. def job_thread_exc(app_obj):
  7396. ret = make_excellon()
  7397. if ret == 'fail':
  7398. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7399. return
  7400. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7401. else:
  7402. eret = make_excellon()
  7403. if eret == 'fail':
  7404. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7405. return 'fail'
  7406. if local_use is not None:
  7407. return eret
  7408. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7409. """
  7410. Exports a Gerber Object to an Gerber file.
  7411. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7412. :param filename: Path to the Gerber file to save to.
  7413. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7414. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7415. :param use_thread: if to be run in a separate thread
  7416. :return:
  7417. """
  7418. self.defaults.report_usage("export_gerber()")
  7419. if filename is None:
  7420. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7421. is not None else self.defaults["global_last_folder"]
  7422. self.log.debug("export_gerber()")
  7423. if local_use is None:
  7424. try:
  7425. obj = self.collection.get_by_name(str(obj_name))
  7426. except Exception:
  7427. return "Could not retrieve object: %s" % obj_name
  7428. else:
  7429. obj = local_use
  7430. # updated units
  7431. gunits = self.defaults["gerber_exp_units"]
  7432. gwhole = self.defaults["gerber_exp_integer"]
  7433. gfract = self.defaults["gerber_exp_decimals"]
  7434. gzeros = self.defaults["gerber_exp_zeros"]
  7435. fc_units = self.defaults['units'].upper()
  7436. if fc_units == 'MM':
  7437. factor = 1 if gunits == 'MM' else 0.03937
  7438. else:
  7439. factor = 25.4 if gunits == 'MM' else 1
  7440. def make_gerber():
  7441. try:
  7442. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7443. header = 'G04*\n'
  7444. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7445. (str(self.version), str(self.version_date))
  7446. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7447. header += 'G04 Created on : %s*' % time_str + '\n'
  7448. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7449. header += "%MO{units}*%\n".format(units=gunits)
  7450. for apid in obj.apertures:
  7451. if obj.apertures[apid]['type'] == 'C':
  7452. header += "%ADD{apid}{type},{size}*%\n".format(
  7453. apid=str(apid),
  7454. type='C',
  7455. size=(factor * obj.apertures[apid]['size'])
  7456. )
  7457. elif obj.apertures[apid]['type'] == 'R':
  7458. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7459. apid=str(apid),
  7460. type='R',
  7461. width=(factor * obj.apertures[apid]['width']),
  7462. height=(factor * obj.apertures[apid]['height'])
  7463. )
  7464. elif obj.apertures[apid]['type'] == 'O':
  7465. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7466. apid=str(apid),
  7467. type='O',
  7468. width=(factor * obj.apertures[apid]['width']),
  7469. height=(factor * obj.apertures[apid]['height'])
  7470. )
  7471. header += '\n'
  7472. # obsolete units but some software may need it
  7473. if gunits == 'IN':
  7474. header += 'G70*\n'
  7475. else:
  7476. header += 'G71*\n'
  7477. # Absolute Mode
  7478. header += 'G90*\n'
  7479. header += 'G01*\n'
  7480. # positive polarity
  7481. header += '%LPD*%\n'
  7482. footer = 'M02*\n'
  7483. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7484. exported_gerber = header
  7485. exported_gerber += gerber_code
  7486. exported_gerber += footer
  7487. if local_use is None:
  7488. try:
  7489. with open(filename, 'w') as fp:
  7490. fp.write(exported_gerber)
  7491. except PermissionError:
  7492. self.inform.emit('[WARNING] %s' %
  7493. _("Permission denied, saving not possible.\n"
  7494. "Most likely another app is holding the file open and not accessible."))
  7495. return 'fail'
  7496. if self.defaults["global_open_style"] is False:
  7497. self.file_opened.emit("Gerber", filename)
  7498. self.file_saved.emit("Gerber", filename)
  7499. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7500. else:
  7501. return exported_gerber
  7502. except Exception as e:
  7503. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7504. return 'fail'
  7505. if use_thread is True:
  7506. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7507. def job_thread_grb(app_obj):
  7508. ret = make_gerber()
  7509. if ret == 'fail':
  7510. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7511. return
  7512. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7513. else:
  7514. gret = make_gerber()
  7515. if gret == 'fail':
  7516. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7517. return 'fail'
  7518. if local_use is not None:
  7519. return gret
  7520. def export_dxf(self, obj_name, filename, use_thread=True):
  7521. """
  7522. Exports a Geometry Object to an DXF file.
  7523. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7524. :param filename: Path to the DXF file to save to.
  7525. :param use_thread: if to be run in a separate thread
  7526. :return:
  7527. """
  7528. self.defaults.report_usage("export_dxf()")
  7529. if filename is None:
  7530. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7531. is not None else self.defaults["global_last_folder"]
  7532. self.log.debug("export_dxf()")
  7533. try:
  7534. obj = self.collection.get_by_name(str(obj_name))
  7535. except Exception:
  7536. # TODO: The return behavior has not been established... should raise exception?
  7537. return "Could not retrieve object: %s" % obj_name
  7538. def make_dxf():
  7539. try:
  7540. dxf_code = obj.export_dxf()
  7541. dxf_code.saveas(filename)
  7542. if self.defaults["global_open_style"] is False:
  7543. self.file_opened.emit("DXF", filename)
  7544. self.file_saved.emit("DXF", filename)
  7545. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7546. except Exception:
  7547. return 'fail'
  7548. if use_thread is True:
  7549. with self.proc_container.new(_("Exporting DXF")) as proc:
  7550. def job_thread_exc(app_obj):
  7551. ret_dxf_val = make_dxf()
  7552. if ret_dxf_val == 'fail':
  7553. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7554. return
  7555. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7556. else:
  7557. ret = make_dxf()
  7558. if ret == 'fail':
  7559. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7560. return
  7561. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7562. """
  7563. Adds a new Geometry Object to the projects and populates
  7564. it with shapes extracted from the SVG file.
  7565. :param filename: Path to the SVG file.
  7566. :param geo_type: Type of FlatCAM object that will be created from SVG
  7567. :param outname:
  7568. :return:
  7569. """
  7570. self.defaults.report_usage("import_svg()")
  7571. log.debug("App.import_svg()")
  7572. obj_type = ""
  7573. if geo_type is None or geo_type == "geometry":
  7574. obj_type = "geometry"
  7575. elif geo_type == "gerber":
  7576. obj_type = "gerber"
  7577. else:
  7578. self.inform.emit('[ERROR_NOTCL] %s' %
  7579. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7580. return
  7581. units = self.defaults['units'].upper()
  7582. def obj_init(geo_obj, app_obj):
  7583. geo_obj.import_svg(filename, obj_type, units=units)
  7584. geo_obj.multigeo = False
  7585. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7586. with self.proc_container.new(_("Importing SVG")) as proc:
  7587. # Object name
  7588. name = outname or filename.split('/')[-1].split('\\')[-1]
  7589. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7590. if ret == 'fail':
  7591. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7592. return 'fail'
  7593. # Register recent file
  7594. self.file_opened.emit("svg", filename)
  7595. # GUI feedback
  7596. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7597. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7598. """
  7599. Adds a new Geometry Object to the projects and populates
  7600. it with shapes extracted from the DXF file.
  7601. :param filename: Path to the DXF file.
  7602. :param geo_type: Type of FlatCAM object that will be created from DXF
  7603. :param outname: Name for the imported Geometry
  7604. :return:
  7605. """
  7606. self.defaults.report_usage("import_dxf()")
  7607. obj_type = ""
  7608. if geo_type is None or geo_type == "geometry":
  7609. obj_type = "geometry"
  7610. elif geo_type == "gerber":
  7611. obj_type = geo_type
  7612. else:
  7613. self.inform.emit('[ERROR_NOTCL] %s' %
  7614. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7615. return
  7616. units = self.defaults['units'].upper()
  7617. def obj_init(geo_obj, app_obj):
  7618. geo_obj.import_dxf(filename, obj_type, units=units)
  7619. geo_obj.multigeo = False
  7620. with self.proc_container.new(_("Importing DXF")):
  7621. # Object name
  7622. name = outname or filename.split('/')[-1].split('\\')[-1]
  7623. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7624. if ret == 'fail':
  7625. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7626. return 'fail'
  7627. # Register recent file
  7628. self.file_opened.emit("dxf", filename)
  7629. # GUI feedback
  7630. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7631. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7632. """
  7633. Opens a Gerber file, parses it and creates a new object for
  7634. it in the program. Thread-safe.
  7635. :param outname: Name of the resulting object. None causes the
  7636. name to be that of the file. Str.
  7637. :param filename: Gerber file filename
  7638. :type filename: str
  7639. :param plot: boolean, to plot or not the resulting object
  7640. :param from_tcl: True if run from Tcl Shell
  7641. :return: None
  7642. """
  7643. # How the object should be initialized
  7644. def obj_init(gerber_obj, app_obj):
  7645. assert isinstance(gerber_obj, GerberObject), \
  7646. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7647. # Opening the file happens here
  7648. try:
  7649. gerber_obj.parse_file(filename)
  7650. except IOError:
  7651. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7652. return "fail"
  7653. except ParseError as err:
  7654. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7655. app_obj.log.error(str(err))
  7656. return "fail"
  7657. except Exception as e:
  7658. log.debug("App.open_gerber() --> %s" % str(e))
  7659. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7660. msg += traceback.format_exc()
  7661. app_obj.inform.emit(msg)
  7662. return "fail"
  7663. if gerber_obj.is_empty():
  7664. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7665. _("Object is not Gerber file or empty. Aborting object creation."))
  7666. return "fail"
  7667. App.log.debug("open_gerber()")
  7668. with self.proc_container.new(_("Opening Gerber")):
  7669. # Object name
  7670. name = outname or filename.split('/')[-1].split('\\')[-1]
  7671. # # ## Object creation # ##
  7672. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7673. if ret_val == 'fail':
  7674. if from_tcl:
  7675. filename = self.defaults['global_tcl_path'] + '/' + name
  7676. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7677. if ret_val == 'fail':
  7678. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7679. return 'fail'
  7680. # Register recent file
  7681. self.file_opened.emit("gerber", filename)
  7682. # GUI feedback
  7683. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7684. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7685. """
  7686. Opens an Excellon file, parses it and creates a new object for
  7687. it in the program. Thread-safe.
  7688. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7689. :param filename: Excellon file filename
  7690. :type filename: str
  7691. :param plot: boolean, to plot or not the resulting object
  7692. :param from_tcl: True if run from Tcl Shell
  7693. :return: None
  7694. """
  7695. App.log.debug("open_excellon()")
  7696. # How the object should be initialized
  7697. def obj_init(excellon_obj, app_obj):
  7698. try:
  7699. ret = excellon_obj.parse_file(filename=filename)
  7700. if ret == "fail":
  7701. log.debug("Excellon parsing failed.")
  7702. self.inform.emit('[ERROR_NOTCL] %s' %
  7703. _("This is not Excellon file."))
  7704. return "fail"
  7705. except IOError:
  7706. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7707. (_("Cannot open file"), filename))
  7708. log.debug("Could not open Excellon object.")
  7709. return "fail"
  7710. except Exception:
  7711. msg = '[ERROR_NOTCL] %s' % \
  7712. _("An internal error has occurred. See shell.\n")
  7713. msg += traceback.format_exc()
  7714. app_obj.inform.emit(msg)
  7715. return "fail"
  7716. ret = excellon_obj.create_geometry()
  7717. if ret == 'fail':
  7718. log.debug("Could not create geometry for Excellon object.")
  7719. return "fail"
  7720. for tool in excellon_obj.tools:
  7721. if excellon_obj.tools[tool]['solid_geometry']:
  7722. return
  7723. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7724. return "fail"
  7725. with self.proc_container.new(_("Opening Excellon.")):
  7726. # Object name
  7727. name = outname or filename.split('/')[-1].split('\\')[-1]
  7728. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7729. if ret_val == 'fail':
  7730. if from_tcl:
  7731. filename = self.defaults['global_tcl_path'] + '/' + name
  7732. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7733. if ret_val == 'fail':
  7734. self.inform.emit('[ERROR_NOTCL] %s' %
  7735. _('Open Excellon file failed. Probable not an Excellon file.'))
  7736. return
  7737. # Register recent file
  7738. self.file_opened.emit("excellon", filename)
  7739. # GUI feedback
  7740. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7741. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7742. """
  7743. Opens a G-gcode file, parses it and creates a new object for
  7744. it in the program. Thread-safe.
  7745. :param filename: G-code file filename
  7746. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7747. :param force_parsing:
  7748. :param plot: If True plot the object on canvas
  7749. :param from_tcl: True if run from Tcl Shell
  7750. :return: None
  7751. """
  7752. App.log.debug("open_gcode()")
  7753. # How the object should be initialized
  7754. def obj_init(job_obj, app_obj_):
  7755. """
  7756. :param job_obj: the resulting object
  7757. :type app_obj_: App
  7758. """
  7759. assert isinstance(app_obj_, App), \
  7760. "Initializer expected App, got %s" % type(app_obj_)
  7761. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7762. try:
  7763. f = open(filename)
  7764. gcode = f.read()
  7765. f.close()
  7766. except IOError:
  7767. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7768. return "fail"
  7769. job_obj.gcode = gcode
  7770. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7771. if gcode_ret == "fail":
  7772. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7773. return "fail"
  7774. job_obj.create_geometry()
  7775. with self.proc_container.new(_("Opening G-Code.")):
  7776. # Object name
  7777. name = outname or filename.split('/')[-1].split('\\')[-1]
  7778. # New object creation and file processing
  7779. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7780. if ret_val == 'fail':
  7781. if from_tcl:
  7782. filename = self.defaults['global_tcl_path'] + '/' + name
  7783. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7784. if ret_val == 'fail':
  7785. self.inform.emit('[ERROR_NOTCL] %s' %
  7786. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7787. "Try to load it from File menu.\n "
  7788. "Attempting to create a FlatCAM CNCJob Object from "
  7789. "G-Code file failed during processing"))
  7790. return "fail"
  7791. # Register recent file
  7792. self.file_opened.emit("cncjob", filename)
  7793. # GUI feedback
  7794. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7795. def open_hpgl2(self, filename, outname=None):
  7796. """
  7797. Opens a HPGL2 file, parses it and creates a new object for
  7798. it in the program. Thread-safe.
  7799. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7800. :param filename: HPGL2 file filename
  7801. :return: None
  7802. """
  7803. filename = filename
  7804. # How the object should be initialized
  7805. def obj_init(geo_obj, app_obj):
  7806. assert isinstance(geo_obj, GeometryObject), \
  7807. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7808. # Opening the file happens here
  7809. obj = HPGL2(self)
  7810. try:
  7811. HPGL2.parse_file(obj, filename)
  7812. except IOError:
  7813. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7814. return "fail"
  7815. except ParseError as err:
  7816. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7817. app_obj.log.error(str(err))
  7818. return "fail"
  7819. except Exception as e:
  7820. log.debug("App.open_hpgl2() --> %s" % str(e))
  7821. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7822. msg += traceback.format_exc()
  7823. app_obj.inform.emit(msg)
  7824. return "fail"
  7825. geo_obj.multigeo = True
  7826. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7827. geo_obj.tools = deepcopy(obj.tools)
  7828. geo_obj.source_file = deepcopy(obj.source_file)
  7829. del obj
  7830. if not geo_obj.solid_geometry:
  7831. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7832. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7833. return "fail"
  7834. App.log.debug("open_hpgl2()")
  7835. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7836. # Object name
  7837. name = outname or filename.split('/')[-1].split('\\')[-1]
  7838. # # ## Object creation # ##
  7839. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7840. if ret == 'fail':
  7841. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7842. return 'fail'
  7843. # Register recent file
  7844. self.file_opened.emit("geometry", filename)
  7845. # GUI feedback
  7846. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7847. def open_script(self, filename, outname=None, silent=False):
  7848. """
  7849. Opens a Script file, parses it and creates a new object for
  7850. it in the program. Thread-safe.
  7851. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7852. :param filename: Script file filename
  7853. :return: None
  7854. """
  7855. App.log.debug("open_script()")
  7856. with self.proc_container.new(_("Opening TCL Script...")):
  7857. try:
  7858. with open(filename, "r") as opened_script:
  7859. script_content = opened_script.readlines()
  7860. script_content = ''.join(script_content)
  7861. if silent is False:
  7862. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7863. except Exception as e:
  7864. log.debug("App.open_script() -> %s" % str(e))
  7865. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7866. return
  7867. # Object name
  7868. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7869. # New object creation and file processing
  7870. self.on_filenewscript(name=script_name, text=script_content)
  7871. # Register recent file
  7872. self.file_opened.emit("script", filename)
  7873. # GUI feedback
  7874. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7875. def open_config_file(self, filename, run_from_arg=None):
  7876. """
  7877. Loads a config file from the specified file.
  7878. :param filename: Name of the file from which to load.
  7879. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7880. :return: None
  7881. """
  7882. App.log.debug("Opening config file: " + filename)
  7883. if run_from_arg:
  7884. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7885. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7886. _("Opening FlatCAM Config file.")),
  7887. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7888. color=QtGui.QColor("gray"))
  7889. # # add the tab if it was closed
  7890. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7891. # # first clear previous text in text editor (if any)
  7892. # self.ui.text_editor_tab.code_editor.clear()
  7893. #
  7894. # # Switch plot_area to CNCJob tab
  7895. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7896. # close the Code editor if already open
  7897. if self.toggle_codeeditor:
  7898. self.on_toggle_code_editor()
  7899. self.on_toggle_code_editor()
  7900. try:
  7901. if filename:
  7902. f = QtCore.QFile(filename)
  7903. if f.open(QtCore.QIODevice.ReadOnly):
  7904. stream = QtCore.QTextStream(f)
  7905. code_edited = stream.readAll()
  7906. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7907. f.close()
  7908. except IOError:
  7909. App.log.error("Failed to open config file: %s" % filename)
  7910. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7911. (_("Failed to open config file"), filename))
  7912. return
  7913. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7914. """
  7915. Loads a project from the specified file.
  7916. 1) Loads and parses file
  7917. 2) Registers the file as recently opened.
  7918. 3) Calls on_file_new()
  7919. 4) Updates options
  7920. 5) Calls new_object() with the object's from_dict() as init method.
  7921. 6) Calls plot_all() if plot=True
  7922. :param filename: Name of the file from which to load.
  7923. :param run_from_arg: True if run for arguments
  7924. :param plot: If True plot all objects in the project
  7925. :param cli: Run from command line
  7926. :param from_tcl: True if run from Tcl Sehll
  7927. :return: None
  7928. """
  7929. App.log.debug("Opening project: " + filename)
  7930. # block autosaving while a project is loaded
  7931. self.block_autosave = True
  7932. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7933. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7934. if cli is None:
  7935. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7936. if run_from_arg:
  7937. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7938. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7939. _("Opening FlatCAM Project file.")),
  7940. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7941. color=QtGui.QColor("gray"))
  7942. # Open and parse an uncompressed Project file
  7943. try:
  7944. f = open(filename, 'r')
  7945. except IOError:
  7946. if from_tcl:
  7947. name = filename.split('/')[-1].split('\\')[-1]
  7948. filename = self.defaults['global_tcl_path'] + '/' + name
  7949. try:
  7950. f = open(filename, 'r')
  7951. except IOError:
  7952. log.error("Failed to open project file: %s" % filename)
  7953. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7954. return
  7955. else:
  7956. log.error("Failed to open project file: %s" % filename)
  7957. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7958. return
  7959. try:
  7960. d = json.load(f, object_hook=dict2obj)
  7961. except Exception as e:
  7962. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7963. (filename, str(e)))
  7964. f.close()
  7965. # Open and parse a compressed Project file
  7966. try:
  7967. with lzma.open(filename) as f:
  7968. file_content = f.read().decode('utf-8')
  7969. d = json.loads(file_content, object_hook=dict2obj)
  7970. except Exception as e:
  7971. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7972. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7973. (_("Failed to open project file"), filename))
  7974. return
  7975. # Clear the current project
  7976. # # NOT THREAD SAFE # ##
  7977. if run_from_arg is True:
  7978. pass
  7979. elif cli is True:
  7980. self.delete_selection_shape()
  7981. else:
  7982. self.on_file_new()
  7983. # Project options
  7984. self.options.update(d['options'])
  7985. self.project_filename = filename
  7986. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7987. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7988. if cli is None:
  7989. self.set_screen_units(self.options["units"])
  7990. # Re create objects
  7991. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7992. for obj in d['objs']:
  7993. try:
  7994. def obj_init(obj_inst, app_inst):
  7995. obj_inst.from_dict(obj)
  7996. App.log.debug("Recreating from opened project an %s object: %s" %
  7997. (obj['kind'].capitalize(), obj['options']['name']))
  7998. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7999. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8000. if cli is None:
  8001. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8002. obj['kind'].upper(),
  8003. obj['options']['name']
  8004. )
  8005. )
  8006. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8007. except Exception as e:
  8008. print('App.open_project() --> ' + str(e))
  8009. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8010. self.should_we_save = False
  8011. self.file_opened.emit("project", filename)
  8012. # restore autosaving after a project was loaded
  8013. self.block_autosave = False
  8014. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8015. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8016. if cli is None:
  8017. self.set_ui_title(name=self.project_filename)
  8018. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8019. def plot_all(self, fit_view=True, use_thread=True):
  8020. """
  8021. Re-generates all plots from all objects.
  8022. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8023. :param use_thread: if True will use threading for plotting the objects
  8024. :return: None
  8025. """
  8026. self.log.debug("Plot_all()")
  8027. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8028. for plot_obj in self.collection.get_list():
  8029. def worker_task(obj):
  8030. with self.proc_container.new("Plotting"):
  8031. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8032. if fit_view is True:
  8033. self.object_plotted.emit(obj)
  8034. if use_thread is True:
  8035. # Send to worker
  8036. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8037. else:
  8038. worker_task(plot_obj)
  8039. def register_folder(self, filename):
  8040. """
  8041. Register the last folder used by the app to open something
  8042. :param filename: the last folder is extracted from the filename
  8043. :return: None
  8044. """
  8045. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8046. def register_save_folder(self, filename):
  8047. """
  8048. Register the last folder used by the app to save something
  8049. :param filename: the last folder is extracted from the filename
  8050. :return: None
  8051. """
  8052. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8053. # def set_progress_bar(self, percentage, text=""):
  8054. # """
  8055. # Set a progress bar to a value (percentage)
  8056. #
  8057. # :param percentage: Value set to the progressbar
  8058. # :param text: Not used
  8059. # :return: None
  8060. # """
  8061. # self.ui.progress_bar.setValue(int(percentage))
  8062. def setup_recent_items(self):
  8063. """
  8064. Setup a dictionary with the recent files accessed, organized by type
  8065. :return:
  8066. """
  8067. icons = {
  8068. "gerber": self.resource_location + "/flatcam_icon16.png",
  8069. "excellon": self.resource_location + "/drill16.png",
  8070. 'geometry': self.resource_location + "/geometry16.png",
  8071. "cncjob": self.resource_location + "/cnc16.png",
  8072. "script": self.resource_location + "/script_new24.png",
  8073. "document": self.resource_location + "/notes16_1.png",
  8074. "project": self.resource_location + "/project16.png",
  8075. "svg": self.resource_location + "/geometry16.png",
  8076. "dxf": self.resource_location + "/dxf16.png",
  8077. "pdf": self.resource_location + "/pdf32.png",
  8078. "image": self.resource_location + "/image16.png"
  8079. }
  8080. try:
  8081. image_opener = self.image_tool.import_image
  8082. except AttributeError:
  8083. image_opener = None
  8084. openers = {
  8085. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8086. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8087. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8088. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8089. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8090. "document": None,
  8091. 'project': self.open_project,
  8092. 'svg': self.import_svg,
  8093. 'dxf': self.import_dxf,
  8094. 'image': image_opener,
  8095. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8096. }
  8097. # Open recent file for files
  8098. try:
  8099. f = open(self.data_path + '/recent.json')
  8100. except IOError:
  8101. App.log.error("Failed to load recent item list.")
  8102. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8103. return
  8104. try:
  8105. self.recent = json.load(f)
  8106. except json.errors.JSONDecodeError:
  8107. App.log.error("Failed to parse recent item list.")
  8108. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8109. f.close()
  8110. return
  8111. f.close()
  8112. # Open recent file for projects
  8113. try:
  8114. fp = open(self.data_path + '/recent_projects.json')
  8115. except IOError:
  8116. App.log.error("Failed to load recent project item list.")
  8117. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8118. return
  8119. try:
  8120. self.recent_projects = json.load(fp)
  8121. except json.errors.JSONDecodeError:
  8122. App.log.error("Failed to parse recent project item list.")
  8123. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8124. fp.close()
  8125. return
  8126. fp.close()
  8127. # Closure needed to create callbacks in a loop.
  8128. # Otherwise late binding occurs.
  8129. def make_callback(func, fname):
  8130. def opener():
  8131. func(fname)
  8132. return opener
  8133. def reset_recent_files():
  8134. # Reset menu
  8135. self.ui.recent.clear()
  8136. self.recent = []
  8137. try:
  8138. ff = open(self.data_path + '/recent.json', 'w')
  8139. except IOError:
  8140. App.log.error("Failed to open recent items file for writing.")
  8141. return
  8142. json.dump(self.recent, ff)
  8143. def reset_recent_projects():
  8144. # Reset menu
  8145. self.ui.recent_projects.clear()
  8146. self.recent_projects = []
  8147. try:
  8148. frp = open(self.data_path + '/recent_projects.json', 'w')
  8149. except IOError:
  8150. App.log.error("Failed to open recent projects items file for writing.")
  8151. return
  8152. json.dump(self.recent, frp)
  8153. # Reset menu
  8154. self.ui.recent.clear()
  8155. self.ui.recent_projects.clear()
  8156. # Create menu items for projects
  8157. for recent in self.recent_projects:
  8158. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8159. if recent['kind'] == 'project':
  8160. try:
  8161. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8162. # Attach callback
  8163. o = make_callback(openers[recent["kind"]], recent['filename'])
  8164. action.triggered.connect(o)
  8165. self.ui.recent_projects.addAction(action)
  8166. except KeyError:
  8167. App.log.error("Unsupported file type: %s" % recent["kind"])
  8168. # Last action in Recent Files menu is one that Clear the content
  8169. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8170. (_("Clear Recent projects")), self)
  8171. clear_action_proj.triggered.connect(reset_recent_projects)
  8172. self.ui.recent_projects.addSeparator()
  8173. self.ui.recent_projects.addAction(clear_action_proj)
  8174. # Create menu items for files
  8175. for recent in self.recent:
  8176. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8177. if recent['kind'] != 'project':
  8178. try:
  8179. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8180. # Attach callback
  8181. o = make_callback(openers[recent["kind"]], recent['filename'])
  8182. action.triggered.connect(o)
  8183. self.ui.recent.addAction(action)
  8184. except KeyError:
  8185. App.log.error("Unsupported file type: %s" % recent["kind"])
  8186. # Last action in Recent Files menu is one that Clear the content
  8187. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8188. (_("Clear Recent files")), self)
  8189. clear_action.triggered.connect(reset_recent_files)
  8190. self.ui.recent.addSeparator()
  8191. self.ui.recent.addAction(clear_action)
  8192. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8193. # self.ui.menufilerecent.set_submenu(recent_menu)
  8194. # recent_menu.show_all()
  8195. # self.ui.recent.show()
  8196. self.log.debug("Recent items list has been populated.")
  8197. def setup_component_editor(self):
  8198. """
  8199. Default text for the Selected tab when is not taken by the Object UI.
  8200. :return:
  8201. """
  8202. # label = QtWidgets.QLabel("Choose an item from Project")
  8203. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8204. sel_title = QtWidgets.QTextEdit(
  8205. _('<b>Shortcut Key List</b>'))
  8206. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8207. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8208. f_settings = QSettings("Open Source", "FlatCAM")
  8209. if f_settings.contains("notebook_font_size"):
  8210. fsize = f_settings.value('notebook_font_size', type=int)
  8211. else:
  8212. fsize = 12
  8213. tsize = fsize + int(fsize / 2)
  8214. # selected_text = (_('''
  8215. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8216. # </p>
  8217. #
  8218. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8219. # The normal flow when working in FlatCAM is the following:</span></p>
  8220. #
  8221. # <ol>
  8222. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8223. # file into
  8224. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8225. # even dragging and dropping the files on the GUI.<br />
  8226. # <br />
  8227. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8228. # drop of the
  8229. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8230. # &nbsp;</li>
  8231. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8232. # and then
  8233. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8234. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8235. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8236. # <br />
  8237. # If the selection of the object is done on the canvas by single click instead, and the
  8238. # <strong>SELECTED TAB</strong>
  8239. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8240. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8241. # it even if it was out of focus.<br />
  8242. # <br />
  8243. # You can change the parameters in this screen and the flow direction is like this:<br />
  8244. # <br />
  8245. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8246. # <strong> Geometry Object
  8247. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8248. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8249. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8250. # </ol>
  8251. #
  8252. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8253. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8254. # <strong>F3</strong>.</span></p>
  8255. #
  8256. # ''').format(fsize=fsize, tsize=tsize))
  8257. selected_text = '''
  8258. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8259. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8260. {s1}</span></p>
  8261. <ol>
  8262. <li><span style="font-size:{fsize}px">{s2}<br />
  8263. <br />
  8264. {s3}</span><br />
  8265. &nbsp;</li>
  8266. <li><span style="font-size:{fsize}px">{s4}<br />
  8267. &nbsp;</li>
  8268. <br />
  8269. <li><span style="font-size:{fsize}px">{s5}<br />
  8270. &nbsp;</li>
  8271. <br />
  8272. <li><span style="font-size:{fsize}px">{s6}<br />
  8273. <br />
  8274. {s7}</span></li>
  8275. </ol>
  8276. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8277. '''.format(
  8278. title=_("Selected Tab - Choose an Item from Project Tab"),
  8279. subtitle=_("Details"),
  8280. s1=_("The normal flow when working in FlatCAM is the following:"),
  8281. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8282. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8283. "files on the GUI."),
  8284. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8285. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8286. "actions offered within the app."),
  8287. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8288. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8289. "SELECTED TAB will be updated with the object properties according to its kind: "
  8290. "Gerber, Excellon, Geometry or CNCJob object."),
  8291. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8292. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8293. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8294. "the SELECTED TAB and populate it even if it was out of focus."),
  8295. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8296. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8297. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8298. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8299. "(again, done in SELECTED TAB) --> Save GCode."),
  8300. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8301. "or through its own key shortcut: <b>F3</b>."),
  8302. tsize=tsize,
  8303. fsize=fsize
  8304. )
  8305. sel_title.setText(selected_text)
  8306. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8307. self.ui.selected_scroll_area.setWidget(sel_title)
  8308. def setup_obj_classes(self):
  8309. """
  8310. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8311. class.
  8312. :return: None
  8313. """
  8314. FlatCAMObj.app = self
  8315. ObjectCollection.app = self
  8316. Gerber.app = self
  8317. Excellon.app = self
  8318. Geometry.app = self
  8319. CNCjob.app = self
  8320. FCProcess.app = self
  8321. FCProcessContainer.app = self
  8322. OptionsGroupUI.app = self
  8323. def version_check(self):
  8324. """
  8325. Checks for the latest version of the program. Alerts the
  8326. user if theirs is outdated. This method is meant to be run
  8327. in a separate thread.
  8328. :return: None
  8329. """
  8330. self.log.debug("version_check()")
  8331. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8332. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8333. App.version_url,
  8334. str(self.defaults['global_serial']),
  8335. str(self.version),
  8336. str(self.os),
  8337. urllib.parse.urlencode(self.defaults["global_stats"])
  8338. )
  8339. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8340. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8341. # urllib.parse.urlencode(self.defaults["global_stats"])
  8342. else:
  8343. # no_stats dict; just so it won't break things on website
  8344. no_ststs_dict = {}
  8345. no_ststs_dict["global_ststs"] = {}
  8346. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8347. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8348. App.log.debug("Checking for updates @ %s" % full_url)
  8349. # ## Get the data
  8350. try:
  8351. f = urllib.request.urlopen(full_url)
  8352. except Exception:
  8353. # App.log.warning("Failed checking for latest version. Could not connect.")
  8354. self.log.warning("Failed checking for latest version. Could not connect.")
  8355. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8356. return
  8357. try:
  8358. data = json.load(f)
  8359. except Exception as e:
  8360. App.log.error("Could not parse information about latest version.")
  8361. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8362. App.log.debug("json.load(): %s" % str(e))
  8363. f.close()
  8364. return
  8365. f.close()
  8366. # ## Latest version?
  8367. if self.version >= data["version"]:
  8368. App.log.debug("FlatCAM is up to date!")
  8369. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8370. return
  8371. App.log.debug("Newer version available.")
  8372. self.message.emit(
  8373. _("Newer Version Available"),
  8374. '%s<br><br>><b>%s</b><br>%s' % (
  8375. _("There is a newer version of FlatCAM available for download:"),
  8376. str(data["name"]),
  8377. str(data["message"])
  8378. ),
  8379. _("info")
  8380. )
  8381. def on_plotcanvas_setup(self, container=None):
  8382. """
  8383. This is doing the setup for the plot area (canvas).
  8384. :param container: QT Widget where to install the canvas
  8385. :return: None
  8386. """
  8387. if container:
  8388. plot_container = container
  8389. else:
  8390. plot_container = self.ui.right_layout
  8391. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8392. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8393. self.is_legacy = True
  8394. self.defaults["global_graphic_engine"] = "2D"
  8395. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8396. else:
  8397. try:
  8398. self.plotcanvas = PlotCanvas(plot_container, self)
  8399. except Exception as er:
  8400. msg_txt = traceback.format_exc()
  8401. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8402. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8403. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8404. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8405. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8406. msg += msg_txt
  8407. self.inform.emit(msg)
  8408. return 'fail'
  8409. # So it can receive key presses
  8410. self.plotcanvas.native.setFocus()
  8411. if self.is_legacy is False:
  8412. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8413. # Set the mouse button for panning
  8414. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8415. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8416. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8417. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8418. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8419. # Keys over plot enabled
  8420. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8421. if self.defaults['global_cursor_type'] == 'small':
  8422. self.app_cursor = self.plotcanvas.new_cursor()
  8423. else:
  8424. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8425. if self.ui.grid_snap_btn.isChecked():
  8426. self.app_cursor.enabled = True
  8427. else:
  8428. self.app_cursor.enabled = False
  8429. if self.is_legacy is False:
  8430. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8431. else:
  8432. # will use the default Matplotlib axes
  8433. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8434. def on_zoom_fit(self, event):
  8435. """
  8436. Callback for zoom-fit request. This can be either from the corresponding
  8437. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8438. with axes limits from the geometry bounds of all objects.
  8439. :param event: Ignored.
  8440. :return: None
  8441. """
  8442. if self.is_legacy is False:
  8443. self.plotcanvas.fit_view()
  8444. else:
  8445. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8446. width = xmax - xmin
  8447. height = ymax - ymin
  8448. xmin -= 0.05 * width
  8449. xmax += 0.05 * width
  8450. ymin -= 0.05 * height
  8451. ymax += 0.05 * height
  8452. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8453. def on_zoom_in(self):
  8454. """
  8455. Callback for zoom-in request.
  8456. :return:
  8457. """
  8458. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8459. def on_zoom_out(self):
  8460. """
  8461. Callback for zoom-out request.
  8462. :return:
  8463. """
  8464. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8465. def disable_all_plots(self):
  8466. self.defaults.report_usage("disable_all_plots()")
  8467. self.disable_plots(self.collection.get_list())
  8468. self.inform.emit('[success] %s' %
  8469. _("All plots disabled."))
  8470. def disable_other_plots(self):
  8471. self.defaults.report_usage("disable_other_plots()")
  8472. self.disable_plots(self.collection.get_non_selected())
  8473. self.inform.emit('[success] %s' %
  8474. _("All non selected plots disabled."))
  8475. def enable_all_plots(self):
  8476. self.defaults.report_usage("enable_all_plots()")
  8477. self.enable_plots(self.collection.get_list())
  8478. self.inform.emit('[success] %s' %
  8479. _("All plots enabled."))
  8480. def on_enable_sel_plots(self):
  8481. log.debug("App.on_enable_sel_plot()")
  8482. object_list = self.collection.get_selected()
  8483. self.enable_plots(objects=object_list)
  8484. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8485. def on_disable_sel_plots(self):
  8486. log.debug("App.on_disable_sel_plot()")
  8487. # self.inform.emit(_("Disabling plots ..."))
  8488. object_list = self.collection.get_selected()
  8489. self.disable_plots(objects=object_list)
  8490. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8491. def enable_plots(self, objects):
  8492. """
  8493. Enable plots
  8494. :param objects: list of Objects to be enabled
  8495. :return:
  8496. """
  8497. log.debug("Enabling plots ...")
  8498. # self.inform.emit(_("Working ..."))
  8499. for obj in objects:
  8500. if obj.options['plot'] is False:
  8501. obj.options.set_change_callback(lambda x: None)
  8502. obj.options['plot'] = True
  8503. try:
  8504. # only the Gerber obj has on_plot_cb_click() method
  8505. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8506. # disable this cb while disconnected,
  8507. # in case the operation takes time the user is not allowed to change it
  8508. obj.ui.plot_cb.setDisabled(True)
  8509. except AttributeError:
  8510. pass
  8511. obj.set_form_item("plot")
  8512. try:
  8513. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8514. obj.ui.plot_cb.setDisabled(False)
  8515. except AttributeError:
  8516. pass
  8517. obj.options.set_change_callback(obj.on_options_change)
  8518. def worker_task(objs):
  8519. with self.proc_container.new(_("Enabling plots ...")):
  8520. for plot_obj in objs:
  8521. # obj.options['plot'] = True
  8522. if isinstance(plot_obj, CNCJobObject):
  8523. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8524. else:
  8525. plot_obj.plot(visible=True)
  8526. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8527. # self.plots_updated.emit()
  8528. def disable_plots(self, objects):
  8529. """
  8530. Disables plots
  8531. :param objects: list of Objects to be disabled
  8532. :return:
  8533. """
  8534. # if no objects selected then do nothing
  8535. if not self.collection.get_selected():
  8536. return
  8537. log.debug("Disabling plots ...")
  8538. # self.inform.emit(_("Working ..."))
  8539. for obj in objects:
  8540. if obj.options['plot'] is True:
  8541. obj.options.set_change_callback(lambda x: None)
  8542. obj.options['plot'] = False
  8543. try:
  8544. # only the Gerber obj has on_plot_cb_click() method
  8545. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8546. obj.ui.plot_cb.setDisabled(True)
  8547. except AttributeError:
  8548. pass
  8549. obj.set_form_item("plot")
  8550. try:
  8551. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8552. obj.ui.plot_cb.setDisabled(False)
  8553. except AttributeError:
  8554. pass
  8555. obj.options.set_change_callback(obj.on_options_change)
  8556. try:
  8557. self.delete_selection_shape()
  8558. except Exception as e:
  8559. log.debug("App.disable_plots() --> %s" % str(e))
  8560. # self.plots_updated.emit()
  8561. def worker_task(objs):
  8562. with self.proc_container.new(_("Disabling plots ...")):
  8563. for plot_obj in objs:
  8564. # obj.options['plot'] = True
  8565. if isinstance(plot_obj, CNCJobObject):
  8566. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8567. else:
  8568. plot_obj.plot(visible=False)
  8569. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8570. def toggle_plots(self, objects):
  8571. """
  8572. Toggle plots visibility
  8573. :param objects: list of Objects for which to be toggled the visibility
  8574. :return: None
  8575. """
  8576. # if no objects selected then do nothing
  8577. if not self.collection.get_selected():
  8578. return
  8579. log.debug("Toggling plots ...")
  8580. self.inform.emit(_("Working ..."))
  8581. for obj in objects:
  8582. if obj.options['plot'] is False:
  8583. obj.options['plot'] = True
  8584. else:
  8585. obj.options['plot'] = False
  8586. self.plots_updated.emit()
  8587. def clear_plots(self):
  8588. """
  8589. Clear the plots
  8590. :return: None
  8591. """
  8592. objects = self.collection.get_list()
  8593. for obj in objects:
  8594. obj.clear(obj == objects[-1])
  8595. # Clear pool to free memory
  8596. self.clear_pool()
  8597. def on_set_color_action_triggered(self):
  8598. """
  8599. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8600. :return:
  8601. """
  8602. new_color = self.defaults['gerber_plot_fill']
  8603. clicked_action = self.sender()
  8604. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8605. act_name = clicked_action.text()
  8606. sel_obj_list = self.collection.get_selected()
  8607. if not sel_obj_list:
  8608. return
  8609. # a default value, I just chose this one
  8610. alpha_level = 'BF'
  8611. for sel_obj in sel_obj_list:
  8612. if sel_obj.kind == 'excellon':
  8613. alpha_level = str(hex(
  8614. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8615. elif sel_obj.kind == 'gerber':
  8616. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8617. elif sel_obj.kind == 'geometry':
  8618. alpha_level = 'FF'
  8619. else:
  8620. log.debug(
  8621. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8622. continue
  8623. sel_obj.alpha_level = alpha_level
  8624. if act_name == _('Red'):
  8625. new_color = '#FF0000' + alpha_level
  8626. if act_name == _('Blue'):
  8627. new_color = '#0000FF' + alpha_level
  8628. if act_name == _('Yellow'):
  8629. new_color = '#FFDF00' + alpha_level
  8630. if act_name == _('Green'):
  8631. new_color = '#00FF00' + alpha_level
  8632. if act_name == _('Purple'):
  8633. new_color = '#FF00FF' + alpha_level
  8634. if act_name == _('Brown'):
  8635. new_color = '#A52A2A' + alpha_level
  8636. if act_name == _('White'):
  8637. new_color = '#FFFFFF' + alpha_level
  8638. if act_name == _('Black'):
  8639. new_color = '#000000' + alpha_level
  8640. if act_name == _('Custom'):
  8641. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8642. c_dialog = QtWidgets.QColorDialog()
  8643. plot_fill_color = c_dialog.getColor(initial=new_color)
  8644. if plot_fill_color.isValid() is False:
  8645. return
  8646. new_color = str(plot_fill_color.name()) + alpha_level
  8647. if act_name == _("Default"):
  8648. for sel_obj in sel_obj_list:
  8649. if sel_obj.kind == 'excellon':
  8650. new_color = self.defaults['excellon_plot_fill']
  8651. new_line_color = self.defaults['excellon_plot_line']
  8652. elif sel_obj.kind == 'gerber':
  8653. new_color = self.defaults['gerber_plot_fill']
  8654. new_line_color = self.defaults['gerber_plot_line']
  8655. elif sel_obj.kind == 'geometry':
  8656. new_color = self.defaults['geometry_plot_line']
  8657. new_line_color = self.defaults['geometry_plot_line']
  8658. else:
  8659. log.debug(
  8660. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8661. continue
  8662. sel_obj.fill_color = new_color
  8663. sel_obj.outline_color = new_line_color
  8664. sel_obj.shapes.redraw(
  8665. update_colors=(new_color, new_line_color)
  8666. )
  8667. return
  8668. if act_name == _("Opacity"):
  8669. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8670. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8671. if ok_button:
  8672. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8673. for sel_obj in sel_obj_list:
  8674. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8675. sel_obj.shapes.redraw(
  8676. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8677. )
  8678. return
  8679. new_line_color = color_variant(new_color[:7], 0.7)
  8680. if act_name == _("White"):
  8681. new_line_color = color_variant("#dedede", 0.7)
  8682. for sel_obj in sel_obj_list:
  8683. sel_obj.fill_color = new_color
  8684. sel_obj.outline_color = new_line_color
  8685. sel_obj.shapes.redraw(
  8686. update_colors=(new_color, new_line_color)
  8687. )
  8688. def on_grid_snap_triggered(self, state):
  8689. """
  8690. :param state: A parameter with the state of the grid, boolean
  8691. :return:
  8692. """
  8693. if state:
  8694. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8695. else:
  8696. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8697. self.ui.snap_infobar_label.clicked_state = state
  8698. def on_grid_icon_snap_clicked(self):
  8699. """
  8700. Slot called by clicking a GUI element, in this case a FCLabel
  8701. :return:
  8702. """
  8703. if isinstance(self.sender(), FCLabel):
  8704. self.ui.grid_snap_btn.trigger()
  8705. def generate_cnc_job(self, objects):
  8706. """
  8707. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8708. :param objects: Selected objects in the Project Tab
  8709. :return:
  8710. """
  8711. self.defaults.report_usage("generate_cnc_job()")
  8712. # for obj in objects:
  8713. # obj.generatecncjob()
  8714. for obj in objects:
  8715. obj.on_generatecnc_button_click()
  8716. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8717. """
  8718. Saves the current project to the specified file.
  8719. :param filename: Name of the file in which to save.
  8720. :type filename: str
  8721. :param quit_action: if the project saving will be followed by an app quit; boolean
  8722. :param silent: if True will not display status messages
  8723. :param from_tcl True is run from Tcl Shell
  8724. :return: None
  8725. """
  8726. self.log.debug("save_project()")
  8727. self.save_in_progress = True
  8728. with self.proc_container.new(_("Saving FlatCAM Project")):
  8729. # Capture the latest changes
  8730. # Current object
  8731. try:
  8732. current_object = self.collection.get_active()
  8733. if current_object:
  8734. current_object.read_form()
  8735. except Exception as e:
  8736. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8737. pass
  8738. # Serialize the whole project
  8739. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8740. "options": self.options,
  8741. "version": self.version}
  8742. if self.defaults["global_save_compressed"] is True:
  8743. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8744. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8745. # # Write
  8746. f.write(g)
  8747. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8748. else:
  8749. # Open file
  8750. try:
  8751. f = open(filename, 'w')
  8752. except IOError:
  8753. App.log.error("Failed to open file for saving: %s", filename)
  8754. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8755. return
  8756. # Write
  8757. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8758. f.close()
  8759. # verification of the saved project
  8760. # Open and parse
  8761. try:
  8762. saved_f = open(filename, 'r')
  8763. except IOError:
  8764. if silent is False:
  8765. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8766. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8767. return
  8768. try:
  8769. saved_d = json.load(saved_f, object_hook=dict2obj)
  8770. except Exception:
  8771. if silent is False:
  8772. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8773. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8774. f.close()
  8775. return
  8776. saved_f.close()
  8777. if silent is False:
  8778. if 'version' in saved_d:
  8779. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8780. else:
  8781. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8782. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8783. tb_settings = QSettings("Open Source", "FlatCAM")
  8784. lock_state = self.ui.lock_action.isChecked()
  8785. tb_settings.setValue('toolbar_lock', lock_state)
  8786. # This will write the setting to the platform specific storage.
  8787. del tb_settings
  8788. # if quit:
  8789. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8790. # t.start()
  8791. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8792. def start_delayed_quit(self, delay, filename, should_quit=None):
  8793. """
  8794. :param delay: period of checking if project file size is more than zero; in seconds
  8795. :param filename: the name of the project file to be checked periodically for size more than zero
  8796. :param should_quit: if the task finished will be followed by an app quit; boolean
  8797. :return:
  8798. """
  8799. to_quit = should_quit
  8800. self.save_timer = QtCore.QTimer()
  8801. self.save_timer.setInterval(delay)
  8802. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8803. self.save_timer.start()
  8804. def check_project_file_size(self, filename, should_quit=None):
  8805. """
  8806. :param filename: the name of the project file to be checked periodically for size more than zero
  8807. :param should_quit: will quit the app if True; boolean
  8808. :return:
  8809. """
  8810. try:
  8811. if os.stat(filename).st_size > 0:
  8812. self.save_in_progress = False
  8813. self.save_timer.stop()
  8814. if should_quit:
  8815. self.app_quit.emit()
  8816. except Exception:
  8817. traceback.print_exc()
  8818. def save_project_auto(self):
  8819. """
  8820. Called periodically to save the project.
  8821. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8822. # progress.
  8823. :return:
  8824. """
  8825. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8826. self.on_file_saveproject()
  8827. def save_project_auto_update(self):
  8828. """
  8829. Update the auto save time interval value.
  8830. :return:
  8831. """
  8832. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8833. try:
  8834. if self.autosave_timer.isActive():
  8835. self.autosave_timer.stop()
  8836. except Exception:
  8837. pass
  8838. if self.defaults['global_autosave'] is True:
  8839. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8840. self.autosave_timer.start()
  8841. def on_plotarea_tab_closed(self, tab_idx):
  8842. """
  8843. :param tab_idx: Index of the Tab from the plotarea that was closed
  8844. :return:
  8845. """
  8846. widget = self.ui.plot_tab_area.widget(tab_idx)
  8847. if widget is not None:
  8848. widget.deleteLater()
  8849. self.ui.plot_tab_area.removeTab(tab_idx)
  8850. def on_options_app2project(self):
  8851. """
  8852. Callback for Options->Transfer Options->App=>Project. Copies options
  8853. from application defaults to project defaults.
  8854. :return: None
  8855. """
  8856. self.defaults.report_usage("on_options_app2project")
  8857. self.preferencesUiManager.defaults_read_form()
  8858. self.options.update(self.defaults)
  8859. def toggle_shell(self):
  8860. """
  8861. Toggle shell: if is visible close it, if it is closed then open it
  8862. :return: None
  8863. """
  8864. self.defaults.report_usage("toggle_shell()")
  8865. if self.ui.shell_dock.isVisible():
  8866. self.ui.shell_dock.hide()
  8867. self.plotcanvas.native.setFocus()
  8868. else:
  8869. self.ui.shell_dock.show()
  8870. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8871. # self.shell._edit.setFocus()
  8872. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8873. # HACK - simulate a mouse click - alternative
  8874. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8875. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8876. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8877. # no_km)
  8878. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8879. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8880. # no_km)
  8881. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8882. def on_toggle_shell_from_settings(self, state):
  8883. """
  8884. Toggle shell: if is visible close it, if it is closed then open it
  8885. :return: None
  8886. """
  8887. self.defaults.report_usage("on_toggle_shell_from_settings()")
  8888. if state is True:
  8889. if not self.ui.shell_dock.isVisible():
  8890. self.ui.shell_dock.show()
  8891. else:
  8892. if self.ui.shell_dock.isVisible():
  8893. self.ui.shell_dock.hide()
  8894. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8895. """
  8896. Shows a message on the FlatCAM Shell
  8897. :param msg: Message to display.
  8898. :param show: Opens the shell.
  8899. :param error: Shows the message as an error.
  8900. :param warning: Shows the message as an warning.
  8901. :param success: Shows the message as an success.
  8902. :param selected: Indicate that something was selected on canvas
  8903. :return: None
  8904. """
  8905. if show:
  8906. self.ui.shell_dock.show()
  8907. try:
  8908. if error:
  8909. self.shell.append_error(msg + "\n")
  8910. elif warning:
  8911. self.shell.append_warning(msg + "\n")
  8912. elif success:
  8913. self.shell.append_success(msg + "\n")
  8914. elif selected:
  8915. self.shell.append_selected(msg + "\n")
  8916. else:
  8917. self.shell.append_output(msg + "\n")
  8918. except AttributeError:
  8919. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8920. class ArgsThread(QtCore.QObject):
  8921. open_signal = pyqtSignal(list)
  8922. start = pyqtSignal()
  8923. if sys.platform == 'win32':
  8924. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8925. else:
  8926. address = ('/tmp/testipc', 'AF_UNIX')
  8927. def __init__(self):
  8928. super(ArgsThread, self).__init__()
  8929. self.listener = None
  8930. self.start.connect(self.run)
  8931. def my_loop(self, address):
  8932. try:
  8933. self.listener = Listener(*address)
  8934. while True:
  8935. conn = self.listener.accept()
  8936. self.serve(conn)
  8937. except socket.error:
  8938. try:
  8939. conn = Client(*address)
  8940. conn.send(sys.argv)
  8941. conn.send('close')
  8942. # close the current instance only if there are args
  8943. if len(sys.argv) > 1:
  8944. try:
  8945. self.listener.close()
  8946. except Exception:
  8947. pass
  8948. sys.exit()
  8949. except ConnectionRefusedError:
  8950. if sys.platform == 'win32':
  8951. pass
  8952. else:
  8953. os.system('rm /tmp/testipc')
  8954. self.listener = Listener(*address)
  8955. while True:
  8956. conn = self.listener.accept()
  8957. self.serve(conn)
  8958. def serve(self, conn):
  8959. while True:
  8960. msg = conn.recv()
  8961. if msg == 'close':
  8962. break
  8963. self.open_signal.emit(msg)
  8964. conn.close()
  8965. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8966. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8967. @pyqtSlot()
  8968. def run(self):
  8969. self.my_loop(self.address)
  8970. # end of file